diff --git a/.gitattributes b/.gitattributes index 74f5f4a6409..811a89b5493 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1 +1,2 @@ -*.js linguist-language=TypeScript \ No newline at end of file +*.js linguist-language=TypeScript +* -text diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 5de2bd87e63..41a16fff3eb 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -31,44 +31,75 @@ Your pull request should: ## Running the Tests To run all tests, invoke the runtests target using jake: -`jake runtests` +```Shell +jake runtests +``` This run will all tests; to run only a specific subset of tests, use: -`jake runtests tests=` +```Shell +jake runtests tests= +``` e.g. to run all compiler baseline tests: -`jake runtests tests=compiler` +```Shell +jake runtests tests=compiler +``` -or to run specifc test:tests\cases\compiler\2dArrays.ts +or to run specifc test: `tests\cases\compiler\2dArrays.ts` -`jake runtests tests=2dArrays` +```Shell +jake runtests tests=2dArrays +``` ## Adding a Test -To add a new testcase, simply place a .ts file in tests\cases\compiler containing code that exemplifies the bugfix or change you are making. +To add a new testcase, simply place a `.ts` file in `tests\cases\compiler` containing code that exemplifies the bugfix or change you are making. -These files support metadata tags in the format // @name: value . The supported names and values are: +These files support metadata tags in the format `// @metaDataName: value`. The supported names and values are: -* comments, sourcemap, noimplicitany, declaration: true or false (corresponds to the compiler command-line options of the same name) -* target: ES3 or ES5 (same as compiler) -* out, outDir: path (same as compiler) -* module: local, commonjs, or amd (local corresponds to not passing any compiler --module flag) +* `comments`, `sourcemap`, `noimplicitany`, `declaration`: true or false (corresponds to the compiler command-line options of the same name) +* `target`: ES3 or ES5 (same as compiler) +* `out`, outDir: path (same as compiler) +* `module`: local, commonjs, or amd (local corresponds to not passing any compiler --module flag) +* `fileName`: path + * These tags delimit sections of a file to be used as separate compilation units. They are useful for tests relating to modules. See below for examples. -**Note** that if you have a test corresponding to a specific spec compliance item, you can place it in tests\cases\conformance in an appropriately-named subfolder. +**Note** that if you have a test corresponding to a specific spec compliance item, you can place it in `tests\cases\conformance` in an appropriately-named subfolder. **Note** that filenames here must be distinct from all other compiler testcase names, so you may have to work a bit to find a unique name if it's something common. +### Tests for multiple files + +When one needs to test for scenarios which require multiple files, it is useful to use the `fileName` metadata tag as such: + +```TypeScript +// @fileName: file1.ts +export function f() { +} + +// @fileName: file2.ts +import { f as g } from "file1"; + +var x = g(); +``` + +One can also write a project test, but it is slightly more involved. + ## Managing the Baselines -Compiler testcases generate baselines that track the emitted .js, the errors produced by the compiler, and the type of each expression in the file. Additionally, some testcases opt in to baselining the source map output. +Compiler testcases generate baselines that track the emitted `.js`, the errors produced by the compiler, and the type of each expression in the file. Additionally, some testcases opt in to baselining the source map output. When a change in the baselines is detected, the test will fail. To inspect changes vs the expected baselines, use -`jake diff` +```Shell +jake diff +``` After verifying that the changes in the baselines are correct, run -`jake baseline-accept` +```Shell +jake baseline-accept +``` -to establish the new baselines as the desired behavior. This will change the files in tests\baselines\reference, which should be included as part of your commit. It's important to carefully validate changes in the baselines. +to establish the new baselines as the desired behavior. This will change the files in `tests\baselines\reference`, which should be included as part of your commit. It's important to carefully validate changes in the baselines. **Note** that baseline-accept should only be run after a full test run! Accepting baselines after running a subset of tests will delete baseline files for the tests that didn't run. diff --git a/Jakefile.js b/Jakefile.js index afe0ffd3ce5..07a2ade06a6 100644 --- a/Jakefile.js +++ b/Jakefile.js @@ -105,6 +105,14 @@ var serverSources = [ return path.join(serverDirectory, f); }); +var languageServiceLibrarySources = [ + "editorServices.ts", + "protocol.d.ts", + "session.ts" +].map(function (f) { + return path.join(serverDirectory, f); +}).concat(servicesSources); + var harnessSources = [ "harness.ts", "sourceMapRecorder.ts", @@ -129,7 +137,8 @@ var harnessSources = [ "services/preProcessFile.ts", "services/patternMatcher.ts", "versionCache.ts", - "convertToBase64.ts" + "convertToBase64.ts", + "transpile.ts" ].map(function (f) { return path.join(unittestsDirectory, f); })).concat([ @@ -148,7 +157,7 @@ var librarySourceMap = [ { target: "lib.scriptHost.d.ts", sources: ["importcore.d.ts", "scriptHost.d.ts"], }, { target: "lib.d.ts", sources: ["core.d.ts", "extensions.d.ts", "intl.d.ts", "dom.generated.d.ts", "webworker.importscripts.d.ts", "scriptHost.d.ts"], }, { target: "lib.core.es6.d.ts", sources: ["core.d.ts", "es6.d.ts"]}, - { target: "lib.es6.d.ts", sources: ["core.d.ts", "es6.d.ts", "intl.d.ts", "dom.generated.d.ts", "webworker.importscripts.d.ts", "scriptHost.d.ts"]}, + { target: "lib.es6.d.ts", sources: ["core.d.ts", "es6.d.ts", "intl.d.ts", "dom.generated.d.ts", "dom.es6.d.ts", "webworker.importscripts.d.ts", "scriptHost.d.ts"] }, ]; var libraryTargets = librarySourceMap.map(function (f) { @@ -360,7 +369,7 @@ compileFile(servicesFile, servicesSources,[builtLocalDirectory, copyright].conca // Create the node definition file by replacing 'ts' module with '"typescript"' as a module. jake.cpR(standaloneDefinitionsFile, nodeDefinitionsFile, {silent: true}); var definitionFileContents = fs.readFileSync(nodeDefinitionsFile).toString(); - definitionFileContents = definitionFileContents.replace(/declare module ts/g, 'declare module "typescript"'); + definitionFileContents = definitionFileContents.replace(/declare (namespace|module) ts/g, 'declare module "typescript"'); fs.writeFileSync(nodeDefinitionsFile, definitionFileContents); }); @@ -368,6 +377,20 @@ compileFile(servicesFile, servicesSources,[builtLocalDirectory, copyright].conca var serverFile = path.join(builtLocalDirectory, "tsserver.js"); compileFile(serverFile, serverSources,[builtLocalDirectory, copyright].concat(serverSources), /*prefixes*/ [copyright], /*useBuiltCompiler*/ true); +var lsslFile = path.join(builtLocalDirectory, "tslssl.js"); +compileFile( + lsslFile, + languageServiceLibrarySources, + [builtLocalDirectory, copyright].concat(languageServiceLibrarySources), + /*prefixes*/ [copyright], + /*useBuiltCompiler*/ true, + /*noOutFile*/ false, + /*generateDeclarations*/ true); + +// Local target to build the language service server library +desc("Builds language service server library"); +task("lssl", [lsslFile]); + // Local target to build the compiler and services desc("Builds the full compiler and services"); task("local", ["generate-diagnostics", "lib", tscFile, servicesFile, nodeDefinitionsFile, serverFile]); @@ -504,9 +527,9 @@ function cleanTestDirs() { } // used to pass data from jake command line directly to run.js -function writeTestConfigFile(tests, testConfigFile) { +function writeTestConfigFile(tests, light, testConfigFile) { console.log('Running test(s): ' + tests); - var testConfigContents = '{\n' + '\ttest: [\'' + tests + '\']\n}'; + var testConfigContents = JSON.stringify({ test: [tests], light: light }); fs.writeFileSync('test.config', testConfigContents); } @@ -522,13 +545,14 @@ task("runtests", ["tests", builtLocalDirectory], function() { cleanTestDirs(); host = "mocha" tests = process.env.test || process.env.tests || process.env.t; + var light = process.env.light || false; var testConfigFile = 'test.config'; if(fs.existsSync(testConfigFile)) { fs.unlinkSync(testConfigFile); } - if(tests) { - writeTestConfigFile(tests, testConfigFile); + if(tests || light) { + writeTestConfigFile(tests, light, testConfigFile); } if (tests && tests.toLocaleLowerCase() === "rwc") { @@ -571,12 +595,13 @@ task("runtests-browser", ["tests", "browserify", builtLocalDirectory], function( port = process.env.port || process.env.p || '8888'; browser = process.env.browser || process.env.b || "IE"; tests = process.env.test || process.env.tests || process.env.t; + var light = process.env.light || false; var testConfigFile = 'test.config'; if(fs.existsSync(testConfigFile)) { fs.unlinkSync(testConfigFile); } - if(tests) { - writeTestConfigFile(tests, testConfigFile); + if(tests || light) { + writeTestConfigFile(tests, light, testConfigFile); } tests = tests ? tests : ''; diff --git a/README.md b/README.md index ee32547ca95..31b1a21f64d 100644 --- a/README.md +++ b/README.md @@ -5,8 +5,8 @@ [![Downloads](http://img.shields.io/npm/dm/TypeScript.svg)](https://npmjs.org/package/typescript) # TypeScript - -[![Join the chat at https://gitter.im/Microsoft/TypeScript](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/Microsoft/TypeScript?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) + +[![Join the chat at https://gitter.im/Microsoft/TypeScript](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/Microsoft/TypeScript?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) [TypeScript](http://www.typescriptlang.org/) is a language for application-scale JavaScript. TypeScript adds optional types, classes, and modules to JavaScript. TypeScript supports tools for large-scale JavaScript applications for any browser, for any host, on any OS. TypeScript compiles to readable, standards-based JavaScript. Try it out at the [playground](http://www.typescriptlang.org/Playground), and stay up to date via [our blog](http://blogs.msdn.com/typescript) and [twitter account](https://twitter.com/typescriptlang). @@ -31,7 +31,7 @@ There are many ways to [contribute](https://github.com/Microsoft/TypeScript/blob ## Building -In order to build the TypeScript compiler, ensure that you have [Git](http://git-scm.com/downloads) and [Node.js](http://nodejs.org/) installed. Note that you need to have autocrlf off as we track whitespace changes (`git config --global core.autocrlf false`). +In order to build the TypeScript compiler, ensure that you have [Git](http://git-scm.com/downloads) and [Node.js](http://nodejs.org/) installed. Clone a copy of the repo: diff --git a/bin/lib.core.d.ts b/bin/lib.core.d.ts index fd048630ca1..af876765ab4 100644 --- a/bin/lib.core.d.ts +++ b/bin/lib.core.d.ts @@ -1165,7 +1165,7 @@ interface ArrayConstructor { (arrayLength?: number): any[]; (arrayLength: number): T[]; (...items: T[]): T[]; - isArray(arg: any): boolean; + isArray(arg: any): arg is Array; prototype: Array; } diff --git a/bin/lib.core.es6.d.ts b/bin/lib.core.es6.d.ts index 86e2fa3ad70..1ee111caa9b 100644 --- a/bin/lib.core.es6.d.ts +++ b/bin/lib.core.es6.d.ts @@ -1165,7 +1165,7 @@ interface ArrayConstructor { (arrayLength?: number): any[]; (arrayLength: number): T[]; (...items: T[]): T[]; - isArray(arg: any): boolean; + isArray(arg: any): arg is Array; prototype: Array; } @@ -1502,6 +1502,11 @@ interface Array { copyWithin(target: number, start: number, end?: number): T[]; } +interface IArguments { + /** Iterator */ + [Symbol.iterator](): IterableIterator; +} + interface ArrayConstructor { /** * Creates an array from an array-like object. @@ -1686,14 +1691,6 @@ interface GeneratorFunctionConstructor { } declare var GeneratorFunction: GeneratorFunctionConstructor; -interface Generator extends IterableIterator { - next(value?: any): IteratorResult; - throw(exception: any): IteratorResult; - return(value: T): IteratorResult; - [Symbol.iterator](): Generator; - [Symbol.toStringTag]: string; -} - interface Math { /** * Returns the number of leading zero bits in the 32-bit binary representation of a number. diff --git a/bin/lib.d.ts b/bin/lib.d.ts index e583f1ac783..63a8adbeda4 100644 --- a/bin/lib.d.ts +++ b/bin/lib.d.ts @@ -1165,7 +1165,7 @@ interface ArrayConstructor { (arrayLength?: number): any[]; (arrayLength: number): T[]; (...items: T[]): T[]; - isArray(arg: any): boolean; + isArray(arg: any): arg is Array; prototype: Array; } @@ -3531,6 +3531,11 @@ declare module Intl { currency?: string; currencyDisplay?: string; useGrouping?: boolean; + minimumintegerDigits?: number; + minimumFractionDigits?: number; + maximumFractionDigits?: number; + minimumSignificantDigits?: number; + maximumSignificantDigits?: number; } interface ResolvedNumberFormatOptions { @@ -3552,10 +3557,10 @@ declare module Intl { resolvedOptions(): ResolvedNumberFormatOptions; } var NumberFormat: { - new (locales?: string[], options?: NumberFormatOptions): Collator; - new (locale?: string, options?: NumberFormatOptions): Collator; - (locales?: string[], options?: NumberFormatOptions): Collator; - (locale?: string, options?: NumberFormatOptions): Collator; + new (locales?: string[], options?: NumberFormatOptions): NumberFormat; + new (locale?: string, options?: NumberFormatOptions): NumberFormat; + (locales?: string[], options?: NumberFormatOptions): NumberFormat; + (locale?: string, options?: NumberFormatOptions): NumberFormat; supportedLocalesOf(locales: string[], options?: NumberFormatOptions): string[]; supportedLocalesOf(locale: string, options?: NumberFormatOptions): string[]; } @@ -3593,14 +3598,14 @@ declare module Intl { } interface DateTimeFormat { - format(date: number): string; + format(date?: Date | number): string; resolvedOptions(): ResolvedDateTimeFormatOptions; } var DateTimeFormat: { - new (locales?: string[], options?: DateTimeFormatOptions): Collator; - new (locale?: string, options?: DateTimeFormatOptions): Collator; - (locales?: string[], options?: DateTimeFormatOptions): Collator; - (locale?: string, options?: DateTimeFormatOptions): Collator; + new (locales?: string[], options?: DateTimeFormatOptions): DateTimeFormat; + new (locale?: string, options?: DateTimeFormatOptions): DateTimeFormat; + (locales?: string[], options?: DateTimeFormatOptions): DateTimeFormat; + (locale?: string, options?: DateTimeFormatOptions): DateTimeFormat; supportedLocalesOf(locales: string[], options?: DateTimeFormatOptions): string[]; supportedLocalesOf(locale: string, options?: DateTimeFormatOptions): string[]; } @@ -11335,10 +11340,10 @@ declare var MediaQueryList: { interface MediaSource extends EventTarget { activeSourceBuffers: SourceBufferList; duration: number; - readyState: string; + readyState: number; sourceBuffers: SourceBufferList; addSourceBuffer(type: string): SourceBuffer; - endOfStream(error?: string): void; + endOfStream(error?: number): void; removeSourceBuffer(sourceBuffer: SourceBuffer): void; } @@ -12067,7 +12072,7 @@ declare var PopStateEvent: { interface Position { coords: Coordinates; - timestamp: Date; + timestamp: number; } declare var Position: { @@ -14748,9 +14753,17 @@ interface WebGLRenderingContext { stencilMaskSeparate(face: number, mask: number): void; stencilOp(fail: number, zfail: number, zpass: number): void; stencilOpSeparate(face: number, fail: number, zfail: number, zpass: number): void; + texImage2D(target: number, level: number, internalformat: number, width: number, height: number, border: number, format: number, type: number, pixels: ArrayBufferView): void; + texImage2D(target: number, level: number, internalformat: number, format: number, type: number, image: HTMLImageElement): void; + texImage2D(target: number, level: number, internalformat: number, format: number, type: number, canvas: HTMLCanvasElement): void; + texImage2D(target: number, level: number, internalformat: number, format: number, type: number, video: HTMLVideoElement): void; texImage2D(target: number, level: number, internalformat: number, format: number, type: number, pixels: ImageData): void; texParameterf(target: number, pname: number, param: number): void; texParameteri(target: number, pname: number, param: number): void; + texSubImage2D(target: number, level: number, xoffset: number, yoffset: number, width: number, height: number, format: number, type: number, pixels: ArrayBufferView): void; + texSubImage2D(target: number, level: number, xoffset: number, yoffset: number, format: number, type: number, image: HTMLImageElement): void; + texSubImage2D(target: number, level: number, xoffset: number, yoffset: number, format: number, type: number, canvas: HTMLCanvasElement): void; + texSubImage2D(target: number, level: number, xoffset: number, yoffset: number, format: number, type: number, video: HTMLVideoElement): void; texSubImage2D(target: number, level: number, xoffset: number, yoffset: number, format: number, type: number, pixels: ImageData): void; uniform1f(location: WebGLUniformLocation, x: number): void; uniform1fv(location: WebGLUniformLocation, v: any): void; @@ -15990,10 +16003,11 @@ interface DocumentEvent { createEvent(eventInterface:"AriaRequestEvent"): AriaRequestEvent; createEvent(eventInterface:"AudioProcessingEvent"): AudioProcessingEvent; createEvent(eventInterface:"BeforeUnloadEvent"): BeforeUnloadEvent; + createEvent(eventInterface:"ClipboardEvent"): ClipboardEvent; createEvent(eventInterface:"CloseEvent"): CloseEvent; createEvent(eventInterface:"CommandEvent"): CommandEvent; createEvent(eventInterface:"CompositionEvent"): CompositionEvent; - createEvent(eventInterface: "CustomEvent"): CustomEvent; + createEvent(eventInterface:"CustomEvent"): CustomEvent; createEvent(eventInterface:"DeviceMotionEvent"): DeviceMotionEvent; createEvent(eventInterface:"DeviceOrientationEvent"): DeviceOrientationEvent; createEvent(eventInterface:"DragEvent"): DragEvent; @@ -16016,8 +16030,6 @@ interface DocumentEvent { createEvent(eventInterface:"MouseEvent"): MouseEvent; createEvent(eventInterface:"MouseEvents"): MouseEvent; createEvent(eventInterface:"MouseWheelEvent"): MouseWheelEvent; - createEvent(eventInterface:"MSGestureEvent"): MSGestureEvent; - createEvent(eventInterface:"MSPointerEvent"): MSPointerEvent; createEvent(eventInterface:"MutationEvent"): MutationEvent; createEvent(eventInterface:"MutationEvents"): MutationEvent; createEvent(eventInterface:"NavigationCompletedEvent"): NavigationCompletedEvent; @@ -16630,6 +16642,7 @@ declare function addEventListener(type: "volumechange", listener: (ev: Event) => declare function addEventListener(type: "waiting", listener: (ev: Event) => any, useCapture?: boolean): void; declare function addEventListener(type: "wheel", listener: (ev: WheelEvent) => any, useCapture?: boolean): void; declare function addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + ///////////////////////////// /// WorkerGlobalScope APIs ///////////////////////////// diff --git a/bin/lib.dom.d.ts b/bin/lib.dom.d.ts index 142486a1662..b05be6cbee8 100644 --- a/bin/lib.dom.d.ts +++ b/bin/lib.dom.d.ts @@ -2361,6 +2361,11 @@ declare module Intl { currency?: string; currencyDisplay?: string; useGrouping?: boolean; + minimumintegerDigits?: number; + minimumFractionDigits?: number; + maximumFractionDigits?: number; + minimumSignificantDigits?: number; + maximumSignificantDigits?: number; } interface ResolvedNumberFormatOptions { @@ -2382,10 +2387,10 @@ declare module Intl { resolvedOptions(): ResolvedNumberFormatOptions; } var NumberFormat: { - new (locales?: string[], options?: NumberFormatOptions): Collator; - new (locale?: string, options?: NumberFormatOptions): Collator; - (locales?: string[], options?: NumberFormatOptions): Collator; - (locale?: string, options?: NumberFormatOptions): Collator; + new (locales?: string[], options?: NumberFormatOptions): NumberFormat; + new (locale?: string, options?: NumberFormatOptions): NumberFormat; + (locales?: string[], options?: NumberFormatOptions): NumberFormat; + (locale?: string, options?: NumberFormatOptions): NumberFormat; supportedLocalesOf(locales: string[], options?: NumberFormatOptions): string[]; supportedLocalesOf(locale: string, options?: NumberFormatOptions): string[]; } @@ -2423,14 +2428,14 @@ declare module Intl { } interface DateTimeFormat { - format(date: number): string; + format(date?: Date | number): string; resolvedOptions(): ResolvedDateTimeFormatOptions; } var DateTimeFormat: { - new (locales?: string[], options?: DateTimeFormatOptions): Collator; - new (locale?: string, options?: DateTimeFormatOptions): Collator; - (locales?: string[], options?: DateTimeFormatOptions): Collator; - (locale?: string, options?: DateTimeFormatOptions): Collator; + new (locales?: string[], options?: DateTimeFormatOptions): DateTimeFormat; + new (locale?: string, options?: DateTimeFormatOptions): DateTimeFormat; + (locales?: string[], options?: DateTimeFormatOptions): DateTimeFormat; + (locale?: string, options?: DateTimeFormatOptions): DateTimeFormat; supportedLocalesOf(locales: string[], options?: DateTimeFormatOptions): string[]; supportedLocalesOf(locale: string, options?: DateTimeFormatOptions): string[]; } @@ -10165,10 +10170,10 @@ declare var MediaQueryList: { interface MediaSource extends EventTarget { activeSourceBuffers: SourceBufferList; duration: number; - readyState: string; + readyState: number; sourceBuffers: SourceBufferList; addSourceBuffer(type: string): SourceBuffer; - endOfStream(error?: string): void; + endOfStream(error?: number): void; removeSourceBuffer(sourceBuffer: SourceBuffer): void; } @@ -10897,7 +10902,7 @@ declare var PopStateEvent: { interface Position { coords: Coordinates; - timestamp: Date; + timestamp: number; } declare var Position: { @@ -13578,9 +13583,17 @@ interface WebGLRenderingContext { stencilMaskSeparate(face: number, mask: number): void; stencilOp(fail: number, zfail: number, zpass: number): void; stencilOpSeparate(face: number, fail: number, zfail: number, zpass: number): void; + texImage2D(target: number, level: number, internalformat: number, width: number, height: number, border: number, format: number, type: number, pixels: ArrayBufferView): void; + texImage2D(target: number, level: number, internalformat: number, format: number, type: number, image: HTMLImageElement): void; + texImage2D(target: number, level: number, internalformat: number, format: number, type: number, canvas: HTMLCanvasElement): void; + texImage2D(target: number, level: number, internalformat: number, format: number, type: number, video: HTMLVideoElement): void; texImage2D(target: number, level: number, internalformat: number, format: number, type: number, pixels: ImageData): void; texParameterf(target: number, pname: number, param: number): void; texParameteri(target: number, pname: number, param: number): void; + texSubImage2D(target: number, level: number, xoffset: number, yoffset: number, width: number, height: number, format: number, type: number, pixels: ArrayBufferView): void; + texSubImage2D(target: number, level: number, xoffset: number, yoffset: number, format: number, type: number, image: HTMLImageElement): void; + texSubImage2D(target: number, level: number, xoffset: number, yoffset: number, format: number, type: number, canvas: HTMLCanvasElement): void; + texSubImage2D(target: number, level: number, xoffset: number, yoffset: number, format: number, type: number, video: HTMLVideoElement): void; texSubImage2D(target: number, level: number, xoffset: number, yoffset: number, format: number, type: number, pixels: ImageData): void; uniform1f(location: WebGLUniformLocation, x: number): void; uniform1fv(location: WebGLUniformLocation, v: any): void; @@ -14820,10 +14833,11 @@ interface DocumentEvent { createEvent(eventInterface:"AriaRequestEvent"): AriaRequestEvent; createEvent(eventInterface:"AudioProcessingEvent"): AudioProcessingEvent; createEvent(eventInterface:"BeforeUnloadEvent"): BeforeUnloadEvent; + createEvent(eventInterface:"ClipboardEvent"): ClipboardEvent; createEvent(eventInterface:"CloseEvent"): CloseEvent; createEvent(eventInterface:"CommandEvent"): CommandEvent; createEvent(eventInterface:"CompositionEvent"): CompositionEvent; - createEvent(eventInterface: "CustomEvent"): CustomEvent; + createEvent(eventInterface:"CustomEvent"): CustomEvent; createEvent(eventInterface:"DeviceMotionEvent"): DeviceMotionEvent; createEvent(eventInterface:"DeviceOrientationEvent"): DeviceOrientationEvent; createEvent(eventInterface:"DragEvent"): DragEvent; @@ -14846,8 +14860,6 @@ interface DocumentEvent { createEvent(eventInterface:"MouseEvent"): MouseEvent; createEvent(eventInterface:"MouseEvents"): MouseEvent; createEvent(eventInterface:"MouseWheelEvent"): MouseWheelEvent; - createEvent(eventInterface:"MSGestureEvent"): MSGestureEvent; - createEvent(eventInterface:"MSPointerEvent"): MSPointerEvent; createEvent(eventInterface:"MutationEvent"): MutationEvent; createEvent(eventInterface:"MutationEvents"): MutationEvent; createEvent(eventInterface:"NavigationCompletedEvent"): NavigationCompletedEvent; @@ -15459,4 +15471,4 @@ declare function addEventListener(type: "unload", listener: (ev: Event) => any, declare function addEventListener(type: "volumechange", listener: (ev: Event) => any, useCapture?: boolean): void; declare function addEventListener(type: "waiting", listener: (ev: Event) => any, useCapture?: boolean): void; declare function addEventListener(type: "wheel", listener: (ev: WheelEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; \ No newline at end of file +declare function addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; diff --git a/bin/lib.es6.d.ts b/bin/lib.es6.d.ts index d6ca7245140..e17cb3f35cf 100644 --- a/bin/lib.es6.d.ts +++ b/bin/lib.es6.d.ts @@ -1165,7 +1165,7 @@ interface ArrayConstructor { (arrayLength?: number): any[]; (arrayLength: number): T[]; (...items: T[]): T[]; - isArray(arg: any): boolean; + isArray(arg: any): arg is Array; prototype: Array; } @@ -1502,6 +1502,11 @@ interface Array { copyWithin(target: number, start: number, end?: number): T[]; } +interface IArguments { + /** Iterator */ + [Symbol.iterator](): IterableIterator; +} + interface ArrayConstructor { /** * Creates an array from an array-like object. @@ -1686,14 +1691,6 @@ interface GeneratorFunctionConstructor { } declare var GeneratorFunction: GeneratorFunctionConstructor; -interface Generator extends IterableIterator { - next(value?: any): IteratorResult; - throw(exception: any): IteratorResult; - return(value: T): IteratorResult; - [Symbol.iterator](): Generator; - [Symbol.toStringTag]: string; -} - interface Math { /** * Returns the number of leading zero bits in the 32-bit binary representation of a number. @@ -4912,6 +4909,11 @@ declare module Intl { currency?: string; currencyDisplay?: string; useGrouping?: boolean; + minimumintegerDigits?: number; + minimumFractionDigits?: number; + maximumFractionDigits?: number; + minimumSignificantDigits?: number; + maximumSignificantDigits?: number; } interface ResolvedNumberFormatOptions { @@ -4933,10 +4935,10 @@ declare module Intl { resolvedOptions(): ResolvedNumberFormatOptions; } var NumberFormat: { - new (locales?: string[], options?: NumberFormatOptions): Collator; - new (locale?: string, options?: NumberFormatOptions): Collator; - (locales?: string[], options?: NumberFormatOptions): Collator; - (locale?: string, options?: NumberFormatOptions): Collator; + new (locales?: string[], options?: NumberFormatOptions): NumberFormat; + new (locale?: string, options?: NumberFormatOptions): NumberFormat; + (locales?: string[], options?: NumberFormatOptions): NumberFormat; + (locale?: string, options?: NumberFormatOptions): NumberFormat; supportedLocalesOf(locales: string[], options?: NumberFormatOptions): string[]; supportedLocalesOf(locale: string, options?: NumberFormatOptions): string[]; } @@ -4974,14 +4976,14 @@ declare module Intl { } interface DateTimeFormat { - format(date: number): string; + format(date?: Date | number): string; resolvedOptions(): ResolvedDateTimeFormatOptions; } var DateTimeFormat: { - new (locales?: string[], options?: DateTimeFormatOptions): Collator; - new (locale?: string, options?: DateTimeFormatOptions): Collator; - (locales?: string[], options?: DateTimeFormatOptions): Collator; - (locale?: string, options?: DateTimeFormatOptions): Collator; + new (locales?: string[], options?: DateTimeFormatOptions): DateTimeFormat; + new (locale?: string, options?: DateTimeFormatOptions): DateTimeFormat; + (locales?: string[], options?: DateTimeFormatOptions): DateTimeFormat; + (locale?: string, options?: DateTimeFormatOptions): DateTimeFormat; supportedLocalesOf(locales: string[], options?: DateTimeFormatOptions): string[]; supportedLocalesOf(locale: string, options?: DateTimeFormatOptions): string[]; } @@ -12716,10 +12718,10 @@ declare var MediaQueryList: { interface MediaSource extends EventTarget { activeSourceBuffers: SourceBufferList; duration: number; - readyState: string; + readyState: number; sourceBuffers: SourceBufferList; addSourceBuffer(type: string): SourceBuffer; - endOfStream(error?: string): void; + endOfStream(error?: number): void; removeSourceBuffer(sourceBuffer: SourceBuffer): void; } @@ -13448,7 +13450,7 @@ declare var PopStateEvent: { interface Position { coords: Coordinates; - timestamp: Date; + timestamp: number; } declare var Position: { @@ -16129,9 +16131,17 @@ interface WebGLRenderingContext { stencilMaskSeparate(face: number, mask: number): void; stencilOp(fail: number, zfail: number, zpass: number): void; stencilOpSeparate(face: number, fail: number, zfail: number, zpass: number): void; + texImage2D(target: number, level: number, internalformat: number, width: number, height: number, border: number, format: number, type: number, pixels: ArrayBufferView): void; + texImage2D(target: number, level: number, internalformat: number, format: number, type: number, image: HTMLImageElement): void; + texImage2D(target: number, level: number, internalformat: number, format: number, type: number, canvas: HTMLCanvasElement): void; + texImage2D(target: number, level: number, internalformat: number, format: number, type: number, video: HTMLVideoElement): void; texImage2D(target: number, level: number, internalformat: number, format: number, type: number, pixels: ImageData): void; texParameterf(target: number, pname: number, param: number): void; texParameteri(target: number, pname: number, param: number): void; + texSubImage2D(target: number, level: number, xoffset: number, yoffset: number, width: number, height: number, format: number, type: number, pixels: ArrayBufferView): void; + texSubImage2D(target: number, level: number, xoffset: number, yoffset: number, format: number, type: number, image: HTMLImageElement): void; + texSubImage2D(target: number, level: number, xoffset: number, yoffset: number, format: number, type: number, canvas: HTMLCanvasElement): void; + texSubImage2D(target: number, level: number, xoffset: number, yoffset: number, format: number, type: number, video: HTMLVideoElement): void; texSubImage2D(target: number, level: number, xoffset: number, yoffset: number, format: number, type: number, pixels: ImageData): void; uniform1f(location: WebGLUniformLocation, x: number): void; uniform1fv(location: WebGLUniformLocation, v: any): void; @@ -17371,10 +17381,11 @@ interface DocumentEvent { createEvent(eventInterface:"AriaRequestEvent"): AriaRequestEvent; createEvent(eventInterface:"AudioProcessingEvent"): AudioProcessingEvent; createEvent(eventInterface:"BeforeUnloadEvent"): BeforeUnloadEvent; + createEvent(eventInterface:"ClipboardEvent"): ClipboardEvent; createEvent(eventInterface:"CloseEvent"): CloseEvent; createEvent(eventInterface:"CommandEvent"): CommandEvent; createEvent(eventInterface:"CompositionEvent"): CompositionEvent; - createEvent(eventInterface: "CustomEvent"): CustomEvent; + createEvent(eventInterface:"CustomEvent"): CustomEvent; createEvent(eventInterface:"DeviceMotionEvent"): DeviceMotionEvent; createEvent(eventInterface:"DeviceOrientationEvent"): DeviceOrientationEvent; createEvent(eventInterface:"DragEvent"): DragEvent; @@ -17397,8 +17408,6 @@ interface DocumentEvent { createEvent(eventInterface:"MouseEvent"): MouseEvent; createEvent(eventInterface:"MouseEvents"): MouseEvent; createEvent(eventInterface:"MouseWheelEvent"): MouseWheelEvent; - createEvent(eventInterface:"MSGestureEvent"): MSGestureEvent; - createEvent(eventInterface:"MSPointerEvent"): MSPointerEvent; createEvent(eventInterface:"MutationEvent"): MutationEvent; createEvent(eventInterface:"MutationEvents"): MutationEvent; createEvent(eventInterface:"NavigationCompletedEvent"): NavigationCompletedEvent; @@ -18011,6 +18020,17 @@ declare function addEventListener(type: "volumechange", listener: (ev: Event) => declare function addEventListener(type: "waiting", listener: (ev: Event) => any, useCapture?: boolean): void; declare function addEventListener(type: "wheel", listener: (ev: WheelEvent) => any, useCapture?: boolean): void; declare function addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +interface DOMTokenList { + [Symbol.iterator](): IterableIterator; +} + +interface NodeList { + [Symbol.iterator](): IterableIterator +} + +interface NodeListOf { + [Symbol.iterator](): IterableIterator +} ///////////////////////////// /// WorkerGlobalScope APIs ///////////////////////////// diff --git a/bin/lib.webworker.d.ts b/bin/lib.webworker.d.ts index 1704e07f75a..d0caeccff92 100644 --- a/bin/lib.webworker.d.ts +++ b/bin/lib.webworker.d.ts @@ -2361,6 +2361,11 @@ declare module Intl { currency?: string; currencyDisplay?: string; useGrouping?: boolean; + minimumintegerDigits?: number; + minimumFractionDigits?: number; + maximumFractionDigits?: number; + minimumSignificantDigits?: number; + maximumSignificantDigits?: number; } interface ResolvedNumberFormatOptions { @@ -2382,10 +2387,10 @@ declare module Intl { resolvedOptions(): ResolvedNumberFormatOptions; } var NumberFormat: { - new (locales?: string[], options?: NumberFormatOptions): Collator; - new (locale?: string, options?: NumberFormatOptions): Collator; - (locales?: string[], options?: NumberFormatOptions): Collator; - (locale?: string, options?: NumberFormatOptions): Collator; + new (locales?: string[], options?: NumberFormatOptions): NumberFormat; + new (locale?: string, options?: NumberFormatOptions): NumberFormat; + (locales?: string[], options?: NumberFormatOptions): NumberFormat; + (locale?: string, options?: NumberFormatOptions): NumberFormat; supportedLocalesOf(locales: string[], options?: NumberFormatOptions): string[]; supportedLocalesOf(locale: string, options?: NumberFormatOptions): string[]; } @@ -2423,14 +2428,14 @@ declare module Intl { } interface DateTimeFormat { - format(date: number): string; + format(date?: Date | number): string; resolvedOptions(): ResolvedDateTimeFormatOptions; } var DateTimeFormat: { - new (locales?: string[], options?: DateTimeFormatOptions): Collator; - new (locale?: string, options?: DateTimeFormatOptions): Collator; - (locales?: string[], options?: DateTimeFormatOptions): Collator; - (locale?: string, options?: DateTimeFormatOptions): Collator; + new (locales?: string[], options?: DateTimeFormatOptions): DateTimeFormat; + new (locale?: string, options?: DateTimeFormatOptions): DateTimeFormat; + (locales?: string[], options?: DateTimeFormatOptions): DateTimeFormat; + (locale?: string, options?: DateTimeFormatOptions): DateTimeFormat; supportedLocalesOf(locales: string[], options?: DateTimeFormatOptions): string[]; supportedLocalesOf(locale: string, options?: DateTimeFormatOptions): string[]; } diff --git a/bin/tsc b/bin/tsc old mode 100644 new mode 100755 diff --git a/bin/tsc.js b/bin/tsc.js index 47c6769ae8d..e5f449c4101 100644 --- a/bin/tsc.js +++ b/bin/tsc.js @@ -31,6 +31,36 @@ var ts; /// var ts; (function (ts) { + function createFileMap(getCanonicalFileName) { + var files = {}; + return { + get: get, + set: set, + contains: contains, + remove: remove, + forEachValue: forEachValueInMap + }; + function set(fileName, value) { + files[normalizeKey(fileName)] = value; + } + function get(fileName) { + return files[normalizeKey(fileName)]; + } + function contains(fileName) { + return hasProperty(files, normalizeKey(fileName)); + } + function remove(fileName) { + var key = normalizeKey(fileName); + delete files[key]; + } + function forEachValueInMap(f) { + forEachValue(files, f); + } + function normalizeKey(key) { + return getCanonicalFileName(normalizeSlashes(key)); + } + } + ts.createFileMap = createFileMap; function forEach(array, callback) { if (array) { for (var i = 0, len = array.length; i < len; i++) { @@ -145,6 +175,16 @@ var ts; } } ts.addRange = addRange; + function rangeEquals(array1, array2, pos, end) { + while (pos < end) { + if (array1[pos] !== array2[pos]) { + return false; + } + pos++; + } + return true; + } + ts.rangeEquals = rangeEquals; function lastOrUndefined(array) { if (array.length === 0) { return undefined; @@ -301,8 +341,10 @@ var ts; var end = start + length; Debug.assert(start >= 0, "start must be non-negative, is " + start); Debug.assert(length >= 0, "length must be non-negative, is " + length); - Debug.assert(start <= file.text.length, "start must be within the bounds of the file. " + start + " > " + file.text.length); - Debug.assert(end <= file.text.length, "end must be the bounds of the file. " + end + " > " + file.text.length); + if (file) { + Debug.assert(start <= file.text.length, "start must be within the bounds of the file. " + start + " > " + file.text.length); + Debug.assert(end <= file.text.length, "end must be the bounds of the file. " + end + " > " + file.text.length); + } var text = getLocaleSpecificMessage(message.key); if (arguments.length > 4) { text = formatStringFromArgs(text, arguments, 4); @@ -486,7 +528,7 @@ var ts; function getNormalizedPathComponents(path, currentDirectory) { path = normalizeSlashes(path); var rootLength = getRootLength(path); - if (rootLength == 0) { + if (rootLength === 0) { path = combinePaths(normalizeSlashes(currentDirectory), path); rootLength = getRootLength(path); } @@ -726,6 +768,9 @@ var ts; fileStream.Close(); } } + function getCanonicalPath(path) { + return path.toLowerCase(); + } function getNames(collection) { var result = []; for (var e = new Enumerator(collection); !e.atEnd(); e.moveNext()) { @@ -733,23 +778,28 @@ var ts; } return result.sort(); } - function readDirectory(path, extension) { + function readDirectory(path, extension, exclude) { var result = []; + exclude = ts.map(exclude, function (s) { return getCanonicalPath(ts.combinePaths(path, s)); }); visitDirectory(path); return result; function visitDirectory(path) { var folder = fso.GetFolder(path || "."); var files = getNames(folder.files); for (var _i = 0; _i < files.length; _i++) { - var name_1 = files[_i]; - if (!extension || ts.fileExtensionIs(name_1, extension)) { - result.push(ts.combinePaths(path, name_1)); + var current = files[_i]; + var name_1 = ts.combinePaths(path, current); + if ((!extension || ts.fileExtensionIs(name_1, extension)) && !ts.contains(exclude, getCanonicalPath(name_1))) { + result.push(name_1); } } var subfolders = getNames(folder.subfolders); for (var _a = 0; _a < subfolders.length; _a++) { var current = subfolders[_a]; - visitDirectory(ts.combinePaths(path, current)); + var name_2 = ts.combinePaths(path, current); + if (!ts.contains(exclude, getCanonicalPath(name_2))) { + visitDirectory(name_2); + } } } } @@ -827,8 +877,12 @@ var ts; } _fs.writeFileSync(fileName, data, "utf8"); } - function readDirectory(path, extension) { + function getCanonicalPath(path) { + return useCaseSensitiveFileNames ? path.toLowerCase() : path; + } + function readDirectory(path, extension, exclude) { var result = []; + exclude = ts.map(exclude, function (s) { return getCanonicalPath(ts.combinePaths(path, s)); }); visitDirectory(path); return result; function visitDirectory(path) { @@ -837,14 +891,16 @@ var ts; for (var _i = 0; _i < files.length; _i++) { var current = files[_i]; var name = ts.combinePaths(path, current); - var stat = _fs.lstatSync(name); - if (stat.isFile()) { - if (!extension || ts.fileExtensionIs(name, extension)) { - result.push(name); + if (!ts.contains(exclude, getCanonicalPath(name))) { + var stat = _fs.statSync(name); + if (stat.isFile()) { + if (!extension || ts.fileExtensionIs(name, extension)) { + result.push(name); + } + } + else if (stat.isDirectory()) { + directories.push(name); } - } - else if (stat.isDirectory()) { - directories.push(name); } } for (var _a = 0; _a < directories.length; _a++) { @@ -1039,7 +1095,7 @@ var ts; Unterminated_template_literal: { code: 1160, category: ts.DiagnosticCategory.Error, key: "Unterminated template literal." }, Unterminated_regular_expression_literal: { code: 1161, category: ts.DiagnosticCategory.Error, key: "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." }, - yield_expression_must_be_contained_within_a_generator_declaration: { code: 1163, category: ts.DiagnosticCategory.Error, key: "'yield' expression must be contained_within a generator declaration." }, + 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." }, Computed_property_names_are_not_allowed_in_enums: { code: 1164, category: ts.DiagnosticCategory.Error, key: "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." }, 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." }, @@ -1084,15 +1140,32 @@ var ts; Decorators_are_only_available_when_targeting_ECMAScript_5_and_higher: { code: 1205, category: ts.DiagnosticCategory.Error, key: "Decorators are only available when targeting ECMAScript 5 and higher." }, Decorators_are_not_valid_here: { code: 1206, category: ts.DiagnosticCategory.Error, key: "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/set accessors of the same name." }, - Cannot_compile_namespaces_when_the_separateCompilation_flag_is_provided: { code: 1208, category: ts.DiagnosticCategory.Error, key: "Cannot compile namespaces when the '--separateCompilation' flag is provided." }, - Ambient_const_enums_are_not_allowed_when_the_separateCompilation_flag_is_provided: { code: 1209, category: ts.DiagnosticCategory.Error, key: "Ambient const enums are not allowed when the '--separateCompilation' flag is provided." }, + 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." }, + 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." }, 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." }, 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" }, 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" }, 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 strict mode." }, - Type_expected_0_is_a_reserved_word_in_strict_mode: { code: 1215, category: ts.DiagnosticCategory.Error, key: "Type expected. '{0}' is a reserved word in strict mode" }, - Type_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_strict_mode: { code: 1216, category: ts.DiagnosticCategory.Error, key: "Type 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." }, + 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." }, 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'." }, + Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Specify_experimentalDecorators_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. Specify '--experimentalDecorators' to remove this warning." }, + Generators_are_only_available_when_targeting_ECMAScript_6_or_higher: { code: 1220, category: ts.DiagnosticCategory.Error, key: "Generators are only available when targeting ECMAScript 6 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." }, + 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." }, + _0_tag_already_specified: { code: 1223, category: ts.DiagnosticCategory.Error, key: "'{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." }, + Cannot_find_parameter_0: { code: 1225, category: ts.DiagnosticCategory.Error, key: "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}'." }, + 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}'." }, + 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." }, + A_type_predicate_cannot_reference_a_rest_parameter: { code: 1229, category: ts.DiagnosticCategory.Error, key: "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." }, + 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." }, + 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." }, + 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." }, + 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." }, + 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." }, Duplicate_identifier_0: { code: 2300, category: ts.DiagnosticCategory.Error, key: "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." }, Static_members_cannot_reference_class_type_parameters: { code: 2302, category: ts.DiagnosticCategory.Error, key: "Static members cannot reference class type parameters." }, @@ -1253,7 +1326,7 @@ var ts; 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'." }, 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." }, 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'." }, - Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_6_and_higher: { code: 2472, category: ts.DiagnosticCategory.Error, key: "Spread operator in 'new' expressions is only available when targeting ECMAScript 6 and higher." }, + 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." }, 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." }, 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." }, 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 import declaration or export assignment." }, @@ -1284,6 +1357,13 @@ var ts; A_rest_element_cannot_contain_a_binding_pattern: { code: 2501, category: ts.DiagnosticCategory.Error, key: "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." }, Cannot_find_namespace_0: { code: 2503, category: ts.DiagnosticCategory.Error, key: "Cannot find namespace '{0}'." }, + No_best_common_type_exists_among_yield_expressions: { code: 2504, category: ts.DiagnosticCategory.Error, key: "No best common type exists among yield expressions." }, + A_generator_cannot_have_a_void_type_annotation: { code: 2505, category: ts.DiagnosticCategory.Error, key: "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." }, + Type_0_is_not_a_constructor_function_type: { code: 2507, category: ts.DiagnosticCategory.Error, key: "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." }, + 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." }, + 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." }, Import_declaration_0_is_using_private_name_1: { code: 4000, category: ts.DiagnosticCategory.Error, key: "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}'." }, 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}'." }, @@ -1368,11 +1448,11 @@ var ts; Option_noEmit_cannot_be_specified_with_option_out_or_outDir: { code: 5040, category: ts.DiagnosticCategory.Error, key: "Option 'noEmit' cannot be specified with option 'out' or 'outDir'." }, Option_noEmit_cannot_be_specified_with_option_declaration: { code: 5041, category: ts.DiagnosticCategory.Error, key: "Option 'noEmit' cannot be specified with option 'declaration'." }, 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." }, - Option_sourceMap_cannot_be_specified_with_option_separateCompilation: { code: 5043, category: ts.DiagnosticCategory.Error, key: "Option 'sourceMap' cannot be specified with option 'separateCompilation'." }, - Option_declaration_cannot_be_specified_with_option_separateCompilation: { code: 5044, category: ts.DiagnosticCategory.Error, key: "Option 'declaration' cannot be specified with option 'separateCompilation'." }, - Option_noEmitOnError_cannot_be_specified_with_option_separateCompilation: { code: 5045, category: ts.DiagnosticCategory.Error, key: "Option 'noEmitOnError' cannot be specified with option 'separateCompilation'." }, - Option_out_cannot_be_specified_with_option_separateCompilation: { code: 5046, category: ts.DiagnosticCategory.Error, key: "Option 'out' cannot be specified with option 'separateCompilation'." }, - Option_separateCompilation_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES6_or_higher: { code: 5047, category: ts.DiagnosticCategory.Error, key: "Option 'separateCompilation' can only be used when either option'--module' is provided or option 'target' is 'ES6' or higher." }, + Option_sourceMap_cannot_be_specified_with_option_isolatedModules: { code: 5043, category: ts.DiagnosticCategory.Error, key: "Option 'sourceMap' cannot be specified with option 'isolatedModules'." }, + Option_declaration_cannot_be_specified_with_option_isolatedModules: { code: 5044, category: ts.DiagnosticCategory.Error, key: "Option 'declaration' cannot be specified with option 'isolatedModules'." }, + Option_noEmitOnError_cannot_be_specified_with_option_isolatedModules: { code: 5045, category: ts.DiagnosticCategory.Error, key: "Option 'noEmitOnError' cannot be specified with option 'isolatedModules'." }, + Option_out_cannot_be_specified_with_option_isolatedModules: { code: 5046, category: ts.DiagnosticCategory.Error, key: "Option 'out' cannot be specified with option 'isolatedModules'." }, + Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES6_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 'ES6' or higher." }, Option_sourceMap_cannot_be_specified_with_option_inlineSourceMap: { code: 5048, category: ts.DiagnosticCategory.Error, key: "Option 'sourceMap' cannot be specified with option 'inlineSourceMap'." }, Option_sourceRoot_cannot_be_specified_with_option_inlineSourceMap: { code: 5049, category: ts.DiagnosticCategory.Error, key: "Option 'sourceRoot' cannot be specified with option 'inlineSourceMap'." }, Option_mapRoot_cannot_be_specified_with_option_inlineSourceMap: { code: 5050, category: ts.DiagnosticCategory.Error, key: "Option 'mapRoot' cannot be specified with option 'inlineSourceMap'." }, @@ -1426,6 +1506,9 @@ var ts; Specifies_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix: { code: 6060, category: ts.DiagnosticCategory.Message, key: "Specifies 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" }, Argument_for_newLine_option_must_be_CRLF_or_LF: { code: 6062, category: ts.DiagnosticCategory.Error, key: "Argument for '--newLine' option must be 'CRLF' or 'LF'." }, + Option_experimentalDecorators_must_also_be_specified_when_option_emitDecoratorMetadata_is_specified: { code: 6064, category: ts.DiagnosticCategory.Error, key: "Option 'experimentalDecorators' must also be specified when option 'emitDecoratorMetadata' is specified." }, + Enables_experimental_support_for_ES7_decorators: { code: 6065, category: ts.DiagnosticCategory.Message, key: "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." }, Variable_0_implicitly_has_an_1_type: { code: 7005, category: ts.DiagnosticCategory.Error, key: "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." }, Member_0_implicitly_has_an_1_type: { code: 7008, category: ts.DiagnosticCategory.Error, key: "Member '{0}' implicitly has an '{1}' type." }, @@ -1438,9 +1521,10 @@ var ts; 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." }, Rest_parameter_0_implicitly_has_an_any_type: { code: 7019, category: ts.DiagnosticCategory.Error, key: "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." }, - _0_implicitly_has_type_any_because_it_is_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 is does not have a type annotation and is referenced directly or indirectly in its own initializer." }, + _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 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 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 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 type." }, You_cannot_rename_this_element: { code: 8000, category: ts.DiagnosticCategory.Error, key: "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." }, 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." }, @@ -1454,16 +1538,12 @@ var ts; 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." }, 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." }, 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." }, - can_only_be_used_in_a_ts_file: { code: 8013, category: ts.DiagnosticCategory.Error, key: "'?' can only be used in a .ts file." }, property_declarations_can_only_be_used_in_a_ts_file: { code: 8014, category: ts.DiagnosticCategory.Error, key: "'property declarations' 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." }, 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." }, decorators_can_only_be_used_in_a_ts_file: { code: 8017, category: ts.DiagnosticCategory.Error, key: "'decorators' can only be used in a .ts file." }, - yield_expressions_are_not_currently_supported: { code: 9000, category: ts.DiagnosticCategory.Error, key: "'yield' expressions are not currently supported." }, - Generators_are_not_currently_supported: { code: 9001, category: ts.DiagnosticCategory.Error, key: "Generators are not currently supported." }, Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_class_extends_clauses: { code: 9002, category: ts.DiagnosticCategory.Error, key: "Only identifiers/qualified-names with optional type arguments are currently supported in a class 'extends' clauses." }, - class_expressions_are_not_currently_supported: { code: 9003, category: ts.DiagnosticCategory.Error, key: "'class' expressions are not currently supported." }, - class_declarations_are_only_supported_directly_inside_a_module_or_as_a_top_level_declaration: { code: 9004, category: ts.DiagnosticCategory.Error, key: "'class' declarations are only supported directly inside a module or as a top level declaration." } + class_expressions_are_not_currently_supported: { code: 9003, category: ts.DiagnosticCategory.Error, key: "'class' expressions are not currently supported." } }; })(ts || (ts = {})); /// @@ -1493,7 +1573,7 @@ var ts; "false": 80, "finally": 81, "for": 82, - "from": 125, + "from": 126, "function": 83, "get": 116, "if": 84, @@ -1502,36 +1582,37 @@ var ts; "in": 86, "instanceof": 87, "interface": 103, + "is": 117, "let": 104, - "module": 117, - "namespace": 118, + "module": 118, + "namespace": 119, "new": 88, "null": 89, - "number": 120, + "number": 121, "package": 105, "private": 106, "protected": 107, "public": 108, - "require": 119, + "require": 120, "return": 90, - "set": 121, + "set": 122, "static": 109, - "string": 122, + "string": 123, "super": 91, "switch": 92, - "symbol": 123, + "symbol": 124, "this": 93, "throw": 94, "true": 95, "try": 96, - "type": 124, + "type": 125, "typeof": 97, "var": 98, "void": 99, "while": 100, "with": 101, "yield": 110, - "of": 126, + "of": 127, "{": 14, "}": 15, "(": 16, @@ -1623,9 +1704,9 @@ var ts; } function makeReverseMap(source) { var result = []; - for (var name_2 in source) { - if (source.hasOwnProperty(name_2)) { - result[source[name_2]] = name_2; + for (var name_3 in source) { + if (source.hasOwnProperty(name_3)) { + result[source[name_3]] = name_3; } } return result; @@ -1734,6 +1815,25 @@ var ts; return ch >= 48 && ch <= 55; } ts.isOctalDigit = isOctalDigit; + function couldStartTrivia(text, pos) { + var ch = text.charCodeAt(pos); + switch (ch) { + case 13: + case 10: + case 9: + case 11: + case 12: + case 32: + case 47: + case 60: + case 61: + case 62: + return true; + default: + return ch > 127; + } + } + ts.couldStartTrivia = couldStartTrivia; function skipTrivia(text, pos, stopAfterLineBreak) { while (true) { var ch = text.charCodeAt(pos); @@ -2196,7 +2296,7 @@ var ts; error(ts.Diagnostics.Unexpected_end_of_text); isInvalidExtendedEscape = true; } - else if (text.charCodeAt(pos) == 125) { + else if (text.charCodeAt(pos) === 125) { pos++; } else { @@ -2717,16 +2817,16 @@ var ts; (function (ts) { ts.bindTime = 0; function getModuleInstanceState(node) { - if (node.kind === 203 || node.kind === 204) { + if (node.kind === 205 || node.kind === 206) { return 0; } else if (ts.isConstEnumDeclaration(node)) { return 2; } - else if ((node.kind === 210 || node.kind === 209) && !(node.flags & 1)) { + else if ((node.kind === 212 || node.kind === 211) && !(node.flags & 1)) { return 0; } - else if (node.kind === 207) { + else if (node.kind === 209) { var state = 0; ts.forEachChild(node, function (n) { switch (getModuleInstanceState(n)) { @@ -2742,7 +2842,7 @@ var ts; }); return state; } - else if (node.kind === 206) { + else if (node.kind === 208) { return getModuleInstanceState(node.body); } else { @@ -2761,44 +2861,43 @@ var ts; var container; var blockScopeContainer; var lastContainer; + var inStrictMode = !!file.externalModuleIndicator; var symbolCount = 0; var Symbol = ts.objectAllocator.getSymbolConstructor(); + var classifiableNames = {}; if (!file.locals) { - file.locals = {}; - container = file; - setBlockScopeContainer(file, false); bind(file); file.symbolCount = symbolCount; + file.classifiableNames = classifiableNames; } + return; function createSymbol(flags, name) { symbolCount++; return new Symbol(flags, name); } - function setBlockScopeContainer(node, cleanLocals) { - blockScopeContainer = node; - if (cleanLocals) { - blockScopeContainer.locals = undefined; - } - } - function addDeclarationToSymbol(symbol, node, symbolKind) { - symbol.flags |= symbolKind; - if (!symbol.declarations) - symbol.declarations = []; - symbol.declarations.push(node); - if (symbolKind & 1952 && !symbol.exports) - symbol.exports = {}; - if (symbolKind & 6240 && !symbol.members) - symbol.members = {}; + function addDeclarationToSymbol(symbol, node, symbolFlags) { + symbol.flags |= symbolFlags; node.symbol = symbol; - if (symbolKind & 107455 && !symbol.valueDeclaration) + if (!symbol.declarations) { + symbol.declarations = []; + } + symbol.declarations.push(node); + if (symbolFlags & 1952 && !symbol.exports) { + symbol.exports = {}; + } + if (symbolFlags & 6240 && !symbol.members) { + symbol.members = {}; + } + if (symbolFlags & 107455 && !symbol.valueDeclaration) { symbol.valueDeclaration = node; + } } function getDeclarationName(node) { if (node.name) { - if (node.kind === 206 && node.name.kind === 8) { + if (node.kind === 208 && node.name.kind === 8) { return '"' + node.name.text + '"'; } - if (node.name.kind === 128) { + if (node.name.kind === 129) { var nameExpression = node.name.expression; ts.Debug.assert(ts.isWellKnownSymbolSyntactically(nameExpression)); return ts.getPropertyNameForKnownSymbolName(nameExpression.name.text); @@ -2806,34 +2905,39 @@ var ts; return node.name.text; } switch (node.kind) { - case 144: - case 136: + case 137: return "__constructor"; - case 143: - case 139: - return "__call"; + case 145: case 140: - return "__new"; + return "__call"; + case 146: case 141: + return "__new"; + case 142: return "__index"; - case 216: + case 218: return "__export"; - case 215: + case 217: return node.isExportEquals ? "export=" : "default"; - case 201: - case 202: + case 203: + case 204: return node.flags & 256 ? "default" : undefined; } } function getDisplayName(node) { return node.name ? ts.declarationNameToString(node.name) : getDeclarationName(node); } - function declareSymbol(symbols, parent, node, includes, excludes) { + function declareSymbol(symbolTable, parent, node, includes, excludes) { ts.Debug.assert(!ts.hasDynamicName(node)); var name = node.flags & 256 && parent ? "default" : getDeclarationName(node); var symbol; if (name !== undefined) { - symbol = ts.hasProperty(symbols, name) ? symbols[name] : (symbols[name] = createSymbol(0, name)); + symbol = ts.hasProperty(symbolTable, name) + ? symbolTable[name] + : (symbolTable[name] = createSymbol(0, name)); + if (name && (includes & 788448)) { + classifiableNames[name] = name; + } if (symbol.flags & excludes) { if (node.name) { node.name.parent = node; @@ -2853,125 +2957,158 @@ var ts; } addDeclarationToSymbol(symbol, node, includes); symbol.parent = parent; - if ((node.kind === 202 || node.kind === 175) && symbol.exports) { - var prototypeSymbol = createSymbol(4 | 134217728, "prototype"); - if (ts.hasProperty(symbol.exports, prototypeSymbol.name)) { - if (node.name) { - node.name.parent = node; - } - file.bindDiagnostics.push(ts.createDiagnosticForNode(symbol.exports[prototypeSymbol.name].declarations[0], ts.Diagnostics.Duplicate_identifier_0, prototypeSymbol.name)); - } - symbol.exports[prototypeSymbol.name] = prototypeSymbol; - prototypeSymbol.parent = symbol; - } return symbol; } - function declareModuleMember(node, symbolKind, symbolExcludes) { + function declareModuleMember(node, symbolFlags, symbolExcludes) { var hasExportModifier = ts.getCombinedNodeFlags(node) & 1; - if (symbolKind & 8388608) { - if (node.kind === 218 || (node.kind === 209 && hasExportModifier)) { - declareSymbol(container.symbol.exports, container.symbol, node, symbolKind, symbolExcludes); + if (symbolFlags & 8388608) { + if (node.kind === 220 || (node.kind === 211 && hasExportModifier)) { + return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); } else { - declareSymbol(container.locals, undefined, node, symbolKind, symbolExcludes); + return declareSymbol(container.locals, undefined, node, symbolFlags, symbolExcludes); } } else { if (hasExportModifier || container.flags & 65536) { - var exportKind = (symbolKind & 107455 ? 1048576 : 0) | - (symbolKind & 793056 ? 2097152 : 0) | - (symbolKind & 1536 ? 4194304 : 0); + var exportKind = (symbolFlags & 107455 ? 1048576 : 0) | + (symbolFlags & 793056 ? 2097152 : 0) | + (symbolFlags & 1536 ? 4194304 : 0); var local = declareSymbol(container.locals, undefined, node, exportKind, symbolExcludes); - local.exportSymbol = declareSymbol(container.symbol.exports, container.symbol, node, symbolKind, symbolExcludes); + local.exportSymbol = declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); node.localSymbol = local; + return local; } else { - declareSymbol(container.locals, undefined, node, symbolKind, symbolExcludes); + return declareSymbol(container.locals, undefined, node, symbolFlags, symbolExcludes); } } } - function bindChildren(node, symbolKind, isBlockScopeContainer) { - if (symbolKind & 255504) { - node.locals = {}; - } + function bindChildren(node) { var saveParent = parent; var saveContainer = container; var savedBlockScopeContainer = blockScopeContainer; parent = node; - if (symbolKind & 262128) { - container = node; + var containerFlags = getContainerFlags(node); + if (containerFlags & 1) { + container = blockScopeContainer = node; + if (containerFlags & 4) { + container.locals = {}; + } addToContainerChain(container); } - if (isBlockScopeContainer) { - setBlockScopeContainer(node, (symbolKind & 255504) === 0 && node.kind !== 228); + else if (containerFlags & 2) { + blockScopeContainer = node; + blockScopeContainer.locals = undefined; } ts.forEachChild(node, bind); container = saveContainer; parent = saveParent; blockScopeContainer = savedBlockScopeContainer; } - function addToContainerChain(node) { - if (lastContainer) { - lastContainer.nextContainer = node; - } - lastContainer = node; - } - function bindDeclaration(node, symbolKind, symbolExcludes, isBlockScopeContainer) { - switch (container.kind) { - case 206: - declareModuleMember(node, symbolKind, symbolExcludes); - break; - case 228: - if (ts.isExternalModule(container)) { - declareModuleMember(node, symbolKind, symbolExcludes); - break; - } - case 143: - case 144: - case 139: + function getContainerFlags(node) { + switch (node.kind) { + case 177: + case 204: + case 205: + case 207: + case 148: + case 157: + return 1; case 140: case 141: - case 135: - case 134: + case 142: case 136: + case 135: + case 203: case 137: case 138: - case 201: - case 163: - case 164: - declareSymbol(container.locals, undefined, node, symbolKind, symbolExcludes); - break; - case 175: - case 202: - if (node.flags & 128) { - declareSymbol(container.symbol.exports, container.symbol, node, symbolKind, symbolExcludes); - break; - } + case 139: + case 145: case 146: - case 155: - case 203: - declareSymbol(container.symbol.members, container.symbol, node, symbolKind, symbolExcludes); - break; - case 205: - declareSymbol(container.symbol.exports, container.symbol, node, symbolKind, symbolExcludes); - break; + case 165: + case 166: + case 208: + case 230: + case 206: + return 5; + case 226: + case 189: + case 190: + case 191: + case 210: + return 2; + case 182: + return ts.isFunctionLike(node.parent) ? 0 : 2; } - bindChildren(node, symbolKind, isBlockScopeContainer); + return 0; + } + function addToContainerChain(next) { + if (lastContainer) { + lastContainer.nextContainer = next; + } + lastContainer = next; + } + function declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes) { + declareSymbolAndAddToSymbolTableWorker(node, symbolFlags, symbolExcludes); + } + function declareSymbolAndAddToSymbolTableWorker(node, symbolFlags, symbolExcludes) { + switch (container.kind) { + case 208: + return declareModuleMember(node, symbolFlags, symbolExcludes); + case 230: + return declareSourceFileMember(node, symbolFlags, symbolExcludes); + case 177: + case 204: + return declareClassMember(node, symbolFlags, symbolExcludes); + case 207: + return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); + case 148: + case 157: + case 205: + return declareSymbol(container.symbol.members, container.symbol, node, symbolFlags, symbolExcludes); + case 145: + case 146: + case 140: + case 141: + case 142: + case 136: + case 135: + case 137: + case 138: + case 139: + case 203: + case 165: + case 166: + case 206: + return declareSymbol(container.locals, undefined, node, symbolFlags, symbolExcludes); + } + } + function declareClassMember(node, symbolFlags, symbolExcludes) { + return node.flags & 128 + ? 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 isAmbientContext(node) { while (node) { - if (node.flags & 2) + if (node.flags & 2) { return true; + } node = node.parent; } return false; } function hasExportDeclarations(node) { - var body = node.kind === 228 ? node : node.body; - if (body.kind === 228 || body.kind === 207) { + var body = node.kind === 230 ? node : node.body; + if (body.kind === 230 || body.kind === 209) { for (var _i = 0, _a = body.statements; _i < _a.length; _i++) { var stat = _a[_i]; - if (stat.kind === 216 || stat.kind === 215) { + if (stat.kind === 218 || stat.kind === 217) { return true; } } @@ -2989,15 +3126,15 @@ var ts; function bindModuleDeclaration(node) { setExportContextFlag(node); if (node.name.kind === 8) { - bindDeclaration(node, 512, 106639, true); + declareSymbolAndAddToSymbolTable(node, 512, 106639); } else { var state = getModuleInstanceState(node); if (state === 0) { - bindDeclaration(node, 1024, 0, true); + declareSymbolAndAddToSymbolTable(node, 1024, 0); } else { - bindDeclaration(node, 512, 106639, true); + declareSymbolAndAddToSymbolTable(node, 512, 106639); var currentModuleIsConstEnumOnly = state === 2; if (node.symbol.constEnumOnlyModule === undefined) { node.symbol.constEnumOnlyModule = currentModuleIsConstEnumOnly; @@ -3009,36 +3146,50 @@ var ts; } } 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, getDeclarationName(node)); addDeclarationToSymbol(symbol, node, 131072); - bindChildren(node, 131072, false); var typeLiteralSymbol = createSymbol(2048, "__type"); addDeclarationToSymbol(typeLiteralSymbol, node, 2048); - typeLiteralSymbol.members = {}; - typeLiteralSymbol.members[node.kind === 143 ? "__call" : "__new"] = symbol; + typeLiteralSymbol.members = (_a = {}, _a[symbol.name] = symbol, _a); + var _a; } - function bindAnonymousDeclaration(node, symbolKind, name, isBlockScopeContainer) { - var symbol = createSymbol(symbolKind, name); - addDeclarationToSymbol(symbol, node, symbolKind); - bindChildren(node, symbolKind, isBlockScopeContainer); + function bindObjectLiteralExpression(node) { + if (inStrictMode) { + var seen = {}; + for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { + var prop = _a[_i]; + if (prop.name.kind !== 65) { + continue; + } + var identifier = prop.name; + var currentKind = prop.kind === 227 || prop.kind === 228 || prop.kind === 136 + ? 1 + : 2; + var existingKind = seen[identifier.text]; + if (!existingKind) { + seen[identifier.text] = currentKind; + continue; + } + if (currentKind === 1 && existingKind === 1) { + var span = ts.getErrorSpanForNode(file, identifier); + file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, ts.Diagnostics.An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode)); + } + } + } + return bindAnonymousDeclaration(node, 4096, "__object"); } - function bindCatchVariableDeclaration(node) { - bindChildren(node, 0, true); + function bindAnonymousDeclaration(node, symbolFlags, name) { + var symbol = createSymbol(symbolFlags, name); + addDeclarationToSymbol(symbol, node, symbolFlags); } - function bindBlockScopedDeclaration(node, symbolKind, symbolExcludes) { + function bindBlockScopedDeclaration(node, symbolFlags, symbolExcludes) { switch (blockScopeContainer.kind) { - case 206: - declareModuleMember(node, symbolKind, symbolExcludes); + case 208: + declareModuleMember(node, symbolFlags, symbolExcludes); break; - case 228: + case 230: if (ts.isExternalModule(container)) { - declareModuleMember(node, symbolKind, symbolExcludes); + declareModuleMember(node, symbolFlags, symbolExcludes); break; } default: @@ -3046,185 +3197,322 @@ var ts; blockScopeContainer.locals = {}; addToContainerChain(blockScopeContainer); } - declareSymbol(blockScopeContainer.locals, undefined, node, symbolKind, symbolExcludes); + declareSymbol(blockScopeContainer.locals, undefined, node, symbolFlags, symbolExcludes); } - bindChildren(node, symbolKind, false); } function bindBlockScopedVariableDeclaration(node) { bindBlockScopedDeclaration(node, 2, 107455); } + function checkStrictModeIdentifier(node) { + if (inStrictMode && + node.originalKeywordKind >= 102 && + node.originalKeywordKind <= 110 && + !ts.isIdentifierName(node)) { + if (!file.parseDiagnostics.length) { + file.bindDiagnostics.push(ts.createDiagnosticForNode(node, getStrictModeIdentifierMessage(node), ts.declarationNameToString(node))); + } + } + } + function getStrictModeIdentifierMessage(node) { + if (ts.getAncestor(node, 204) || ts.getAncestor(node, 177)) { + 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 === 65) { + var span = ts.getErrorSpanForNode(file, node.expression); + file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, ts.Diagnostics.delete_cannot_be_called_on_an_identifier_in_strict_mode)); + } + } + function isEvalOrArgumentsIdentifier(node) { + return node.kind === 65 && + (node.text === "eval" || node.text === "arguments"); + } + function checkStrictModeEvalOrArguments(contextNode, name) { + if (name && name.kind === 65) { + var identifier = name; + if (isEvalOrArgumentsIdentifier(identifier)) { + var span = ts.getErrorSpanForNode(file, name); + file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, getStrictModeEvalOrArgumentsMessage(contextNode), identifier.text)); + } + } + } + function getStrictModeEvalOrArgumentsMessage(node) { + if (ts.getAncestor(node, 204) || ts.getAncestor(node, 177)) { + 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 checkStrictModeNumericLiteral(node) { + if (inStrictMode && node.flags & 16384) { + 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 === 38 || node.operator === 39) { + checkStrictModeEvalOrArguments(node, node.operand); + } + } + } + function checkStrictModeWithStatement(node) { + if (inStrictMode) { + grammarErrorOnFirstToken(node, ts.Diagnostics.with_statements_are_not_allowed_in_strict_mode); + } + } + function grammarErrorOnFirstToken(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) { node.parent = parent; + var savedInStrictMode = inStrictMode; + if (!savedInStrictMode) { + updateStrictMode(node); + } + bindWorker(node); + bindChildren(node); + inStrictMode = savedInStrictMode; + } + function updateStrictMode(node) { switch (node.kind) { - case 129: - bindDeclaration(node, 262144, 530912, false); - break; - case 130: - bindParameter(node); - break; - case 199: - case 153: - if (ts.isBindingPattern(node.name)) { - bindChildren(node, 0, false); + case 230: + case 209: + updateStrictModeStatementList(node.statements); + return; + case 182: + if (ts.isFunctionLike(node.parent)) { + updateStrictModeStatementList(node.statements); } - else if (ts.isBlockOrCatchScoped(node)) { - bindBlockScopedVariableDeclaration(node); - } - else if (ts.isParameterDeclaration(node)) { - bindDeclaration(node, 1, 107455, false); - } - else { - bindDeclaration(node, 1, 107454, false); - } - break; - case 133: - case 132: - bindPropertyOrMethodOrAccessor(node, 4 | (node.questionToken ? 536870912 : 0), 107455, false); - break; - case 225: + return; + case 204: + case 177: + inStrictMode = true; + return; + } + } + function updateStrictModeStatementList(statements) { + for (var _i = 0; _i < statements.length; _i++) { + var statement = statements[_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 65: + return checkStrictModeIdentifier(node); + case 172: + return checkStrictModeBinaryExpression(node); case 226: - bindPropertyOrMethodOrAccessor(node, 4, 107455, false); - break; + return checkStrictModeCatchClause(node); + case 167: + return checkStrictModeDeleteExpression(node); + case 7: + return checkStrictModeNumericLiteral(node); + case 171: + return checkStrictModePostfixUnaryExpression(node); + case 170: + return checkStrictModePrefixUnaryExpression(node); + case 195: + return checkStrictModeWithStatement(node); + case 130: + return declareSymbolAndAddToSymbolTable(node, 262144, 530912); + case 131: + return bindParameter(node); + case 201: + case 155: + return bindVariableDeclarationOrBindingElement(node); + case 134: + case 133: + return bindPropertyOrMethodOrAccessor(node, 4 | (node.questionToken ? 536870912 : 0), 107455); case 227: - bindPropertyOrMethodOrAccessor(node, 8, 107455, false); - break; - case 139: + case 228: + return bindPropertyOrMethodOrAccessor(node, 4, 107455); + case 229: + return bindPropertyOrMethodOrAccessor(node, 8, 107455); case 140: case 141: - bindDeclaration(node, 131072, 0, false); - break; - case 135: - case 134: - bindPropertyOrMethodOrAccessor(node, 8192 | (node.questionToken ? 536870912 : 0), ts.isObjectLiteralMethod(node) ? 107455 : 99263, true); - break; - case 201: - bindDeclaration(node, 16, 106927, true); - break; + case 142: + return declareSymbolAndAddToSymbolTable(node, 131072, 0); case 136: - bindDeclaration(node, 16384, 0, true); - break; - case 137: - bindPropertyOrMethodOrAccessor(node, 32768, 41919, true); - break; - case 138: - bindPropertyOrMethodOrAccessor(node, 65536, 74687, true); - break; - case 143: - case 144: - bindFunctionOrConstructorType(node); - break; - case 146: - bindAnonymousDeclaration(node, 2048, "__type", false); - break; - case 155: - bindAnonymousDeclaration(node, 4096, "__object", false); - break; - case 163: - case 164: - bindAnonymousDeclaration(node, 16, "__function", true); - break; - case 175: - bindAnonymousDeclaration(node, 32, "__class", false); - break; - case 224: - bindCatchVariableDeclaration(node); - break; - case 202: - bindBlockScopedDeclaration(node, 32, 899583); - break; + case 135: + return bindPropertyOrMethodOrAccessor(node, 8192 | (node.questionToken ? 536870912 : 0), ts.isObjectLiteralMethod(node) ? 107455 : 99263); case 203: - bindDeclaration(node, 64, 792992, false); - break; + checkStrictModeFunctionName(node); + return declareSymbolAndAddToSymbolTable(node, 16, 106927); + case 137: + return declareSymbolAndAddToSymbolTable(node, 16384, 0); + case 138: + return bindPropertyOrMethodOrAccessor(node, 32768, 41919); + case 139: + return bindPropertyOrMethodOrAccessor(node, 65536, 74687); + case 145: + case 146: + return bindFunctionOrConstructorType(node); + case 148: + return bindAnonymousDeclaration(node, 2048, "__type"); + case 157: + return bindObjectLiteralExpression(node); + case 165: + case 166: + checkStrictModeFunctionName(node); + return bindAnonymousDeclaration(node, 16, "__function"); + case 177: case 204: - bindDeclaration(node, 524288, 793056, false); - break; + return bindClassLikeDeclaration(node); case 205: - if (ts.isConst(node)) { - bindDeclaration(node, 128, 899967, false); - } - else { - bindDeclaration(node, 256, 899327, false); - } - break; + return bindBlockScopedDeclaration(node, 64, 792992); case 206: - bindModuleDeclaration(node); - break; - case 209: - case 212: - case 214: - case 218: - bindDeclaration(node, 8388608, 8388608, false); - break; - case 211: - if (node.name) { - bindDeclaration(node, 8388608, 8388608, false); - } - else { - bindChildren(node, 0, false); - } - break; - case 216: - if (!node.exportClause) { - declareSymbol(container.symbol.exports, container.symbol, node, 1073741824, 0); - } - bindChildren(node, 0, false); - break; - case 215: - if (node.expression.kind === 65) { - declareSymbol(container.symbol.exports, container.symbol, node, 8388608, 107455 | 8388608); - } - else { - declareSymbol(container.symbol.exports, container.symbol, node, 4, 107455 | 8388608); - } - bindChildren(node, 0, false); - break; - case 228: - setExportContextFlag(node); - if (ts.isExternalModule(node)) { - bindAnonymousDeclaration(node, 512, '"' + ts.removeFileExtension(node.fileName) + '"', true); - break; - } - case 180: - bindChildren(node, 0, !ts.isFunctionLike(node.parent)); - break; - case 224: - case 187: - case 188: - case 189: + return bindBlockScopedDeclaration(node, 524288, 793056); + case 207: + return bindEnumDeclaration(node); case 208: - bindChildren(node, 0, true); - break; - default: - var saveParent = parent; - parent = node; - ts.forEachChild(node, bind); - parent = saveParent; + return bindModuleDeclaration(node); + case 211: + case 214: + case 216: + case 220: + return declareSymbolAndAddToSymbolTable(node, 8388608, 8388608); + case 213: + return bindImportClause(node); + case 218: + return bindExportDeclaration(node); + case 217: + return bindExportAssignment(node); + case 230: + return bindSourceFileIfExternalModule(); + } + } + function bindSourceFileIfExternalModule() { + setExportContextFlag(file); + if (ts.isExternalModule(file)) { + bindAnonymousDeclaration(file, 512, '"' + ts.removeFileExtension(file.fileName) + '"'); + } + } + function bindExportAssignment(node) { + if (!container.symbol || !container.symbol.exports) { + bindAnonymousDeclaration(node, 8388608, getDeclarationName(node)); + } + else if (node.expression.kind === 65) { + declareSymbol(container.symbol.exports, container.symbol, node, 8388608, 107455 | 8388608); + } + else { + declareSymbol(container.symbol.exports, container.symbol, node, 4, 107455 | 8388608); + } + } + function bindExportDeclaration(node) { + if (!container.symbol || !container.symbol.exports) { + bindAnonymousDeclaration(node, 1073741824, getDeclarationName(node)); + } + else if (!node.exportClause) { + declareSymbol(container.symbol.exports, container.symbol, node, 1073741824, 0); + } + } + function bindImportClause(node) { + if (node.name) { + declareSymbolAndAddToSymbolTable(node, 8388608, 8388608); + } + } + function bindClassLikeDeclaration(node) { + if (node.kind === 204) { + bindBlockScopedDeclaration(node, 32, 899583); + } + else { + bindAnonymousDeclaration(node, 32, "__class"); + } + var symbol = node.symbol; + var prototypeSymbol = createSymbol(4 | 134217728, "prototype"); + if (ts.hasProperty(symbol.exports, prototypeSymbol.name)) { + if (node.name) { + node.name.parent = node; + } + file.bindDiagnostics.push(ts.createDiagnosticForNode(symbol.exports[prototypeSymbol.name].declarations[0], ts.Diagnostics.Duplicate_identifier_0, prototypeSymbol.name)); + } + symbol.exports[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) { + checkStrictModeEvalOrArguments(node, node.name); + } if (ts.isBindingPattern(node.name)) { - bindAnonymousDeclaration(node, 1, getDestructuringParameterName(node), false); + bindAnonymousDeclaration(node, 1, getDestructuringParameterName(node)); } else { - bindDeclaration(node, 1, 107455, false); + declareSymbolAndAddToSymbolTable(node, 1, 107455); } if (node.flags & 112 && - node.parent.kind === 136 && - (node.parent.parent.kind === 202 || node.parent.parent.kind === 175)) { + node.parent.kind === 137 && + (node.parent.parent.kind === 204 || node.parent.parent.kind === 177)) { var classDeclaration = node.parent.parent; declareSymbol(classDeclaration.symbol.members, classDeclaration.symbol, node, 4, 107455); } } - function bindPropertyOrMethodOrAccessor(node, symbolKind, symbolExcludes, isBlockScopeContainer) { - if (ts.hasDynamicName(node)) { - bindAnonymousDeclaration(node, symbolKind, "__computed", isBlockScopeContainer); - } - else { - bindDeclaration(node, symbolKind, symbolExcludes, isBlockScopeContainer); - } + function bindPropertyOrMethodOrAccessor(node, symbolFlags, symbolExcludes) { + return ts.hasDynamicName(node) + ? bindAnonymousDeclaration(node, symbolFlags, "__computed") + : declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes); } } })(ts || (ts = {})); @@ -3244,7 +3532,7 @@ var ts; ts.getDeclarationOfKind = getDeclarationOfKind; var stringWriters = []; function getSingleLineStringWriter() { - if (stringWriters.length == 0) { + if (stringWriters.length === 0) { var str = ""; var writeText = function (text) { return str += text; }; return { @@ -3277,21 +3565,21 @@ var ts; ts.getFullWidth = getFullWidth; function containsParseError(node) { aggregateChildData(node); - return (node.parserContextFlags & 64) !== 0; + return (node.parserContextFlags & 128) !== 0; } ts.containsParseError = containsParseError; function aggregateChildData(node) { - if (!(node.parserContextFlags & 128)) { + if (!(node.parserContextFlags & 256)) { var thisNodeOrAnySubNodesHasError = ((node.parserContextFlags & 32) !== 0) || ts.forEachChild(node, containsParseError); if (thisNodeOrAnySubNodesHasError) { - node.parserContextFlags |= 64; + node.parserContextFlags |= 128; } - node.parserContextFlags |= 128; + node.parserContextFlags |= 256; } } function getSourceFileOfNode(node) { - while (node && node.kind !== 228) { + while (node && node.kind !== 230) { node = node.parent; } return node; @@ -3380,15 +3668,15 @@ var ts; return current; } switch (current.kind) { - case 228: + case 230: + case 210: + case 226: case 208: - case 224: - case 206: - case 187: - case 188: case 189: + case 190: + case 191: return current; - case 180: + case 182: if (!isFunctionLike(current.parent)) { return current; } @@ -3399,9 +3687,9 @@ var ts; ts.getEnclosingBlockScopeContainer = getEnclosingBlockScopeContainer; function isCatchClauseVariableDeclaration(declaration) { return declaration && - declaration.kind === 199 && + declaration.kind === 201 && declaration.parent && - declaration.parent.kind === 224; + declaration.parent.kind === 226; } ts.isCatchClauseVariableDeclaration = isCatchClauseVariableDeclaration; function declarationNameToString(name) { @@ -3437,22 +3725,22 @@ var ts; function getErrorSpanForNode(sourceFile, node) { var errorNode = node; switch (node.kind) { - case 228: + case 230: 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 199: - case 153: - case 202: - case 175: - case 203: - case 206: - case 205: - case 227: case 201: - case 163: + case 155: + case 204: + case 177: + case 205: + case 208: + case 207: + case 229: + case 203: + case 165: errorNode = node.name; break; } @@ -3474,11 +3762,11 @@ var ts; } ts.isDeclarationFile = isDeclarationFile; function isConstEnumDeclaration(node) { - return node.kind === 205 && isConst(node); + return node.kind === 207 && isConst(node); } ts.isConstEnumDeclaration = isConstEnumDeclaration; function walkUpBindingElementsAndPatterns(node) { - while (node && (node.kind === 153 || isBindingPattern(node))) { + while (node && (node.kind === 155 || isBindingPattern(node))) { node = node.parent; } return node; @@ -3486,14 +3774,14 @@ var ts; function getCombinedNodeFlags(node) { node = walkUpBindingElementsAndPatterns(node); var flags = node.flags; - if (node.kind === 199) { + if (node.kind === 201) { node = node.parent; } - if (node && node.kind === 200) { + if (node && node.kind === 202) { flags |= node.flags; node = node.parent; } - if (node && node.kind === 181) { + if (node && node.kind === 183) { flags |= node.flags; } return flags; @@ -3508,11 +3796,11 @@ var ts; } ts.isLet = isLet; function isPrologueDirective(node) { - return node.kind === 183 && node.expression.kind === 8; + return node.kind === 185 && node.expression.kind === 8; } ts.isPrologueDirective = isPrologueDirective; function getLeadingCommentRangesOfNode(node, sourceFileOfNode) { - if (node.kind === 130 || node.kind === 129) { + if (node.kind === 131 || node.kind === 130) { return ts.concatenate(ts.getTrailingCommentRanges(sourceFileOfNode.text, node.pos), ts.getLeadingCommentRanges(sourceFileOfNode.text, node.pos)); } else { @@ -3530,43 +3818,143 @@ var ts; } ts.getJsDocComments = getJsDocComments; ts.fullTripleSlashReferencePathRegEx = /^(\/\/\/\s*/; + function isTypeNode(node) { + if (144 <= node.kind && node.kind <= 152) { + return true; + } + switch (node.kind) { + case 112: + case 121: + case 123: + case 113: + case 124: + return true; + case 99: + return node.parent.kind !== 169; + case 8: + return node.parent.kind === 131; + case 179: + return !isExpressionWithTypeArgumentsInClassExtendsClause(node); + case 65: + if (node.parent.kind === 128 && node.parent.right === node) { + node = node.parent; + } + else if (node.parent.kind === 158 && node.parent.name === node) { + node = node.parent; + } + case 128: + case 158: + ts.Debug.assert(node.kind === 65 || node.kind === 128 || node.kind === 158, "'node' was expected to be a qualified name, identifier or property access in 'isTypeNode'."); + var parent_1 = node.parent; + if (parent_1.kind === 147) { + return false; + } + if (144 <= parent_1.kind && parent_1.kind <= 152) { + return true; + } + switch (parent_1.kind) { + case 179: + return !isExpressionWithTypeArgumentsInClassExtendsClause(parent_1); + case 130: + return node === parent_1.constraint; + case 134: + case 133: + case 131: + case 201: + return node === parent_1.type; + case 203: + case 165: + case 166: + case 137: + case 136: + case 135: + case 138: + case 139: + return node === parent_1.type; + case 140: + case 141: + case 142: + return node === parent_1.type; + case 163: + return node === parent_1.type; + case 160: + case 161: + return parent_1.typeArguments && ts.indexOf(parent_1.typeArguments, node) >= 0; + case 162: + return false; + } + } + return false; + } + ts.isTypeNode = isTypeNode; function forEachReturnStatement(body, visitor) { return traverse(body); function traverse(node) { switch (node.kind) { - case 192: + case 194: return visitor(node); - case 208: - case 180: - case 184: - case 185: + case 210: + case 182: case 186: case 187: case 188: case 189: - case 193: - case 194: - case 221: - case 222: + case 190: + case 191: case 195: - case 197: + case 196: + case 223: case 224: + case 197: + case 199: + case 226: return ts.forEachChild(node, traverse); } } } ts.forEachReturnStatement = forEachReturnStatement; + function forEachYieldExpression(body, visitor) { + return traverse(body); + function traverse(node) { + switch (node.kind) { + case 175: + visitor(node); + var operand = node.expression; + if (operand) { + traverse(operand); + } + case 207: + case 205: + case 208: + case 206: + case 204: + return; + default: + if (isFunctionLike(node)) { + var name_4 = node.name; + if (name_4 && name_4.kind === 129) { + traverse(name_4.expression); + return; + } + } + else if (!isTypeNode(node)) { + ts.forEachChild(node, traverse); + } + } + } + } + ts.forEachYieldExpression = forEachYieldExpression; function isVariableLike(node) { if (node) { switch (node.kind) { - case 153: + case 155: + case 229: + case 131: case 227: - case 130: - case 225: + case 134: case 133: - case 132: - case 226: - case 199: + case 228: + case 201: return true; } } @@ -3576,30 +3964,36 @@ var ts; function isAccessor(node) { if (node) { switch (node.kind) { - case 137: case 138: + case 139: return true; } } return false; } ts.isAccessor = isAccessor; + function isClassLike(node) { + if (node) { + return node.kind === 204 || node.kind === 177; + } + } + ts.isClassLike = isClassLike; function isFunctionLike(node) { if (node) { switch (node.kind) { - case 136: - case 163: - case 201: - case 164: - case 135: - case 134: case 137: + case 165: + case 203: + case 166: + case 136: + case 135: case 138: case 139: case 140: case 141: - case 143: - case 144: + case 142: + case 145: + case 146: return true; } } @@ -3607,11 +4001,11 @@ var ts; } ts.isFunctionLike = isFunctionLike; function isFunctionBlock(node) { - return node && node.kind === 180 && isFunctionLike(node.parent); + return node && node.kind === 182 && isFunctionLike(node.parent); } ts.isFunctionBlock = isFunctionBlock; function isObjectLiteralMethod(node) { - return node && node.kind === 135 && node.parent.kind === 155; + return node && node.kind === 136 && node.parent.kind === 157; } ts.isObjectLiteralMethod = isObjectLiteralMethod; function getContainingFunction(node) { @@ -3630,36 +4024,36 @@ var ts; return undefined; } switch (node.kind) { - case 128: - if (node.parent.parent.kind === 202) { + case 129: + if (node.parent.parent.kind === 204) { return node; } node = node.parent; break; - case 131: - if (node.parent.kind === 130 && isClassElement(node.parent.parent)) { + case 132: + if (node.parent.kind === 131 && isClassElement(node.parent.parent)) { node = node.parent.parent; } else if (isClassElement(node.parent)) { node = node.parent; } break; - case 164: + case 166: if (!includeArrowFunctions) { continue; } - case 201: - case 163: - case 206: - case 133: - case 132: - case 135: + case 203: + case 165: + case 208: case 134: + case 133: case 136: + case 135: case 137: case 138: - case 205: - case 228: + case 139: + case 207: + case 230: return node; } } @@ -3671,40 +4065,40 @@ var ts; if (!node) return node; switch (node.kind) { - case 128: - if (node.parent.parent.kind === 202) { + case 129: + if (node.parent.parent.kind === 204) { return node; } node = node.parent; break; - case 131: - if (node.parent.kind === 130 && isClassElement(node.parent.parent)) { + case 132: + if (node.parent.kind === 131 && isClassElement(node.parent.parent)) { node = node.parent.parent; } else if (isClassElement(node.parent)) { node = node.parent; } break; - case 201: - case 163: - case 164: + case 203: + case 165: + case 166: if (!includeFunctions) { continue; } - case 133: - case 132: - case 135: case 134: + case 133: case 136: + case 135: case 137: case 138: + case 139: return node; } } } ts.getSuperContainer = getSuperContainer; function getInvokedExpression(node) { - if (node.kind === 160) { + if (node.kind === 162) { return node.tag; } return node.expression; @@ -3712,40 +4106,40 @@ var ts; ts.getInvokedExpression = getInvokedExpression; function nodeCanBeDecorated(node) { switch (node.kind) { - case 202: + case 204: return true; - case 133: - return node.parent.kind === 202; - case 130: - return node.parent.body && node.parent.parent.kind === 202; - case 137: + case 134: + return node.parent.kind === 204; + case 131: + return node.parent.body && node.parent.parent.kind === 204; case 138: - case 135: - return node.body && node.parent.kind === 202; + case 139: + case 136: + return node.body && node.parent.kind === 204; } return false; } ts.nodeCanBeDecorated = nodeCanBeDecorated; function nodeIsDecorated(node) { switch (node.kind) { - case 202: + case 204: if (node.decorators) { return true; } return false; - case 133: - case 130: + case 134: + case 131: if (node.decorators) { return true; } return false; - case 137: + case 138: if (node.body && node.decorators) { return true; } return false; - case 135: - case 138: + case 136: + case 139: if (node.body && node.decorators) { return true; } @@ -3756,10 +4150,10 @@ var ts; ts.nodeIsDecorated = nodeIsDecorated; function childIsDecorated(node) { switch (node.kind) { - case 202: + case 204: return ts.forEach(node.members, nodeOrChildIsDecorated); - case 135: - case 138: + case 136: + case 139: return ts.forEach(node.parameters, nodeIsDecorated); } return false; @@ -3777,8 +4171,6 @@ var ts; case 95: case 80: case 9: - case 154: - case 155: case 156: case 157: case 158: @@ -3787,72 +4179,77 @@ var ts; case 161: case 162: case 163: - case 175: case 164: - case 167: case 165: + case 177: case 166: - case 168: case 169: + case 167: + case 168: case 170: case 171: - case 174: case 172: - case 10: + case 173: case 176: + case 174: + case 10: + case 178: + case 175: return true; - case 127: - while (node.parent.kind === 127) { + case 128: + while (node.parent.kind === 128) { node = node.parent; } - return node.parent.kind === 145; + return node.parent.kind === 147; case 65: - if (node.parent.kind === 145) { + if (node.parent.kind === 147) { return true; } case 7: case 8: - var parent_1 = node.parent; - switch (parent_1.kind) { - case 199: - case 130: + var parent_2 = node.parent; + switch (parent_2.kind) { + case 201: + case 131: + case 134: case 133: - case 132: + case 229: case 227: - case 225: - case 153: - return parent_1.initializer === node; - case 183: - case 184: + case 155: + return parent_2.initializer === node; case 185: case 186: - case 192: - case 193: - case 194: - case 221: - case 196: - case 194: - return parent_1.expression === node; case 187: - var forStatement = parent_1; - return (forStatement.initializer === node && forStatement.initializer.kind !== 200) || + case 188: + case 194: + case 195: + case 196: + case 223: + case 198: + case 196: + return parent_2.expression === node; + case 189: + var forStatement = parent_2; + return (forStatement.initializer === node && forStatement.initializer.kind !== 202) || forStatement.condition === node || forStatement.incrementor === node; - case 188: - case 189: - var forInStatement = parent_1; - return (forInStatement.initializer === node && forInStatement.initializer.kind !== 200) || + case 190: + case 191: + var forInStatement = parent_2; + return (forInStatement.initializer === node && forInStatement.initializer.kind !== 202) || forInStatement.expression === node; - case 161: - return node === parent_1.expression; - case 178: - return node === parent_1.expression; - case 128: - return node === parent_1.expression; - case 131: + case 163: + return node === parent_2.expression; + case 180: + return node === parent_2.expression; + case 129: + return node === parent_2.expression; + case 132: return true; + case 179: + return parent_2.expression === node && isExpressionWithTypeArgumentsInClassExtendsClause(parent_2); default: - if (isExpression(parent_1)) { + if (isExpression(parent_2)) { return true; } } @@ -3867,7 +4264,7 @@ var ts; } ts.isInstantiatedModule = isInstantiatedModule; function isExternalModuleImportEqualsDeclaration(node) { - return node.kind === 209 && node.moduleReference.kind === 220; + return node.kind === 211 && node.moduleReference.kind === 222; } ts.isExternalModuleImportEqualsDeclaration = isExternalModuleImportEqualsDeclaration; function getExternalModuleImportEqualsDeclarationExpression(node) { @@ -3876,50 +4273,108 @@ var ts; } ts.getExternalModuleImportEqualsDeclarationExpression = getExternalModuleImportEqualsDeclarationExpression; function isInternalModuleImportEqualsDeclaration(node) { - return node.kind === 209 && node.moduleReference.kind !== 220; + return node.kind === 211 && node.moduleReference.kind !== 222; } ts.isInternalModuleImportEqualsDeclaration = isInternalModuleImportEqualsDeclaration; function getExternalModuleName(node) { - if (node.kind === 210) { + if (node.kind === 212) { return node.moduleSpecifier; } - if (node.kind === 209) { + if (node.kind === 211) { var reference = node.moduleReference; - if (reference.kind === 220) { + if (reference.kind === 222) { return reference.expression; } } - if (node.kind === 216) { + if (node.kind === 218) { return node.moduleSpecifier; } } ts.getExternalModuleName = getExternalModuleName; - function hasDotDotDotToken(node) { - return node && node.kind === 130 && node.dotDotDotToken !== undefined; - } - ts.hasDotDotDotToken = hasDotDotDotToken; function hasQuestionToken(node) { if (node) { switch (node.kind) { - case 130: + case 131: return node.questionToken !== undefined; + case 136: case 135: - case 134: return node.questionToken !== undefined; - case 226: - case 225: + case 228: + case 227: + case 134: case 133: - case 132: return node.questionToken !== undefined; } } return false; } ts.hasQuestionToken = hasQuestionToken; - function hasRestParameters(s) { - return s.parameters.length > 0 && ts.lastOrUndefined(s.parameters).dotDotDotToken !== undefined; + function isJSDocConstructSignature(node) { + return node.kind === 243 && + node.parameters.length > 0 && + node.parameters[0].type.kind === 245; } - ts.hasRestParameters = hasRestParameters; + ts.isJSDocConstructSignature = isJSDocConstructSignature; + function getJSDocTag(node, kind) { + if (node && node.jsDocComment) { + for (var _i = 0, _a = node.jsDocComment.tags; _i < _a.length; _i++) { + var tag = _a[_i]; + if (tag.kind === kind) { + return tag; + } + } + } + } + function getJSDocTypeTag(node) { + return getJSDocTag(node, 251); + } + ts.getJSDocTypeTag = getJSDocTypeTag; + function getJSDocReturnTag(node) { + return getJSDocTag(node, 250); + } + ts.getJSDocReturnTag = getJSDocReturnTag; + function getJSDocTemplateTag(node) { + return getJSDocTag(node, 252); + } + ts.getJSDocTemplateTag = getJSDocTemplateTag; + function getCorrespondingJSDocParameterTag(parameter) { + if (parameter.name && parameter.name.kind === 65) { + var parameterName = parameter.name.text; + var docComment = parameter.parent.jsDocComment; + if (docComment) { + return ts.forEach(docComment.tags, function (t) { + if (t.kind === 249) { + var parameterTag = t; + var name_5 = parameterTag.preParameterName || parameterTag.postParameterName; + if (name_5.text === parameterName) { + return t; + } + } + }); + } + } + } + ts.getCorrespondingJSDocParameterTag = getCorrespondingJSDocParameterTag; + function hasRestParameter(s) { + return isRestParameter(ts.lastOrUndefined(s.parameters)); + } + ts.hasRestParameter = hasRestParameter; + function isRestParameter(node) { + if (node) { + if (node.parserContextFlags & 64) { + if (node.type && node.type.kind === 244) { + return true; + } + var paramTag = getCorrespondingJSDocParameterTag(node); + if (paramTag && paramTag.typeExpression) { + return paramTag.typeExpression.type.kind === 244; + } + } + return node.dotDotDotToken !== undefined; + } + return false; + } + ts.isRestParameter = isRestParameter; function isLiteralKind(kind) { return 7 <= kind && kind <= 10; } @@ -3933,7 +4388,7 @@ var ts; } ts.isTemplateLiteralKind = isTemplateLiteralKind; function isBindingPattern(node) { - return !!node && (node.kind === 152 || node.kind === 151); + return !!node && (node.kind === 154 || node.kind === 153); } ts.isBindingPattern = isBindingPattern; function isInAmbientContext(node) { @@ -3948,33 +4403,33 @@ var ts; ts.isInAmbientContext = isInAmbientContext; function isDeclaration(node) { switch (node.kind) { - case 164: - case 153: - case 202: - case 136: - case 205: - case 227: - case 218: - case 201: - case 163: - case 137: - case 211: - case 209: - case 214: - case 203: - case 135: - case 134: - case 206: - case 212: - case 130: - case 225: - case 133: - case 132: - case 138: - case 226: + case 166: + case 155: case 204: - case 129: - case 199: + case 137: + case 207: + case 229: + case 220: + case 203: + case 165: + case 138: + case 213: + case 211: + case 216: + case 205: + case 136: + case 135: + case 208: + case 214: + case 131: + case 227: + case 134: + case 133: + case 139: + case 228: + case 206: + case 130: + case 201: return true; } return false; @@ -3982,25 +4437,25 @@ var ts; ts.isDeclaration = isDeclaration; function isStatement(n) { switch (n.kind) { - case 191: - case 190: - case 198: - case 185: - case 183: - case 182: - case 188: - case 189: - case 187: - case 184: - case 195: - case 192: - case 194: - case 94: - case 197: - case 181: - case 186: case 193: - case 215: + case 192: + case 200: + case 187: + case 185: + case 184: + case 190: + case 191: + case 189: + case 186: + case 197: + case 194: + case 196: + case 94: + case 199: + case 183: + case 188: + case 195: + case 217: return true; default: return false; @@ -4009,13 +4464,13 @@ var ts; ts.isStatement = isStatement; function isClassElement(n) { switch (n.kind) { - case 136: - case 133: - case 135: case 137: - case 138: case 134: - case 141: + case 136: + case 138: + case 139: + case 135: + case 142: return true; default: return false; @@ -4027,7 +4482,7 @@ var ts; return false; } var parent = name.parent; - if (parent.kind === 214 || parent.kind === 218) { + if (parent.kind === 216 || parent.kind === 220) { if (parent.propertyName) { return true; } @@ -4038,13 +4493,43 @@ var ts; return false; } ts.isDeclarationName = isDeclarationName; + function isIdentifierName(node) { + var parent = node.parent; + switch (parent.kind) { + case 134: + case 133: + case 136: + case 135: + case 138: + case 139: + case 229: + case 227: + case 158: + return parent.name === node; + case 128: + if (parent.right === node) { + while (parent.kind === 128) { + parent = parent.parent; + } + return parent.kind === 147; + } + return false; + case 155: + case 216: + return parent.propertyName === node; + case 220: + return true; + } + return false; + } + ts.isIdentifierName = isIdentifierName; function isAliasSymbolDeclaration(node) { - return node.kind === 209 || - node.kind === 211 && !!node.name || - node.kind === 212 || + return node.kind === 211 || + node.kind === 213 && !!node.name || node.kind === 214 || - node.kind === 218 || - node.kind === 215 && node.expression.kind === 65; + node.kind === 216 || + node.kind === 220 || + node.kind === 217 && node.expression.kind === 65; } ts.isAliasSymbolDeclaration = isAliasSymbolDeclaration; function getClassExtendsHeritageClauseElement(node) { @@ -4127,7 +4612,7 @@ var ts; } ts.getFileReferenceFromReferencePath = getFileReferenceFromReferencePath; function isKeyword(token) { - return 66 <= token && token <= 126; + return 66 <= token && token <= 127; } ts.isKeyword = isKeyword; function isTrivia(token) { @@ -4136,19 +4621,19 @@ var ts; ts.isTrivia = isTrivia; function hasDynamicName(declaration) { return declaration.name && - declaration.name.kind === 128 && + declaration.name.kind === 129 && !isWellKnownSymbolSyntactically(declaration.name.expression); } ts.hasDynamicName = hasDynamicName; function isWellKnownSymbolSyntactically(node) { - return node.kind === 156 && isESSymbolIdentifier(node.expression); + return node.kind === 158 && isESSymbolIdentifier(node.expression); } ts.isWellKnownSymbolSyntactically = isWellKnownSymbolSyntactically; function getPropertyNameForPropertyNameNode(name) { if (name.kind === 65 || name.kind === 8 || name.kind === 7) { return name.text; } - if (name.kind === 128) { + if (name.kind === 129) { var nameExpression = name.expression; if (isWellKnownSymbolSyntactically(nameExpression)) { var rightHandSideName = nameExpression.name.text; @@ -4183,18 +4668,18 @@ var ts; ts.isModifier = isModifier; function isParameterDeclaration(node) { var root = getRootDeclaration(node); - return root.kind === 130; + return root.kind === 131; } ts.isParameterDeclaration = isParameterDeclaration; function getRootDeclaration(node) { - while (node.kind === 153) { + while (node.kind === 155) { node = node.parent.parent; } return node; } ts.getRootDeclaration = getRootDeclaration; function nodeStartsNewLexicalEnvironment(n) { - return isFunctionLike(n) || n.kind === 206 || n.kind === 228; + return isFunctionLike(n) || n.kind === 208 || n.kind === 230; } ts.nodeStartsNewLexicalEnvironment = nodeStartsNewLexicalEnvironment; function nodeIsSynthesized(node) { @@ -4418,7 +4903,7 @@ var ts; ts.getLineOfLocalPosition = getLineOfLocalPosition; function getFirstConstructorWithBody(node) { return ts.forEach(node.members, function (member) { - if (member.kind === 136 && nodeIsPresent(member.body)) { + if (member.kind === 137 && nodeIsPresent(member.body)) { return member; } }); @@ -4427,7 +4912,7 @@ var ts; function shouldEmitToOwnFile(sourceFile, compilerOptions) { if (!isDeclarationFile(sourceFile)) { if ((isExternalModule(sourceFile) || !compilerOptions.out)) { - return compilerOptions.separateCompilation || !ts.fileExtensionIs(sourceFile.fileName, ".js"); + return compilerOptions.isolatedModules || !ts.fileExtensionIs(sourceFile.fileName, ".js"); } return false; } @@ -4441,10 +4926,10 @@ var ts; var setAccessor; if (hasDynamicName(accessor)) { firstAccessor = accessor; - if (accessor.kind === 137) { + if (accessor.kind === 138) { getAccessor = accessor; } - else if (accessor.kind === 138) { + else if (accessor.kind === 139) { setAccessor = accessor; } else { @@ -4453,7 +4938,7 @@ var ts; } else { ts.forEach(declarations, function (member) { - if ((member.kind === 137 || member.kind === 138) + if ((member.kind === 138 || member.kind === 139) && (member.flags & 128) === (accessor.flags & 128)) { var memberName = getPropertyNameForPropertyNameNode(member.name); var accessorName = getPropertyNameForPropertyNameNode(accessor.name); @@ -4464,10 +4949,10 @@ var ts; else if (!secondAccessor) { secondAccessor = member; } - if (member.kind === 137 && !getAccessor) { + if (member.kind === 138 && !getAccessor) { getAccessor = member; } - if (member.kind === 138 && !setAccessor) { + if (member.kind === 139 && !setAccessor) { setAccessor = member; } } @@ -4588,22 +5073,22 @@ var ts; function isLeftHandSideExpression(expr) { if (expr) { switch (expr.kind) { - case 156: - case 157: - case 159: case 158: + case 159: + case 161: case 160: - case 154: case 162: - case 155: - case 175: - case 163: + case 156: + case 164: + case 157: + case 177: + case 165: case 65: case 9: case 7: case 8: case 10: - case 172: + case 174: case 80: case 89: case 93: @@ -4619,6 +5104,12 @@ var ts; return token >= 53 && token <= 64; } ts.isAssignmentOperator = isAssignmentOperator; + function isExpressionWithTypeArgumentsInClassExtendsClause(node) { + return node.kind === 179 && + node.parent.token === 79 && + node.parent.parent.kind === 204; + } + ts.isExpressionWithTypeArgumentsInClassExtendsClause = isExpressionWithTypeArgumentsInClassExtendsClause; function isSupportedExpressionWithTypeArguments(node) { return isSupportedExpressionWithTypeArgumentsRest(node.expression); } @@ -4627,7 +5118,7 @@ var ts; if (node.kind === 65) { return true; } - else if (node.kind === 156) { + else if (node.kind === 158) { return isSupportedExpressionWithTypeArgumentsRest(node.expression); } else { @@ -4635,14 +5126,18 @@ var ts; } } function isRightSideOfQualifiedNameOrPropertyAccess(node) { - return (node.parent.kind === 127 && node.parent.right === node) || - (node.parent.kind === 156 && node.parent.name === node); + return (node.parent.kind === 128 && node.parent.right === node) || + (node.parent.kind === 158 && node.parent.name === node); } ts.isRightSideOfQualifiedNameOrPropertyAccess = isRightSideOfQualifiedNameOrPropertyAccess; function getLocalSymbolForExportDefault(symbol) { return symbol && symbol.valueDeclaration && (symbol.valueDeclaration.flags & 256) ? symbol.valueDeclaration.localSymbol : undefined; } ts.getLocalSymbolForExportDefault = getLocalSymbolForExportDefault; + function isJavaScript(fileName) { + return ts.fileExtensionIs(fileName, ".js"); + } + ts.isJavaScript = isJavaScript; function getExpandedCharCodes(input) { var output = []; var length = input.length; @@ -4697,6 +5192,21 @@ var ts; return result; } ts.convertToBase64 = convertToBase64; + var carriageReturnLineFeed = "\r\n"; + var lineFeed = "\n"; + function getNewLineCharacter(options) { + if (options.newLine === 0) { + return carriageReturnLineFeed; + } + else if (options.newLine === 1) { + return lineFeed; + } + else if (ts.sys) { + return ts.sys.newLine; + } + return carriageReturnLineFeed; + } + ts.getNewLineCharacter = getNewLineCharacter; })(ts || (ts = {})); var ts; (function (ts) { @@ -4744,6 +5254,12 @@ var ts; 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; } @@ -4813,12 +5329,22 @@ var ts; return createTextChangeRange(createTextSpanFromBounds(oldStartN, oldEndN), newEndN - oldStartN); } ts.collapseTextChangeRangesAcrossMultipleVersions = collapseTextChangeRangesAcrossMultipleVersions; + function getTypeParameterOwner(d) { + if (d && d.kind === 130) { + for (var current = d; current; current = current.parent) { + if (ts.isFunctionLike(current) || ts.isClassLike(current) || current.kind === 205) { + return current; + } + } + } + } + ts.getTypeParameterOwner = getTypeParameterOwner; })(ts || (ts = {})); /// /// var ts; (function (ts) { - var nodeConstructors = new Array(230); + var nodeConstructors = new Array(254); ts.parseTime = 0; function getNodeConstructor(kind) { return nodeConstructors[kind] || (nodeConstructors[kind] = ts.objectAllocator.getNodeConstructor(kind)); @@ -4856,20 +5382,20 @@ var ts; var visitNodes = cbNodeArray ? visitNodeArray : visitEachNode; var cbNodes = cbNodeArray || cbNode; switch (node.kind) { - case 127: + case 128: return visitNode(cbNode, node.left) || visitNode(cbNode, node.right); - case 129: + case 130: return visitNode(cbNode, node.name) || visitNode(cbNode, node.constraint) || visitNode(cbNode, node.expression); - case 130: + case 131: + case 134: case 133: - case 132: - case 225: - case 226: - case 199: - case 153: + case 227: + case 228: + case 201: + case 155: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.propertyName) || @@ -4878,24 +5404,24 @@ var ts; visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.type) || visitNode(cbNode, node.initializer); - case 143: - case 144: - case 139: + case 145: + case 146: case 140: case 141: + case 142: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNodes(cbNodes, node.typeParameters) || visitNodes(cbNodes, node.parameters) || visitNode(cbNode, node.type); - case 135: - case 134: case 136: + case 135: case 137: case 138: - case 163: - case 201: - case 164: + case 139: + case 165: + case 203: + case 166: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.asteriskToken) || @@ -4906,221 +5432,268 @@ var ts; visitNode(cbNode, node.type) || visitNode(cbNode, node.equalsGreaterThanToken) || visitNode(cbNode, node.body); - case 142: + case 144: return visitNode(cbNode, node.typeName) || visitNodes(cbNodes, node.typeArguments); - case 145: - return visitNode(cbNode, node.exprName); - case 146: - return visitNodes(cbNodes, node.members); + case 143: + return visitNode(cbNode, node.parameterName) || + visitNode(cbNode, node.type); case 147: - return visitNode(cbNode, node.elementType); + return visitNode(cbNode, node.exprName); case 148: - return visitNodes(cbNodes, node.elementTypes); + return visitNodes(cbNodes, node.members); case 149: - return visitNodes(cbNodes, node.types); + return visitNode(cbNode, node.elementType); case 150: - return visitNode(cbNode, node.type); + return visitNodes(cbNodes, node.elementTypes); case 151: + return visitNodes(cbNodes, node.types); case 152: - return visitNodes(cbNodes, node.elements); + return visitNode(cbNode, node.type); + case 153: case 154: return visitNodes(cbNodes, node.elements); - case 155: - return visitNodes(cbNodes, node.properties); case 156: + return visitNodes(cbNodes, node.elements); + case 157: + return visitNodes(cbNodes, node.properties); + case 158: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.dotToken) || visitNode(cbNode, node.name); - case 157: + case 159: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.argumentExpression); - case 158: - case 159: + case 160: + case 161: return visitNode(cbNode, node.expression) || visitNodes(cbNodes, node.typeArguments) || visitNodes(cbNodes, node.arguments); - case 160: + case 162: return visitNode(cbNode, node.tag) || visitNode(cbNode, node.template); - case 161: + case 163: return visitNode(cbNode, node.type) || visitNode(cbNode, node.expression); - case 162: - return visitNode(cbNode, node.expression); - case 165: - return visitNode(cbNode, node.expression); - case 166: + case 164: return visitNode(cbNode, node.expression); case 167: return visitNode(cbNode, node.expression); case 168: + return visitNode(cbNode, node.expression); + case 169: + return visitNode(cbNode, node.expression); + case 170: return visitNode(cbNode, node.operand); - case 173: + case 175: return visitNode(cbNode, node.asteriskToken) || visitNode(cbNode, node.expression); - case 169: + case 171: return visitNode(cbNode, node.operand); - case 170: + case 172: return visitNode(cbNode, node.left) || visitNode(cbNode, node.operatorToken) || visitNode(cbNode, node.right); - case 171: + case 173: return visitNode(cbNode, node.condition) || visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.whenTrue) || visitNode(cbNode, node.colonToken) || visitNode(cbNode, node.whenFalse); - case 174: + case 176: return visitNode(cbNode, node.expression); - case 180: - case 207: + case 182: + case 209: return visitNodes(cbNodes, node.statements); - case 228: + case 230: return visitNodes(cbNodes, node.statements) || visitNode(cbNode, node.endOfFileToken); - case 181: + case 183: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.declarationList); - case 200: + case 202: return visitNodes(cbNodes, node.declarations); - case 183: + case 185: return visitNode(cbNode, node.expression); - case 184: + case 186: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.thenStatement) || visitNode(cbNode, node.elseStatement); - case 185: + case 187: return visitNode(cbNode, node.statement) || visitNode(cbNode, node.expression); - case 186: + case 188: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.statement); - case 187: + case 189: return visitNode(cbNode, node.initializer) || visitNode(cbNode, node.condition) || visitNode(cbNode, node.incrementor) || visitNode(cbNode, node.statement); - case 188: - return visitNode(cbNode, node.initializer) || - visitNode(cbNode, node.expression) || - visitNode(cbNode, node.statement); - case 189: - return visitNode(cbNode, node.initializer) || - visitNode(cbNode, node.expression) || - visitNode(cbNode, node.statement); case 190: - case 191: - return visitNode(cbNode, node.label); - case 192: - return visitNode(cbNode, node.expression); - case 193: - return visitNode(cbNode, node.expression) || + return visitNode(cbNode, node.initializer) || + visitNode(cbNode, node.expression) || visitNode(cbNode, node.statement); + case 191: + return visitNode(cbNode, node.initializer) || + visitNode(cbNode, node.expression) || + visitNode(cbNode, node.statement); + case 192: + case 193: + return visitNode(cbNode, node.label); case 194: - return visitNode(cbNode, node.expression) || - visitNode(cbNode, node.caseBlock); - case 208: - return visitNodes(cbNodes, node.clauses); - case 221: - return visitNode(cbNode, node.expression) || - visitNodes(cbNodes, node.statements); - case 222: - return visitNodes(cbNodes, node.statements); + return visitNode(cbNode, node.expression); case 195: - return visitNode(cbNode, node.label) || + return visitNode(cbNode, node.expression) || visitNode(cbNode, node.statement); case 196: - return visitNode(cbNode, node.expression); + return visitNode(cbNode, node.expression) || + visitNode(cbNode, node.caseBlock); + case 210: + return visitNodes(cbNodes, node.clauses); + case 223: + return visitNode(cbNode, node.expression) || + visitNodes(cbNodes, node.statements); + case 224: + return visitNodes(cbNodes, node.statements); case 197: + return visitNode(cbNode, node.label) || + visitNode(cbNode, node.statement); + case 198: + return visitNode(cbNode, node.expression); + case 199: return visitNode(cbNode, node.tryBlock) || visitNode(cbNode, node.catchClause) || visitNode(cbNode, node.finallyBlock); - case 224: + case 226: return visitNode(cbNode, node.variableDeclaration) || visitNode(cbNode, node.block); - case 131: + case 132: return visitNode(cbNode, node.expression); - case 202: - case 175: - 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 203: - 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 204: + case 177: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.name) || - visitNode(cbNode, node.type); + visitNodes(cbNodes, node.typeParameters) || + visitNodes(cbNodes, node.heritageClauses) || + visitNodes(cbNodes, node.members); case 205: 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 227: - return visitNode(cbNode, node.name) || - visitNode(cbNode, node.initializer); case 206: + return visitNodes(cbNodes, node.decorators) || + visitNodes(cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNodes(cbNodes, node.typeParameters) || + visitNode(cbNode, node.type); + case 207: + return visitNodes(cbNodes, node.decorators) || + visitNodes(cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNodes(cbNodes, node.members); + case 229: + return visitNode(cbNode, node.name) || + visitNode(cbNode, node.initializer); + case 208: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.body); - case 209: + case 211: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.moduleReference); - case 210: + case 212: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.importClause) || visitNode(cbNode, node.moduleSpecifier); - case 211: + case 213: return visitNode(cbNode, node.name) || visitNode(cbNode, node.namedBindings); - case 212: + case 214: return visitNode(cbNode, node.name); - case 213: - case 217: + case 215: + case 219: return visitNodes(cbNodes, node.elements); - case 216: + case 218: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.exportClause) || visitNode(cbNode, node.moduleSpecifier); - case 214: - case 218: + case 216: + case 220: return visitNode(cbNode, node.propertyName) || visitNode(cbNode, node.name); - case 215: + case 217: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.expression); - case 172: + case 174: return visitNode(cbNode, node.head) || visitNodes(cbNodes, node.templateSpans); - case 178: + case 180: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.literal); - case 128: + case 129: return visitNode(cbNode, node.expression); - case 223: + case 225: return visitNodes(cbNodes, node.types); - case 177: + case 179: return visitNode(cbNode, node.expression) || visitNodes(cbNodes, node.typeArguments); - case 220: + case 222: return visitNode(cbNode, node.expression); - case 219: + case 221: return visitNodes(cbNodes, node.decorators); + case 231: + return visitNode(cbNode, node.type); + case 235: + return visitNodes(cbNodes, node.types); + case 236: + return visitNodes(cbNodes, node.types); + case 234: + return visitNode(cbNode, node.elementType); + case 238: + return visitNode(cbNode, node.type); + case 237: + return visitNode(cbNode, node.type); + case 239: + return visitNodes(cbNodes, node.members); + case 241: + return visitNode(cbNode, node.name) || + visitNodes(cbNodes, node.typeArguments); + case 242: + return visitNode(cbNode, node.type); + case 243: + return visitNodes(cbNodes, node.parameters) || + visitNode(cbNode, node.type); + case 244: + return visitNode(cbNode, node.type); + case 245: + return visitNode(cbNode, node.type); + case 246: + return visitNode(cbNode, node.type); + case 240: + return visitNode(cbNode, node.name) || + visitNode(cbNode, node.type); + case 247: + return visitNodes(cbNodes, node.tags); + case 249: + return visitNode(cbNode, node.preParameterName) || + visitNode(cbNode, node.typeExpression) || + visitNode(cbNode, node.postParameterName); + case 250: + return visitNode(cbNode, node.typeExpression); + case 251: + return visitNode(cbNode, node.typeExpression); + case 252: + return visitNodes(cbNodes, node.typeParameters); } } ts.forEachChild = forEachChild; @@ -5136,11 +5709,20 @@ var ts; return IncrementalParser.updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks); } ts.updateSourceFile = updateSourceFile; + function parseIsolatedJSDocComment(content, start, length) { + return Parser.JSDocParser.parseIsolatedJSDocComment(content, start, length); + } + 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(2, true); var disallowInAndDecoratorContext = 2 | 16; var sourceFile; + var parseDiagnostics; var syntaxCursor; var token; var sourceText; @@ -5148,44 +5730,83 @@ var ts; var identifiers; var identifierCount; var parsingContext; - var contextFlags = 0; + var contextFlags; var parseErrorBeforeNextFinishedNode = false; function parseSourceFile(fileName, _sourceText, languageVersion, _syntaxCursor, setParentNodes) { + initializeState(fileName, _sourceText, languageVersion, _syntaxCursor); + var result = parseSourceFileWorker(fileName, languageVersion, setParentNodes); + clearState(); + return result; + } + Parser.parseSourceFile = parseSourceFile; + function initializeState(fileName, _sourceText, languageVersion, _syntaxCursor) { sourceText = _sourceText; syntaxCursor = _syntaxCursor; + parseDiagnostics = []; parsingContext = 0; identifiers = {}; identifierCount = 0; nodeCount = 0; - contextFlags = 0; + contextFlags = ts.isJavaScript(fileName) ? 64 : 0; parseErrorBeforeNextFinishedNode = false; - createSourceFile(fileName, languageVersion); scanner.setText(sourceText); scanner.setOnError(scanError); scanner.setScriptTarget(languageVersion); + } + function clearState() { + scanner.setText(""); + scanner.setOnError(undefined); + parseDiagnostics = undefined; + sourceFile = undefined; + identifiers = undefined; + syntaxCursor = undefined; + sourceText = undefined; + } + function parseSourceFileWorker(fileName, languageVersion, setParentNodes) { + sourceFile = createSourceFile(fileName, languageVersion); token = nextToken(); processReferenceComments(sourceFile); - sourceFile.statements = parseList(0, true, parseSourceElement); + 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); } - syntaxCursor = undefined; - scanner.setText(""); - scanner.setOnError(undefined); - var result = sourceFile; - sourceFile = undefined; - identifiers = undefined; - syntaxCursor = undefined; - sourceText = undefined; - return result; + if (ts.isJavaScript(fileName)) { + addJSDocComments(); + } + return sourceFile; + } + function addJSDocComments() { + forEachChild(sourceFile, visit); + return; + function visit(node) { + switch (node.kind) { + case 183: + case 203: + case 131: + addJSDocComment(node); + } + forEachChild(node, visit); + } + } + function addJSDocComment(node) { + var comments = ts.getLeadingCommentRangesOfNode(node, sourceFile); + if (comments) { + for (var _i = 0; _i < comments.length; _i++) { + var comment = comments[_i]; + var jsDocComment = JSDocParser.parseJSDocComment(node, comment.pos, comment.end - comment.pos); + if (jsDocComment) { + node.jsDocComment = jsDocComment; + } + } + } } - Parser.parseSourceFile = parseSourceFile; function fixupParentReferences(sourceFile) { // 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 @@ -5204,16 +5825,17 @@ var ts; } } } + Parser.fixupParentReferences = fixupParentReferences; function createSourceFile(fileName, languageVersion) { - sourceFile = createNode(228, 0); + var sourceFile = createNode(230, 0); sourceFile.pos = 0; sourceFile.end = sourceText.length; sourceFile.text = sourceText; - sourceFile.parseDiagnostics = []; sourceFile.bindDiagnostics = []; sourceFile.languageVersion = languageVersion; sourceFile.fileName = ts.normalizePath(fileName); sourceFile.flags = ts.fileExtensionIs(sourceFile.fileName, ".d.ts") ? 2048 : 0; + return sourceFile; } function setContextFlag(val, flag) { if (val) { @@ -5223,9 +5845,6 @@ var ts; contextFlags &= ~flag; } } - function setStrictModeContext(val) { - setContextFlag(val, 1); - } function setDisallowInContext(val) { setContextFlag(val, 2); } @@ -5296,9 +5915,6 @@ var ts; function inYieldContext() { return (contextFlags & 4) !== 0; } - function inStrictModeContext() { - return (contextFlags & 1) !== 0; - } function inGeneratorParameterContext() { return (contextFlags & 8) !== 0; } @@ -5314,9 +5930,9 @@ var ts; parseErrorAtPosition(start, length, message, arg0); } function parseErrorAtPosition(start, length, message, arg0) { - var lastError = ts.lastOrUndefined(sourceFile.parseDiagnostics); + var lastError = ts.lastOrUndefined(parseDiagnostics); if (!lastError || start !== lastError.start) { - sourceFile.parseDiagnostics.push(ts.createFileDiagnostic(sourceFile, start, length, message, arg0)); + parseDiagnostics.push(ts.createFileDiagnostic(sourceFile, start, length, message, arg0)); } parseErrorBeforeNextFinishedNode = true; } @@ -5347,7 +5963,7 @@ var ts; } function speculationHelper(callback, isLookAhead) { var saveToken = token; - var saveParseDiagnosticsLength = sourceFile.parseDiagnostics.length; + var saveParseDiagnosticsLength = parseDiagnostics.length; var saveParseErrorBeforeNextFinishedNode = parseErrorBeforeNextFinishedNode; var saveContextFlags = contextFlags; var result = isLookAhead @@ -5356,7 +5972,7 @@ var ts; ts.Debug.assert(saveContextFlags === contextFlags); if (!result || isLookAhead) { token = saveToken; - sourceFile.parseDiagnostics.length = saveParseDiagnosticsLength; + parseDiagnostics.length = saveParseDiagnosticsLength; parseErrorBeforeNextFinishedNode = saveParseErrorBeforeNextFinishedNode; } return result; @@ -5438,8 +6054,8 @@ var ts; node.end = pos; return node; } - function finishNode(node) { - node.end = scanner.getStartPos(); + function finishNode(node, end) { + node.end = end === undefined ? scanner.getStartPos() : end; if (contextFlags) { node.parserContextFlags = contextFlags; } @@ -5488,17 +6104,26 @@ var ts; token === 8 || token === 7; } - function parsePropertyName() { + function parsePropertyNameWorker(allowComputedPropertyNames) { if (token === 8 || token === 7) { return parseLiteralNode(true); } - if (token === 18) { + if (allowComputedPropertyNames && token === 18) { return parseComputedPropertyName(); } return parseIdentifierName(); } + function parsePropertyName() { + return parsePropertyNameWorker(true); + } + function parseSimplePropertyName() { + return parsePropertyNameWorker(false); + } + function isSimplePropertyName() { + return token === 8 || token === 7 || isIdentifierOrKeyword(); + } function parseComputedPropertyName() { - var node = createNode(128); + var node = createNode(129); parseExpected(18); var yieldContext = inYieldContext(); if (inGeneratorParameterContext()) { @@ -5552,23 +6177,21 @@ var ts; switch (parsingContext) { case 0: case 1: - return isSourceElement(inErrorRecovery); - case 2: - case 4: - return isStartOfStatement(inErrorRecovery); case 3: + return !(token === 22 && inErrorRecovery) && isStartOfStatement(); + case 2: return token === 67 || token === 73; - case 5: + case 4: return isStartOfTypeMember(); - case 6: + case 5: return lookAhead(isClassMemberStart) || (token === 22 && !inErrorRecovery); - case 7: + case 6: return token === 18 || isLiteralPropertyName(); - case 13: + case 12: return token === 18 || token === 35 || isLiteralPropertyName(); - case 10: + case 9: return isLiteralPropertyName(); - case 8: + case 7: if (token === 14) { return lookAhead(isValidHeritageClauseObjectLiteral); } @@ -5578,24 +6201,30 @@ var ts; else { return isIdentifier() && !isHeritageClauseExtendsOrImplementsKeyword(); } - case 9: + case 8: return isIdentifierOrPattern(); - case 11: + case 10: return token === 23 || token === 21 || isIdentifierOrPattern(); - case 16: - return isIdentifier(); - case 12: - case 14: - return token === 23 || token === 21 || isStartOfExpression(); case 15: + return isIdentifier(); + case 11: + case 13: + return token === 23 || token === 21 || isStartOfExpression(); + case 14: return isStartOfParameter(); + case 16: case 17: - case 18: return token === 23 || isStartOfType(); - case 19: + case 18: return isHeritageClause(); - case 20: + case 19: return isIdentifierOrKeyword(); + case 20: + case 21: + case 23: + return JSDocParser.isJSDocType(); + case 22: + return isSimplePropertyName(); } ts.Debug.fail("Non-exhaustive case in 'isListElement'."); } @@ -5629,34 +6258,41 @@ var ts; switch (kind) { case 1: case 2: - case 3: + case 4: case 5: case 6: - case 7: - case 13: - case 10: - case 20: - return token === 15; - case 4: - return token === 15 || token === 67 || token === 73; - case 8: - return token === 14 || token === 79 || token === 102; - case 9: - return isVariableDeclaratorListTerminator(); - case 16: - return token === 25 || token === 16 || token === 14 || token === 79 || token === 102; case 12: - return token === 17 || token === 22; - case 14: - case 18: - case 11: - return token === 19; - case 15: - return token === 17 || token === 19; - case 17: - return token === 25 || token === 16; + case 9: case 19: + return token === 15; + case 3: + return token === 15 || token === 67 || token === 73; + case 7: + return token === 14 || token === 79 || token === 102; + case 8: + return isVariableDeclaratorListTerminator(); + case 15: + return token === 25 || token === 16 || token === 14 || token === 79 || token === 102; + case 11: + return token === 17 || token === 22; + case 13: + case 17: + case 10: + return token === 19; + case 14: + return token === 17 || token === 19; + case 16: + return token === 25 || token === 16; + case 18: return token === 14 || token === 15; + case 20: + return token === 17 || token === 51 || token === 15; + case 21: + return token === 25 || token === 15; + case 23: + return token === 19 || token === 15; + case 22: + return token === 15; } } function isVariableDeclaratorListTerminator() { @@ -5672,7 +6308,7 @@ var ts; return false; } function isInSomeParsingContext() { - for (var kind = 0; kind < 21; kind++) { + for (var kind = 0; kind < 24; kind++) { if (parsingContext & (1 << kind)) { if (isListElement(kind, true) || isListTerminator(kind)) { return true; @@ -5681,43 +6317,25 @@ var ts; } return false; } - function parseList(kind, checkForStrictMode, parseElement) { + function parseList(kind, parseElement) { var saveParsingContext = parsingContext; parsingContext |= 1 << kind; var result = []; result.pos = getNodePos(); - var savedStrictModeContext = inStrictModeContext(); while (!isListTerminator(kind)) { if (isListElement(kind, false)) { var element = parseListElement(kind, parseElement); result.push(element); - if (checkForStrictMode && !inStrictModeContext()) { - if (ts.isPrologueDirective(element)) { - if (isUseStrictPrologueDirective(sourceFile, element)) { - setStrictModeContext(true); - checkForStrictMode = false; - } - } - else { - checkForStrictMode = false; - } - } continue; } if (abortParsingListOrMoveToNextToken(kind)) { break; } } - setStrictModeContext(savedStrictModeContext); result.end = getNodeEnd(); parsingContext = saveParsingContext; return result; } - function isUseStrictPrologueDirective(sourceFile, node) { - ts.Debug.assert(ts.isPrologueDirective(node)); - var nodeText = ts.getSourceTextOfNodeFromSourceFile(sourceFile, node.expression); - return nodeText === '"use strict"' || nodeText === "'use strict'"; - } function parseListElement(parsingContext, parseElement) { var node = currentNode(parsingContext); if (node) { @@ -5742,7 +6360,7 @@ var ts; if (ts.containsParseError(node)) { return undefined; } - var nodeContextFlags = node.parserContextFlags & 63; + var nodeContextFlags = node.parserContextFlags & 62; if (nodeContextFlags !== contextFlags) { return undefined; } @@ -5758,61 +6376,47 @@ var ts; } function canReuseNode(node, parsingContext) { switch (parsingContext) { - case 1: - return isReusableModuleElement(node); - case 6: - return isReusableClassMember(node); - case 3: - return isReusableSwitchClause(node); - case 2: - case 4: - return isReusableStatement(node); - case 7: - return isReusableEnumMember(node); 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 9: - return isReusableVariableDeclaration(node); - case 15: - return isReusableParameter(node); - case 19: - case 16: - case 18: - case 17: - case 12: - case 13: case 8: - } - return false; - } - function isReusableModuleElement(node) { - if (node) { - switch (node.kind) { - case 210: - case 209: - case 216: - case 215: - case 202: - case 203: - case 206: - case 205: - return true; - } - return isReusableStatement(node); + return isReusableVariableDeclaration(node); + case 14: + return isReusableParameter(node); + case 18: + case 15: + case 17: + case 16: + case 11: + case 12: + case 7: } return false; } function isReusableClassMember(node) { if (node) { switch (node.kind) { - case 136: - case 141: - case 135: case 137: + case 142: case 138: - case 133: - case 179: + case 139: + case 134: + case 181: return true; + case 136: + var methodDeclaration = node; + var nameIsConstructor = methodDeclaration.name.kind === 65 && + methodDeclaration.name.originalKeywordKind === 114; + return !nameIsConstructor; } } return false; @@ -5820,8 +6424,8 @@ var ts; function isReusableSwitchClause(node) { if (node) { switch (node.kind) { - case 221: - case 222: + case 223: + case 224: return true; } } @@ -5830,56 +6434,65 @@ var ts; function isReusableStatement(node) { if (node) { switch (node.kind) { - case 201: - case 181: - case 180: - case 184: + case 203: case 183: - case 196: - case 192: - case 194: - case 191: - case 190: - case 188: - case 189: - case 187: - case 186: - case 193: case 182: - case 197: - case 195: + case 186: case 185: case 198: + case 194: + case 196: + case 193: + case 192: + case 190: + case 191: + case 189: + case 188: + case 195: + case 184: + case 199: + case 197: + case 187: + case 200: + case 212: + case 211: + case 218: + case 217: + case 208: + case 204: + case 205: + case 207: + case 206: return true; } } return false; } function isReusableEnumMember(node) { - return node.kind === 227; + return node.kind === 229; } function isReusableTypeMember(node) { if (node) { switch (node.kind) { - case 140: - case 134: case 141: - case 132: - case 139: + case 135: + case 142: + case 133: + case 140: return true; } } return false; } function isReusableVariableDeclaration(node) { - if (node.kind !== 199) { + if (node.kind !== 201) { return false; } var variableDeclarator = node; return variableDeclarator.initializer === undefined; } function isReusableParameter(node) { - if (node.kind !== 130) { + if (node.kind !== 131) { return false; } var parameter = node; @@ -5897,25 +6510,28 @@ var ts; 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.Statement_expected; - case 3: return ts.Diagnostics.case_or_default_expected; - case 4: return ts.Diagnostics.Statement_expected; - case 5: return ts.Diagnostics.Property_or_signature_expected; - case 6: return ts.Diagnostics.Unexpected_token_A_constructor_method_accessor_or_property_was_expected; - case 7: return ts.Diagnostics.Enum_member_expected; - case 8: return ts.Diagnostics.Expression_expected; - case 9: return ts.Diagnostics.Variable_declaration_expected; - case 10: return ts.Diagnostics.Property_destructuring_pattern_expected; - case 11: return ts.Diagnostics.Array_element_destructuring_pattern_expected; - case 12: return ts.Diagnostics.Argument_expression_expected; - case 13: return ts.Diagnostics.Property_assignment_expected; - case 14: return ts.Diagnostics.Expression_or_comma_expected; - case 15: return ts.Diagnostics.Parameter_declaration_expected; - case 16: return ts.Diagnostics.Type_parameter_declaration_expected; - case 17: return ts.Diagnostics.Type_argument_expected; - case 18: return ts.Diagnostics.Type_expected; - case 19: return ts.Diagnostics.Unexpected_token_expected; - case 20: return ts.Diagnostics.Identifier_expected; + case 2: return ts.Diagnostics.case_or_default_expected; + case 3: return ts.Diagnostics.Statement_expected; + 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 13: return ts.Diagnostics.Expression_or_comma_expected; + case 14: return ts.Diagnostics.Parameter_declaration_expected; + case 15: return ts.Diagnostics.Type_parameter_declaration_expected; + case 16: return ts.Diagnostics.Type_argument_expected; + case 17: return ts.Diagnostics.Type_expected; + case 18: return ts.Diagnostics.Unexpected_token_expected; + case 19: return ts.Diagnostics.Identifier_expected; + case 20: return ts.Diagnostics.Parameter_declaration_expected; + case 21: return ts.Diagnostics.Type_argument_expected; + case 23: return ts.Diagnostics.Type_expected; + case 22: return ts.Diagnostics.Property_assignment_expected; } } ; @@ -5974,7 +6590,7 @@ var ts; function parseEntityName(allowReservedWords, diagnosticMessage) { var entity = parseIdentifier(diagnosticMessage); while (parseOptional(20)) { - var node = createNode(127, entity.pos); + var node = createNode(128, entity.pos); node.left = entity; node.right = parseRightSideOfDot(allowReservedWords); entity = finishNode(node); @@ -5982,7 +6598,7 @@ var ts; return entity; } function parseRightSideOfDot(allowIdentifierNames) { - if (scanner.hasPrecedingLineBreak() && scanner.isReservedWord()) { + if (scanner.hasPrecedingLineBreak() && isIdentifierOrKeyword()) { var matchesPattern = lookAhead(nextTokenIsIdentifierOrKeywordOnSameLine); if (matchesPattern) { return createMissingNode(65, true, ts.Diagnostics.Identifier_expected); @@ -5991,7 +6607,7 @@ var ts; return allowIdentifierNames ? parseIdentifierName() : parseIdentifier(); } function parseTemplateExpression() { - var template = createNode(172); + var template = createNode(174); template.head = parseLiteralNode(); ts.Debug.assert(template.head.kind === 11, "Template head has wrong token kind"); var templateSpans = []; @@ -6004,7 +6620,7 @@ var ts; return finishNode(template); } function parseTemplateSpan() { - var span = createNode(178); + var span = createNode(180); span.expression = allowInAnd(parseExpression); var literal; if (token === 15) { @@ -6037,22 +6653,30 @@ var ts; } return node; } - function parseTypeReference() { - var node = createNode(142); - node.typeName = parseEntityName(false, ts.Diagnostics.Type_expected); + function parseTypeReferenceOrTypePredicate() { + var typeName = parseEntityName(false, ts.Diagnostics.Type_expected); + if (typeName.kind === 65 && token === 117 && !scanner.hasPrecedingLineBreak()) { + nextToken(); + var node_1 = createNode(143, typeName.pos); + node_1.parameterName = typeName; + node_1.type = parseType(); + return finishNode(node_1); + } + var node = createNode(144, typeName.pos); + node.typeName = typeName; if (!scanner.hasPrecedingLineBreak() && token === 24) { - node.typeArguments = parseBracketedList(17, parseType, 24, 25); + node.typeArguments = parseBracketedList(16, parseType, 24, 25); } return finishNode(node); } function parseTypeQuery() { - var node = createNode(145); + var node = createNode(147); parseExpected(97); node.exprName = parseEntityName(true); return finishNode(node); } function parseTypeParameter() { - var node = createNode(129); + var node = createNode(130); node.name = parseIdentifier(); if (parseOptional(79)) { if (isStartOfType() || !isStartOfExpression()) { @@ -6066,7 +6690,7 @@ var ts; } function parseTypeParameters() { if (token === 24) { - return parseBracketedList(16, parseTypeParameter, 24, 25); + return parseBracketedList(15, parseTypeParameter, 24, 25); } } function parseParameterType() { @@ -6087,7 +6711,7 @@ var ts; } } function parseParameter() { - var node = createNode(130); + var node = createNode(131); node.decorators = parseDecorators(); setModifiers(node, parseModifiers()); node.dotDotDotToken = parseOptionalToken(21); @@ -6121,7 +6745,7 @@ var ts; var savedGeneratorParameterContext = inGeneratorParameterContext(); setYieldContext(yieldAndGeneratorParameterContext); setGeneratorParameterContext(yieldAndGeneratorParameterContext); - var result = parseDelimitedList(15, parseParameter); + var result = parseDelimitedList(14, parseParameter); setYieldContext(savedYieldContext); setGeneratorParameterContext(savedGeneratorParameterContext); if (!parseExpected(17) && requireCompleteParameterList) { @@ -6139,7 +6763,7 @@ var ts; } function parseSignatureMember(kind) { var node = createNode(kind); - if (kind === 140) { + if (kind === 141) { parseExpected(88); } fillSignature(51, false, false, node); @@ -6179,10 +6803,10 @@ var ts; return token === 51 || token === 23 || token === 19; } function parseIndexSignatureDeclaration(fullStart, decorators, modifiers) { - var node = createNode(141, fullStart); + var node = createNode(142, fullStart); node.decorators = decorators; setModifiers(node, modifiers); - node.parameters = parseBracketedList(15, parseParameter, 18, 19); + node.parameters = parseBracketedList(14, parseParameter, 18, 19); node.type = parseTypeAnnotation(); parseTypeMemberSemicolon(); return finishNode(node); @@ -6192,7 +6816,7 @@ var ts; var name = parsePropertyName(); var questionToken = parseOptionalToken(50); if (token === 16 || token === 24) { - var method = createNode(134, fullStart); + var method = createNode(135, fullStart); method.name = name; method.questionToken = questionToken; fillSignature(51, false, false, method); @@ -6200,7 +6824,7 @@ var ts; return finishNode(method); } else { - var property = createNode(132, fullStart); + var property = createNode(133, fullStart); property.name = name; property.questionToken = questionToken; property.type = parseTypeAnnotation(); @@ -6242,14 +6866,14 @@ var ts; switch (token) { case 16: case 24: - return parseSignatureMember(139); + return parseSignatureMember(140); case 18: return isIndexSignature() ? parseIndexSignatureDeclaration(scanner.getStartPos(), undefined, undefined) : parsePropertyOrMethodSignature(); case 88: if (lookAhead(isStartOfConstructSignature)) { - return parseSignatureMember(140); + return parseSignatureMember(141); } case 8: case 7: @@ -6279,14 +6903,14 @@ var ts; return token === 16 || token === 24; } function parseTypeLiteral() { - var node = createNode(146); + var node = createNode(148); node.members = parseObjectTypeMembers(); return finishNode(node); } function parseObjectTypeMembers() { var members; if (parseExpected(14)) { - members = parseList(5, false, parseTypeMember); + members = parseList(4, parseTypeMember); parseExpected(15); } else { @@ -6295,12 +6919,12 @@ var ts; return members; } function parseTupleType() { - var node = createNode(148); - node.elementTypes = parseBracketedList(18, parseType, 18, 19); + var node = createNode(150); + node.elementTypes = parseBracketedList(17, parseType, 18, 19); return finishNode(node); } function parseParenthesizedType() { - var node = createNode(150); + var node = createNode(152); parseExpected(16); node.type = parseType(); parseExpected(17); @@ -6308,7 +6932,7 @@ var ts; } function parseFunctionOrConstructorType(kind) { var node = createNode(kind); - if (kind === 144) { + if (kind === 146) { parseExpected(88); } fillSignature(32, false, false, node); @@ -6321,12 +6945,12 @@ var ts; function parseNonArrayType() { switch (token) { case 112: - case 122: - case 120: - case 113: case 123: + case 121: + case 113: + case 124: var node = tryParse(parseKeywordAndNoDot); - return node || parseTypeReference(); + return node || parseTypeReferenceOrTypePredicate(); case 99: return parseTokenNode(); case 97: @@ -6338,16 +6962,16 @@ var ts; case 16: return parseParenthesizedType(); default: - return parseTypeReference(); + return parseTypeReferenceOrTypePredicate(); } } function isStartOfType() { switch (token) { case 112: - case 122: - case 120: - case 113: case 123: + case 121: + case 113: + case 124: case 99: case 97: case 14: @@ -6369,7 +6993,7 @@ var ts; var type = parseNonArrayType(); while (!scanner.hasPrecedingLineBreak() && parseOptional(18)) { parseExpected(19); - var node = createNode(147, type.pos); + var node = createNode(149, type.pos); node.elementType = type; type = finishNode(node); } @@ -6384,7 +7008,7 @@ var ts; types.push(parseArrayTypeOrHigher()); } types.end = getNodeEnd(); - var node = createNode(149, type.pos); + var node = createNode(151, type.pos); node.types = types; type = finishNode(node); } @@ -6429,10 +7053,10 @@ var ts; } function parseTypeWorker() { if (isStartOfFunctionType()) { - return parseFunctionOrConstructorType(143); + return parseFunctionOrConstructorType(145); } if (token === 88) { - return parseFunctionOrConstructorType(144); + return parseFunctionOrConstructorType(146); } return parseUnionTypeOrHigher(); } @@ -6553,10 +7177,7 @@ var ts; if (inYieldContext()) { return true; } - if (inStrictModeContext()) { - return true; - } - return lookAhead(nextTokenIsIdentifierOnSameLine); + return lookAhead(nextTokenIsIdentifierOrKeywordOrNumberOnSameLine); } return false; } @@ -6564,13 +7185,8 @@ var ts; nextToken(); return !scanner.hasPrecedingLineBreak() && isIdentifier(); } - function nextTokenIsIdentifierOrStartOfDestructuringOnTheSameLine() { - nextToken(); - return !scanner.hasPrecedingLineBreak() && - (isIdentifier() || token === 14 || token === 18); - } function parseYieldExpression() { - var node = createNode(173); + var node = createNode(175); nextToken(); if (!scanner.hasPrecedingLineBreak() && (token === 35 || isStartOfExpression())) { @@ -6584,8 +7200,8 @@ var ts; } function parseSimpleArrowFunctionExpression(identifier) { ts.Debug.assert(token === 32, "parseSimpleArrowFunctionExpression should only have been called if we had a =>"); - var node = createNode(164, identifier.pos); - var parameter = createNode(130, identifier.pos); + var node = createNode(166, identifier.pos); + var parameter = createNode(131, identifier.pos); parameter.name = identifier; finishNode(parameter); node.parameters = [parameter]; @@ -6663,7 +7279,7 @@ var ts; return parseParenthesizedArrowFunctionExpressionHead(false); } function parseParenthesizedArrowFunctionExpressionHead(allowAmbiguity) { - var node = createNode(164); + var node = createNode(166); fillSignature(51, false, !allowAmbiguity, node); if (!node.parameters) { return undefined; @@ -6677,10 +7293,11 @@ var ts; if (token === 14) { return parseFunctionBlock(false, false); } - if (isStartOfStatement(true) && - !isStartOfExpressionStatement() && + if (token !== 22 && token !== 83 && - token !== 69) { + token !== 69 && + isStartOfStatement() && + !isStartOfExpressionStatement()) { return parseFunctionBlock(false, true); } return parseAssignmentExpressionOrHigher(); @@ -6690,7 +7307,7 @@ var ts; if (!questionToken) { return leftOperand; } - var node = createNode(171, leftOperand.pos); + var node = createNode(173, leftOperand.pos); node.condition = leftOperand; node.questionToken = questionToken; node.whenTrue = doOutsideOfContext(disallowInAndDecoratorContext, parseAssignmentExpressionOrHigher); @@ -6703,7 +7320,7 @@ var ts; return parseBinaryExpressionRest(precedence, leftOperand); } function isInOrOfKeyword(t) { - return t === 86 || t === 126; + return t === 86 || t === 127; } function parseBinaryExpressionRest(precedence, leftOperand) { while (true) { @@ -6764,33 +7381,33 @@ var ts; return -1; } function makeBinaryExpression(left, operatorToken, right) { - var node = createNode(170, left.pos); + var node = createNode(172, left.pos); node.left = left; node.operatorToken = operatorToken; node.right = right; return finishNode(node); } function parsePrefixUnaryExpression() { - var node = createNode(168); + var node = createNode(170); node.operator = token; nextToken(); node.operand = parseUnaryExpressionOrHigher(); return finishNode(node); } function parseDeleteExpression() { - var node = createNode(165); + var node = createNode(167); nextToken(); node.expression = parseUnaryExpressionOrHigher(); return finishNode(node); } function parseTypeOfExpression() { - var node = createNode(166); + var node = createNode(168); nextToken(); node.expression = parseUnaryExpressionOrHigher(); return finishNode(node); } function parseVoidExpression() { - var node = createNode(167); + var node = createNode(169); nextToken(); node.expression = parseUnaryExpressionOrHigher(); return finishNode(node); @@ -6820,7 +7437,7 @@ var ts; var expression = parseLeftHandSideExpressionOrHigher(); ts.Debug.assert(ts.isLeftHandSideExpression(expression)); if ((token === 38 || token === 39) && !scanner.hasPrecedingLineBreak()) { - var node = createNode(169, expression.pos); + var node = createNode(171, expression.pos); node.operand = expression; node.operator = token; nextToken(); @@ -6843,14 +7460,14 @@ var ts; if (token === 16 || token === 20) { return expression; } - var node = createNode(156, expression.pos); + var node = createNode(158, expression.pos); node.expression = expression; node.dotToken = parseExpectedToken(20, false, ts.Diagnostics.super_must_be_followed_by_an_argument_list_or_member_access); node.name = parseRightSideOfDot(true); return finishNode(node); } function parseTypeAssertion() { - var node = createNode(161); + var node = createNode(163); parseExpected(24); node.type = parseType(); parseExpected(25); @@ -6861,7 +7478,7 @@ var ts; while (true) { var dotToken = parseOptionalToken(20); if (dotToken) { - var propertyAccess = createNode(156, expression.pos); + var propertyAccess = createNode(158, expression.pos); propertyAccess.expression = expression; propertyAccess.dotToken = dotToken; propertyAccess.name = parseRightSideOfDot(true); @@ -6869,7 +7486,7 @@ var ts; continue; } if (!inDecoratorContext() && parseOptional(18)) { - var indexedAccess = createNode(157, expression.pos); + var indexedAccess = createNode(159, expression.pos); indexedAccess.expression = expression; if (token !== 19) { indexedAccess.argumentExpression = allowInAnd(parseExpression); @@ -6883,7 +7500,7 @@ var ts; continue; } if (token === 10 || token === 11) { - var tagExpression = createNode(160, expression.pos); + var tagExpression = createNode(162, expression.pos); tagExpression.tag = expression; tagExpression.template = token === 10 ? parseLiteralNode() @@ -6902,7 +7519,7 @@ var ts; if (!typeArguments) { return expression; } - var callExpr = createNode(158, expression.pos); + var callExpr = createNode(160, expression.pos); callExpr.expression = expression; callExpr.typeArguments = typeArguments; callExpr.arguments = parseArgumentList(); @@ -6910,7 +7527,7 @@ var ts; continue; } else if (token === 16) { - var callExpr = createNode(158, expression.pos); + var callExpr = createNode(160, expression.pos); callExpr.expression = expression; callExpr.arguments = parseArgumentList(); expression = finishNode(callExpr); @@ -6921,7 +7538,7 @@ var ts; } function parseArgumentList() { parseExpected(16); - var result = parseDelimitedList(12, parseArgumentExpression); + var result = parseDelimitedList(11, parseArgumentExpression); parseExpected(17); return result; } @@ -6929,7 +7546,7 @@ var ts; if (!parseOptional(24)) { return undefined; } - var typeArguments = parseDelimitedList(17, parseType); + var typeArguments = parseDelimitedList(16, parseType); if (!parseExpected(25)) { return undefined; } @@ -7000,42 +7617,42 @@ var ts; return parseIdentifier(ts.Diagnostics.Expression_expected); } function parseParenthesizedExpression() { - var node = createNode(162); + var node = createNode(164); parseExpected(16); node.expression = allowInAnd(parseExpression); parseExpected(17); return finishNode(node); } function parseSpreadElement() { - var node = createNode(174); + var node = createNode(176); parseExpected(21); node.expression = parseAssignmentExpressionOrHigher(); return finishNode(node); } function parseArgumentOrArrayLiteralElement() { return token === 21 ? parseSpreadElement() : - token === 23 ? createNode(176) : + token === 23 ? createNode(178) : parseAssignmentExpressionOrHigher(); } function parseArgumentExpression() { return doOutsideOfContext(disallowInAndDecoratorContext, parseArgumentOrArrayLiteralElement); } function parseArrayLiteralExpression() { - var node = createNode(154); + var node = createNode(156); parseExpected(18); if (scanner.hasPrecedingLineBreak()) node.flags |= 512; - node.elements = parseDelimitedList(14, parseArgumentOrArrayLiteralElement); + node.elements = parseDelimitedList(13, parseArgumentOrArrayLiteralElement); parseExpected(19); return finishNode(node); } function tryParseAccessorDeclaration(fullStart, decorators, modifiers) { if (parseContextualModifier(116)) { - return parseAccessorDeclaration(137, fullStart, decorators, modifiers); - } - else if (parseContextualModifier(121)) { return parseAccessorDeclaration(138, fullStart, decorators, modifiers); } + else if (parseContextualModifier(122)) { + return parseAccessorDeclaration(139, fullStart, decorators, modifiers); + } return undefined; } function parseObjectLiteralElement() { @@ -7055,13 +7672,13 @@ var ts; return parseMethodDeclaration(fullStart, decorators, modifiers, asteriskToken, propertyName, questionToken); } if ((token === 23 || token === 15) && tokenIsIdentifier) { - var shorthandDeclaration = createNode(226, fullStart); + var shorthandDeclaration = createNode(228, fullStart); shorthandDeclaration.name = propertyName; shorthandDeclaration.questionToken = questionToken; return finishNode(shorthandDeclaration); } else { - var propertyAssignment = createNode(225, fullStart); + var propertyAssignment = createNode(227, fullStart); propertyAssignment.name = propertyName; propertyAssignment.questionToken = questionToken; parseExpected(51); @@ -7070,12 +7687,12 @@ var ts; } } function parseObjectLiteralExpression() { - var node = createNode(155); + var node = createNode(157); parseExpected(14); if (scanner.hasPrecedingLineBreak()) { node.flags |= 512; } - node.properties = parseDelimitedList(13, parseObjectLiteralElement, true); + node.properties = parseDelimitedList(12, parseObjectLiteralElement, true); parseExpected(15); return finishNode(node); } @@ -7084,7 +7701,7 @@ var ts; if (saveDecoratorContext) { setDecoratorContext(false); } - var node = createNode(163); + var node = createNode(165); parseExpected(83); node.asteriskToken = parseOptionalToken(35); node.name = node.asteriskToken ? doInYieldContext(parseOptionalIdentifier) : parseOptionalIdentifier(); @@ -7099,7 +7716,7 @@ var ts; return isIdentifier() ? parseIdentifier() : undefined; } function parseNewExpression() { - var node = createNode(159); + var node = createNode(161); parseExpected(88); node.expression = parseMemberExpressionOrHigher(); node.typeArguments = tryParse(parseTypeArgumentsInExpression); @@ -7108,10 +7725,10 @@ var ts; } return finishNode(node); } - function parseBlock(ignoreMissingOpenBrace, checkForStrictMode, diagnosticMessage) { - var node = createNode(180); + function parseBlock(ignoreMissingOpenBrace, diagnosticMessage) { + var node = createNode(182); if (parseExpected(14, diagnosticMessage) || ignoreMissingOpenBrace) { - node.statements = parseList(2, checkForStrictMode, parseStatement); + node.statements = parseList(1, parseStatement); parseExpected(15); } else { @@ -7126,7 +7743,7 @@ var ts; if (saveDecoratorContext) { setDecoratorContext(false); } - var block = parseBlock(ignoreMissingOpenBrace, true, diagnosticMessage); + var block = parseBlock(ignoreMissingOpenBrace, diagnosticMessage); if (saveDecoratorContext) { setDecoratorContext(true); } @@ -7134,12 +7751,12 @@ var ts; return block; } function parseEmptyStatement() { - var node = createNode(182); + var node = createNode(184); parseExpected(22); return finishNode(node); } function parseIfStatement() { - var node = createNode(184); + var node = createNode(186); parseExpected(84); parseExpected(16); node.expression = allowInAnd(parseExpression); @@ -7149,7 +7766,7 @@ var ts; return finishNode(node); } function parseDoStatement() { - var node = createNode(185); + var node = createNode(187); parseExpected(75); node.statement = parseStatement(); parseExpected(100); @@ -7160,7 +7777,7 @@ var ts; return finishNode(node); } function parseWhileStatement() { - var node = createNode(186); + var node = createNode(188); parseExpected(100); parseExpected(16); node.expression = allowInAnd(parseExpression); @@ -7183,21 +7800,21 @@ var ts; } var forOrForInOrForOfStatement; if (parseOptional(86)) { - var forInStatement = createNode(188, pos); + var forInStatement = createNode(190, pos); forInStatement.initializer = initializer; forInStatement.expression = allowInAnd(parseExpression); parseExpected(17); forOrForInOrForOfStatement = forInStatement; } - else if (parseOptional(126)) { - var forOfStatement = createNode(189, pos); + else if (parseOptional(127)) { + var forOfStatement = createNode(191, pos); forOfStatement.initializer = initializer; forOfStatement.expression = allowInAnd(parseAssignmentExpressionOrHigher); parseExpected(17); forOrForInOrForOfStatement = forOfStatement; } else { - var forStatement = createNode(187, pos); + var forStatement = createNode(189, pos); forStatement.initializer = initializer; parseExpected(22); if (token !== 22 && token !== 17) { @@ -7215,7 +7832,7 @@ var ts; } function parseBreakOrContinueStatement(kind) { var node = createNode(kind); - parseExpected(kind === 191 ? 66 : 71); + parseExpected(kind === 193 ? 66 : 71); if (!canParseSemicolon()) { node.label = parseIdentifier(); } @@ -7223,7 +7840,7 @@ var ts; return finishNode(node); } function parseReturnStatement() { - var node = createNode(192); + var node = createNode(194); parseExpected(90); if (!canParseSemicolon()) { node.expression = allowInAnd(parseExpression); @@ -7232,7 +7849,7 @@ var ts; return finishNode(node); } function parseWithStatement() { - var node = createNode(193); + var node = createNode(195); parseExpected(101); parseExpected(16); node.expression = allowInAnd(parseExpression); @@ -7241,32 +7858,32 @@ var ts; return finishNode(node); } function parseCaseClause() { - var node = createNode(221); + var node = createNode(223); parseExpected(67); node.expression = allowInAnd(parseExpression); parseExpected(51); - node.statements = parseList(4, false, parseStatement); + node.statements = parseList(3, parseStatement); return finishNode(node); } function parseDefaultClause() { - var node = createNode(222); + var node = createNode(224); parseExpected(73); parseExpected(51); - node.statements = parseList(4, false, parseStatement); + node.statements = parseList(3, parseStatement); return finishNode(node); } function parseCaseOrDefaultClause() { return token === 67 ? parseCaseClause() : parseDefaultClause(); } function parseSwitchStatement() { - var node = createNode(194); + var node = createNode(196); parseExpected(92); parseExpected(16); node.expression = allowInAnd(parseExpression); parseExpected(17); - var caseBlock = createNode(208, scanner.getStartPos()); + var caseBlock = createNode(210, scanner.getStartPos()); parseExpected(14); - caseBlock.clauses = parseList(3, false, parseCaseOrDefaultClause); + caseBlock.clauses = parseList(2, parseCaseOrDefaultClause); parseExpected(15); node.caseBlock = finishNode(caseBlock); return finishNode(node); @@ -7274,35 +7891,35 @@ var ts; function parseThrowStatement() { // ThrowStatement[Yield] : // throw [no LineTerminator here]Expression[In, ?Yield]; - var node = createNode(196); + var node = createNode(198); parseExpected(94); node.expression = scanner.hasPrecedingLineBreak() ? undefined : allowInAnd(parseExpression); parseSemicolon(); return finishNode(node); } function parseTryStatement() { - var node = createNode(197); + var node = createNode(199); parseExpected(96); - node.tryBlock = parseBlock(false, false); + node.tryBlock = parseBlock(false); node.catchClause = token === 68 ? parseCatchClause() : undefined; if (!node.catchClause || token === 81) { parseExpected(81); - node.finallyBlock = parseBlock(false, false); + node.finallyBlock = parseBlock(false); } return finishNode(node); } function parseCatchClause() { - var result = createNode(224); + var result = createNode(226); parseExpected(68); if (parseExpected(16)) { result.variableDeclaration = parseVariableDeclaration(); } parseExpected(17); - result.block = parseBlock(false, false); + result.block = parseBlock(false); return finishNode(result); } function parseDebuggerStatement() { - var node = createNode(198); + var node = createNode(200); parseExpected(72); parseSemicolon(); return finishNode(node); @@ -7311,33 +7928,86 @@ var ts; var fullStart = scanner.getStartPos(); var expression = allowInAnd(parseExpression); if (expression.kind === 65 && parseOptional(51)) { - var labeledStatement = createNode(195, fullStart); + var labeledStatement = createNode(197, fullStart); labeledStatement.label = expression; labeledStatement.statement = parseStatement(); return finishNode(labeledStatement); } else { - var expressionStatement = createNode(183, fullStart); + var expressionStatement = createNode(185, fullStart); expressionStatement.expression = expression; parseSemicolon(); return finishNode(expressionStatement); } } - function isStartOfStatement(inErrorRecovery) { - if (ts.isModifier(token)) { - var result = lookAhead(parseVariableStatementOrFunctionDeclarationOrClassDeclarationWithDecoratorsOrModifiers); - if (result) { - return true; + function isIdentifierOrKeyword() { + return token >= 65; + } + function nextTokenIsIdentifierOrKeywordOnSameLine() { + nextToken(); + return isIdentifierOrKeyword() && !scanner.hasPrecedingLineBreak(); + } + function nextTokenIsIdentifierOrKeywordOrNumberOnSameLine() { + nextToken(); + return (isIdentifierOrKeyword() || token === 7) && !scanner.hasPrecedingLineBreak(); + } + function isDeclaration() { + while (true) { + switch (token) { + case 98: + case 104: + case 70: + case 83: + case 69: + case 77: + return true; + case 103: + case 125: + return nextTokenIsIdentifierOnSameLine(); + case 118: + case 119: + return nextTokenIsIdentifierOrStringLiteralOnSameLine(); + case 115: + nextToken(); + if (scanner.hasPrecedingLineBreak()) { + return false; + } + continue; + case 85: + nextToken(); + return token === 8 || token === 35 || + token === 14 || isIdentifierOrKeyword(); + case 78: + nextToken(); + if (token === 53 || token === 35 || + token === 14 || token === 73) { + return true; + } + continue; + case 108: + case 106: + case 107: + case 109: + nextToken(); + continue; + default: + return false; } } + } + function isStartOfDeclaration() { + return lookAhead(isDeclaration); + } + function isStartOfStatement() { switch (token) { + case 52: case 22: - return !inErrorRecovery; case 14: case 98: case 104: case 83: case 69: + case 77: case 84: case 75: case 100: @@ -7354,48 +8024,48 @@ var ts; case 81: return true; case 70: - var isConstEnum = lookAhead(nextTokenIsEnumKeyword); - return !isConstEnum; + case 78: + case 85: + return isStartOfDeclaration(); + case 115: case 103: - case 117: case 118: - case 77: - case 124: - if (isDeclarationStart()) { - return false; - } + case 119: + case 125: + return true; case 108: case 106: case 107: case 109: - if (lookAhead(nextTokenIsIdentifierOrKeywordOnSameLine)) { - return false; - } + return isStartOfDeclaration() || !lookAhead(nextTokenIsIdentifierOrKeywordOnSameLine); default: return isStartOfExpression(); } } - function nextTokenIsEnumKeyword() { + function nextTokenIsIdentifierOrStartOfDestructuring() { nextToken(); - return token === 77; + return isIdentifier() || token === 14 || token === 18; } - function nextTokenIsIdentifierOrKeywordOnSameLine() { - nextToken(); - return isIdentifierOrKeyword() && !scanner.hasPrecedingLineBreak(); + function isLetDeclaration() { + return lookAhead(nextTokenIsIdentifierOrStartOfDestructuring); } function parseStatement() { switch (token) { + case 22: + return parseEmptyStatement(); case 14: - return parseBlock(false, false); + return parseBlock(false); case 98: - case 70: return parseVariableStatement(scanner.getStartPos(), undefined, undefined); + case 104: + if (isLetDeclaration()) { + return parseVariableStatement(scanner.getStartPos(), undefined, undefined); + } + break; case 83: return parseFunctionDeclaration(scanner.getStartPos(), undefined, undefined); case 69: return parseClassDeclaration(scanner.getStartPos(), undefined, undefined); - case 22: - return parseEmptyStatement(); case 84: return parseIfStatement(); case 75: @@ -7405,9 +8075,9 @@ var ts; case 82: return parseForOrForInOrForOfStatement(); case 71: - return parseBreakOrContinueStatement(190); + return parseBreakOrContinueStatement(192); case 66: - return parseBreakOrContinueStatement(191); + return parseBreakOrContinueStatement(193); case 90: return parseReturnStatement(); case 101: @@ -7422,44 +8092,70 @@ var ts; return parseTryStatement(); case 72: return parseDebuggerStatement(); - case 104: - if (isLetDeclaration()) { - return parseVariableStatement(scanner.getStartPos(), undefined, undefined); + case 52: + return parseDeclaration(); + case 103: + case 125: + case 118: + case 119: + case 115: + case 70: + case 77: + case 78: + case 85: + case 106: + case 107: + case 108: + case 109: + if (isStartOfDeclaration()) { + return parseDeclaration(); } - default: - if (ts.isModifier(token) || token === 52) { - var result = tryParse(parseVariableStatementOrFunctionDeclarationOrClassDeclarationWithDecoratorsOrModifiers); - if (result) { - return result; - } - } - return parseExpressionOrLabeledStatement(); + break; } + return parseExpressionOrLabeledStatement(); } - function parseVariableStatementOrFunctionDeclarationOrClassDeclarationWithDecoratorsOrModifiers() { - var start = scanner.getStartPos(); + function parseDeclaration() { + var fullStart = getNodePos(); var decorators = parseDecorators(); var modifiers = parseModifiers(); switch (token) { - case 70: - var nextTokenIsEnum = lookAhead(nextTokenIsEnumKeyword); - if (nextTokenIsEnum) { - return undefined; - } - return parseVariableStatement(start, decorators, modifiers); - case 104: - if (!isLetDeclaration()) { - return undefined; - } - return parseVariableStatement(start, decorators, modifiers); case 98: - return parseVariableStatement(start, decorators, modifiers); + case 104: + case 70: + return parseVariableStatement(fullStart, decorators, modifiers); case 83: - return parseFunctionDeclaration(start, decorators, modifiers); + return parseFunctionDeclaration(fullStart, decorators, modifiers); case 69: - return parseClassDeclaration(start, decorators, modifiers); + return parseClassDeclaration(fullStart, decorators, modifiers); + case 103: + return parseInterfaceDeclaration(fullStart, decorators, modifiers); + case 125: + return parseTypeAliasDeclaration(fullStart, decorators, modifiers); + case 77: + return parseEnumDeclaration(fullStart, decorators, modifiers); + case 118: + case 119: + return parseModuleDeclaration(fullStart, decorators, modifiers); + case 85: + return parseImportDeclarationOrImportEqualsDeclaration(fullStart, decorators, modifiers); + case 78: + nextToken(); + return token === 73 || token === 53 ? + parseExportAssignment(fullStart, decorators, modifiers) : + parseExportDeclaration(fullStart, decorators, modifiers); + default: + if (decorators || modifiers) { + var node = createMissingNode(221, true, ts.Diagnostics.Declaration_expected); + node.pos = fullStart; + node.decorators = decorators; + setModifiers(node, modifiers); + return finishNode(node); + } } - return undefined; + } + function nextTokenIsIdentifierOrStringLiteralOnSameLine() { + nextToken(); + return !scanner.hasPrecedingLineBreak() && (isIdentifier() || token === 8); } function parseFunctionBlockOrSemicolon(isGenerator, diagnosticMessage) { if (token !== 14 && canParseSemicolon()) { @@ -7470,16 +8166,16 @@ var ts; } function parseArrayBindingElement() { if (token === 23) { - return createNode(176); + return createNode(178); } - var node = createNode(153); + var node = createNode(155); node.dotDotDotToken = parseOptionalToken(21); node.name = parseIdentifierOrPattern(); node.initializer = parseInitializer(false); return finishNode(node); } function parseObjectBindingElement() { - var node = createNode(153); + var node = createNode(155); var tokenIsIdentifier = isIdentifier(); var propertyName = parsePropertyName(); if (tokenIsIdentifier && token !== 51) { @@ -7494,16 +8190,16 @@ var ts; return finishNode(node); } function parseObjectBindingPattern() { - var node = createNode(151); + var node = createNode(153); parseExpected(14); - node.elements = parseDelimitedList(10, parseObjectBindingElement); + node.elements = parseDelimitedList(9, parseObjectBindingElement); parseExpected(15); return finishNode(node); } function parseArrayBindingPattern() { - var node = createNode(152); + var node = createNode(154); parseExpected(18); - node.elements = parseDelimitedList(11, parseArrayBindingElement); + node.elements = parseDelimitedList(10, parseArrayBindingElement); parseExpected(19); return finishNode(node); } @@ -7520,7 +8216,7 @@ var ts; return parseIdentifier(); } function parseVariableDeclaration() { - var node = createNode(199); + var node = createNode(201); node.name = parseIdentifierOrPattern(); node.type = parseTypeAnnotation(); if (!isInOrOfKeyword(token)) { @@ -7529,7 +8225,7 @@ var ts; return finishNode(node); } function parseVariableDeclarationList(inForStatementInitializer) { - var node = createNode(200); + var node = createNode(202); switch (token) { case 98: break; @@ -7543,13 +8239,13 @@ var ts; ts.Debug.fail(); } nextToken(); - if (token === 126 && lookAhead(canFollowContextualOfKeyword)) { + if (token === 127 && lookAhead(canFollowContextualOfKeyword)) { node.declarations = createMissingList(); } else { var savedDisallowIn = inDisallowInContext(); setDisallowInContext(inForStatementInitializer); - node.declarations = parseDelimitedList(9, parseVariableDeclaration); + node.declarations = parseDelimitedList(8, parseVariableDeclaration); setDisallowInContext(savedDisallowIn); } return finishNode(node); @@ -7558,7 +8254,7 @@ var ts; return nextTokenIsIdentifier() && nextToken() === 17; } function parseVariableStatement(fullStart, decorators, modifiers) { - var node = createNode(181, fullStart); + var node = createNode(183, fullStart); node.decorators = decorators; setModifiers(node, modifiers); node.declarationList = parseVariableDeclarationList(false); @@ -7566,7 +8262,7 @@ var ts; return finishNode(node); } function parseFunctionDeclaration(fullStart, decorators, modifiers) { - var node = createNode(201, fullStart); + var node = createNode(203, fullStart); node.decorators = decorators; setModifiers(node, modifiers); parseExpected(83); @@ -7577,7 +8273,7 @@ var ts; return finishNode(node); } function parseConstructorDeclaration(pos, decorators, modifiers) { - var node = createNode(136, pos); + var node = createNode(137, pos); node.decorators = decorators; setModifiers(node, modifiers); parseExpected(114); @@ -7586,7 +8282,7 @@ var ts; return finishNode(node); } function parseMethodDeclaration(fullStart, decorators, modifiers, asteriskToken, name, questionToken, diagnosticMessage) { - var method = createNode(135, fullStart); + var method = createNode(136, fullStart); method.decorators = decorators; setModifiers(method, modifiers); method.asteriskToken = asteriskToken; @@ -7597,13 +8293,15 @@ var ts; return finishNode(method); } function parsePropertyDeclaration(fullStart, decorators, modifiers, name, questionToken) { - var property = createNode(133, fullStart); + var property = createNode(134, fullStart); property.decorators = decorators; setModifiers(property, modifiers); property.name = name; property.questionToken = questionToken; property.type = parseTypeAnnotation(); - property.initializer = allowInAnd(parseNonParameterInitializer); + property.initializer = modifiers && modifiers.flags & 128 + ? allowInAnd(parseNonParameterInitializer) + : doOutsideOfContext(4 | 2, parseNonParameterInitializer); parseSemicolon(); return finishNode(property); } @@ -7664,7 +8362,7 @@ var ts; return true; } if (idToken !== undefined) { - if (!ts.isKeyword(idToken) || idToken === 121 || idToken === 116) { + if (!ts.isKeyword(idToken) || idToken === 122 || idToken === 116) { return true; } switch (token) { @@ -7691,7 +8389,7 @@ var ts; decorators = []; decorators.pos = scanner.getStartPos(); } - var decorator = createNode(131, decoratorStart); + var decorator = createNode(132, decoratorStart); decorator.expression = doInDecoratorContext(parseLeftHandSideExpressionOrHigher); decorators.push(finishNode(decorator)); } @@ -7724,7 +8422,7 @@ var ts; } function parseClassElement() { if (token === 22) { - var result = createNode(179); + var result = createNode(181); nextToken(); return finishNode(result); } @@ -7748,21 +8446,19 @@ var ts; token === 18) { return parsePropertyOrMethodDeclaration(fullStart, decorators, modifiers); } - if (decorators) { - var name_3 = createMissingNode(65, true, ts.Diagnostics.Declaration_expected); - return parsePropertyDeclaration(fullStart, decorators, modifiers, name_3, undefined); + if (decorators || modifiers) { + var name_6 = createMissingNode(65, true, ts.Diagnostics.Declaration_expected); + return parsePropertyDeclaration(fullStart, decorators, modifiers, name_6, undefined); } ts.Debug.fail("Should not have attempted to parse class member declaration."); } function parseClassExpression() { - return parseClassDeclarationOrExpression(scanner.getStartPos(), undefined, undefined, 175); + return parseClassDeclarationOrExpression(scanner.getStartPos(), undefined, undefined, 177); } function parseClassDeclaration(fullStart, decorators, modifiers) { - return parseClassDeclarationOrExpression(fullStart, decorators, modifiers, 202); + return parseClassDeclarationOrExpression(fullStart, decorators, modifiers, 204); } function parseClassDeclarationOrExpression(fullStart, decorators, modifiers, kind) { - var savedStrictModeContext = inStrictModeContext(); - setStrictModeContext(true); var node = createNode(kind, fullStart); node.decorators = decorators; setModifiers(node, modifiers); @@ -7779,9 +8475,7 @@ var ts; else { node.members = createMissingList(); } - var finishedNode = finishNode(node); - setStrictModeContext(savedStrictModeContext); - return finishedNode; + return finishNode(node); } function parseHeritageClauses(isClassHeritageClause) { // ClassTail[Yield,GeneratorParameter] : See 14.5 @@ -7795,23 +8489,23 @@ var ts; return undefined; } function parseHeritageClausesWorker() { - return parseList(19, false, parseHeritageClause); + return parseList(18, parseHeritageClause); } function parseHeritageClause() { if (token === 79 || token === 102) { - var node = createNode(223); + var node = createNode(225); node.token = token; nextToken(); - node.types = parseDelimitedList(8, parseExpressionWithTypeArguments); + node.types = parseDelimitedList(7, parseExpressionWithTypeArguments); return finishNode(node); } return undefined; } function parseExpressionWithTypeArguments() { - var node = createNode(177); + var node = createNode(179); node.expression = parseLeftHandSideExpressionOrHigher(); if (token === 24) { - node.typeArguments = parseBracketedList(17, parseType, 24, 25); + node.typeArguments = parseBracketedList(16, parseType, 24, 25); } return finishNode(node); } @@ -7819,10 +8513,10 @@ var ts; return token === 79 || token === 102; } function parseClassMembers() { - return parseList(6, false, parseClassElement); + return parseList(5, parseClassElement); } function parseInterfaceDeclaration(fullStart, decorators, modifiers) { - var node = createNode(203, fullStart); + var node = createNode(205, fullStart); node.decorators = decorators; setModifiers(node, modifiers); parseExpected(103); @@ -7833,30 +8527,31 @@ var ts; return finishNode(node); } function parseTypeAliasDeclaration(fullStart, decorators, modifiers) { - var node = createNode(204, fullStart); + var node = createNode(206, fullStart); node.decorators = decorators; setModifiers(node, modifiers); - parseExpected(124); + parseExpected(125); node.name = parseIdentifier(); + node.typeParameters = parseTypeParameters(); parseExpected(53); node.type = parseType(); parseSemicolon(); return finishNode(node); } function parseEnumMember() { - var node = createNode(227, scanner.getStartPos()); + var node = createNode(229, scanner.getStartPos()); node.name = parsePropertyName(); node.initializer = allowInAnd(parseNonParameterInitializer); return finishNode(node); } function parseEnumDeclaration(fullStart, decorators, modifiers) { - var node = createNode(205, fullStart); + var node = createNode(207, fullStart); node.decorators = decorators; setModifiers(node, modifiers); parseExpected(77); node.name = parseIdentifier(); if (parseExpected(14)) { - node.members = parseDelimitedList(7, parseEnumMember); + node.members = parseDelimitedList(6, parseEnumMember); parseExpected(15); } else { @@ -7865,9 +8560,9 @@ var ts; return finishNode(node); } function parseModuleBlock() { - var node = createNode(207, scanner.getStartPos()); + var node = createNode(209, scanner.getStartPos()); if (parseExpected(14)) { - node.statements = parseList(1, false, parseModuleElement); + node.statements = parseList(1, parseStatement); parseExpected(15); } else { @@ -7876,7 +8571,7 @@ var ts; return finishNode(node); } function parseModuleOrNamespaceDeclaration(fullStart, decorators, modifiers, flags) { - var node = createNode(206, fullStart); + var node = createNode(208, fullStart); node.decorators = decorators; setModifiers(node, modifiers); node.flags |= flags; @@ -7887,7 +8582,7 @@ var ts; return finishNode(node); } function parseAmbientExternalModuleDeclaration(fullStart, decorators, modifiers) { - var node = createNode(206, fullStart); + var node = createNode(208, fullStart); node.decorators = decorators; setModifiers(node, modifiers); node.name = parseLiteralNode(true); @@ -7896,11 +8591,11 @@ var ts; } function parseModuleDeclaration(fullStart, decorators, modifiers) { var flags = modifiers ? modifiers.flags : 0; - if (parseOptional(118)) { + if (parseOptional(119)) { flags |= 32768; } else { - parseExpected(117); + parseExpected(118); if (token === 8) { return parseAmbientExternalModuleDeclaration(fullStart, decorators, modifiers); } @@ -7908,7 +8603,7 @@ var ts; return parseModuleOrNamespaceDeclaration(fullStart, decorators, modifiers, flags); } function isExternalModuleReference() { - return token === 119 && + return token === 120 && lookAhead(nextTokenIsOpenParen); } function nextTokenIsOpenParen() { @@ -7917,7 +8612,7 @@ var ts; function nextTokenIsCommaOrFromKeyword() { nextToken(); return token === 23 || - token === 125; + token === 126; } function parseImportDeclarationOrImportEqualsDeclaration(fullStart, decorators, modifiers) { parseExpected(85); @@ -7925,8 +8620,8 @@ var ts; var identifier; if (isIdentifier()) { identifier = parseIdentifier(); - if (token !== 23 && token !== 125) { - var importEqualsDeclaration = createNode(209, fullStart); + if (token !== 23 && token !== 126) { + var importEqualsDeclaration = createNode(211, fullStart); importEqualsDeclaration.decorators = decorators; setModifiers(importEqualsDeclaration, modifiers); importEqualsDeclaration.name = identifier; @@ -7936,14 +8631,14 @@ var ts; return finishNode(importEqualsDeclaration); } } - var importDeclaration = createNode(210, fullStart); + var importDeclaration = createNode(212, fullStart); importDeclaration.decorators = decorators; setModifiers(importDeclaration, modifiers); if (identifier || token === 35 || token === 14) { importDeclaration.importClause = parseImportClause(identifier, afterImportPos); - parseExpected(125); + parseExpected(126); } importDeclaration.moduleSpecifier = parseModuleSpecifier(); parseSemicolon(); @@ -7956,13 +8651,13 @@ var ts; // NamedImports // ImportedDefaultBinding, NameSpaceImport // ImportedDefaultBinding, NamedImports - var importClause = createNode(211, fullStart); + var importClause = createNode(213, fullStart); if (identifier) { importClause.name = identifier; } if (!importClause.name || parseOptional(23)) { - importClause.namedBindings = token === 35 ? parseNamespaceImport() : parseNamedImportsOrExports(213); + importClause.namedBindings = token === 35 ? parseNamespaceImport() : parseNamedImportsOrExports(215); } return finishNode(importClause); } @@ -7972,8 +8667,8 @@ var ts; : parseEntityName(false); } function parseExternalModuleReference() { - var node = createNode(220); - parseExpected(119); + var node = createNode(222); + parseExpected(120); parseExpected(16); node.expression = parseModuleSpecifier(); parseExpected(17); @@ -7987,7 +8682,7 @@ var ts; return result; } function parseNamespaceImport() { - var namespaceImport = createNode(212); + var namespaceImport = createNode(214); parseExpected(35); parseExpected(111); namespaceImport.name = parseIdentifier(); @@ -7995,14 +8690,14 @@ var ts; } function parseNamedImportsOrExports(kind) { var node = createNode(kind); - node.elements = parseBracketedList(20, kind === 213 ? parseImportSpecifier : parseExportSpecifier, 14, 15); + node.elements = parseBracketedList(19, kind === 215 ? parseImportSpecifier : parseExportSpecifier, 14, 15); return finishNode(node); } function parseExportSpecifier() { - return parseImportOrExportSpecifier(218); + return parseImportOrExportSpecifier(220); } function parseImportSpecifier() { - return parseImportOrExportSpecifier(214); + return parseImportOrExportSpecifier(216); } function parseImportOrExportSpecifier(kind) { var node = createNode(kind); @@ -8021,22 +8716,22 @@ var ts; else { node.name = identifierName; } - if (kind === 214 && checkIdentifierIsKeyword) { + if (kind === 216 && checkIdentifierIsKeyword) { parseErrorAtPosition(checkIdentifierStart, checkIdentifierEnd - checkIdentifierStart, ts.Diagnostics.Identifier_expected); } return finishNode(node); } function parseExportDeclaration(fullStart, decorators, modifiers) { - var node = createNode(216, fullStart); + var node = createNode(218, fullStart); node.decorators = decorators; setModifiers(node, modifiers); if (parseOptional(35)) { - parseExpected(125); + parseExpected(126); node.moduleSpecifier = parseModuleSpecifier(); } else { - node.exportClause = parseNamedImportsOrExports(217); - if (parseOptional(125)) { + node.exportClause = parseNamedImportsOrExports(219); + if (parseOptional(126)) { node.moduleSpecifier = parseModuleSpecifier(); } } @@ -8044,7 +8739,7 @@ var ts; return finishNode(node); } function parseExportAssignment(fullStart, decorators, modifiers) { - var node = createNode(215, fullStart); + var node = createNode(217, fullStart); node.decorators = decorators; setModifiers(node, modifiers); if (parseOptional(53)) { @@ -8057,125 +8752,6 @@ var ts; parseSemicolon(); return finishNode(node); } - function isLetDeclaration() { - return inStrictModeContext() || lookAhead(nextTokenIsIdentifierOrStartOfDestructuringOnTheSameLine); - } - function isDeclarationStart(followsModifier) { - switch (token) { - case 98: - case 70: - case 83: - return true; - case 104: - return isLetDeclaration(); - case 69: - case 103: - case 77: - case 124: - return lookAhead(nextTokenIsIdentifierOrKeyword); - case 85: - return lookAhead(nextTokenCanFollowImportKeyword); - case 117: - case 118: - return lookAhead(nextTokenIsIdentifierOrKeywordOrStringLiteral); - case 78: - return lookAhead(nextTokenCanFollowExportKeyword); - case 115: - case 108: - case 106: - case 107: - case 109: - return lookAhead(nextTokenIsDeclarationStart); - case 52: - return !followsModifier; - } - } - function isIdentifierOrKeyword() { - return token >= 65; - } - function nextTokenIsIdentifierOrKeyword() { - nextToken(); - return isIdentifierOrKeyword(); - } - function nextTokenIsIdentifierOrKeywordOrStringLiteral() { - nextToken(); - return isIdentifierOrKeyword() || token === 8; - } - function nextTokenCanFollowImportKeyword() { - nextToken(); - return isIdentifierOrKeyword() || token === 8 || - token === 35 || token === 14; - } - function nextTokenCanFollowExportKeyword() { - nextToken(); - return token === 53 || token === 35 || - token === 14 || token === 73 || isDeclarationStart(true); - } - function nextTokenIsDeclarationStart() { - nextToken(); - return isDeclarationStart(true); - } - function nextTokenIsAsKeyword() { - return nextToken() === 111; - } - function parseDeclaration() { - var fullStart = getNodePos(); - var decorators = parseDecorators(); - var modifiers = parseModifiers(); - if (token === 78) { - nextToken(); - if (token === 73 || token === 53) { - return parseExportAssignment(fullStart, decorators, modifiers); - } - if (token === 35 || token === 14) { - return parseExportDeclaration(fullStart, decorators, modifiers); - } - } - switch (token) { - case 98: - case 104: - case 70: - return parseVariableStatement(fullStart, decorators, modifiers); - case 83: - return parseFunctionDeclaration(fullStart, decorators, modifiers); - case 69: - return parseClassDeclaration(fullStart, decorators, modifiers); - case 103: - return parseInterfaceDeclaration(fullStart, decorators, modifiers); - case 124: - return parseTypeAliasDeclaration(fullStart, decorators, modifiers); - case 77: - return parseEnumDeclaration(fullStart, decorators, modifiers); - case 117: - case 118: - return parseModuleDeclaration(fullStart, decorators, modifiers); - case 85: - return parseImportDeclarationOrImportEqualsDeclaration(fullStart, decorators, modifiers); - default: - if (decorators) { - var node = createMissingNode(219, true, ts.Diagnostics.Declaration_expected); - node.pos = fullStart; - node.decorators = decorators; - setModifiers(node, modifiers); - return finishNode(node); - } - ts.Debug.fail("Mismatch between isDeclarationStart and parseDeclaration"); - } - } - function isSourceElement(inErrorRecovery) { - return isDeclarationStart() || isStartOfStatement(inErrorRecovery); - } - function parseSourceElement() { - return parseSourceElementOrModuleElement(); - } - function parseModuleElement() { - return parseSourceElementOrModuleElement(); - } - function parseSourceElementOrModuleElement() { - return isDeclarationStart() - ? parseDeclaration() - : parseStatement(); - } function processReferenceComments(sourceFile) { var triviaScanner = ts.createScanner(sourceFile.languageVersion, false, sourceText); var referencedFiles = []; @@ -8200,7 +8776,7 @@ var ts; referencedFiles.push(fileReference); } if (diagnosticMessage) { - sourceFile.parseDiagnostics.push(ts.createFileDiagnostic(sourceFile, range.pos, range.end - range.pos, diagnosticMessage)); + parseDiagnostics.push(ts.createFileDiagnostic(sourceFile, range.pos, range.end - range.pos, diagnosticMessage)); } } else { @@ -8208,7 +8784,7 @@ var ts; var amdModuleNameMatchResult = amdModuleNameRegEx.exec(comment); if (amdModuleNameMatchResult) { if (amdModuleName) { - sourceFile.parseDiagnostics.push(ts.createFileDiagnostic(sourceFile, range.pos, range.end - range.pos, ts.Diagnostics.An_AMD_module_cannot_have_multiple_name_assignments)); + parseDiagnostics.push(ts.createFileDiagnostic(sourceFile, range.pos, range.end - range.pos, ts.Diagnostics.An_AMD_module_cannot_have_multiple_name_assignments)); } amdModuleName = amdModuleNameMatchResult[2]; } @@ -8228,19 +8804,527 @@ var ts; } sourceFile.referencedFiles = referencedFiles; sourceFile.amdDependencies = amdDependencies; - sourceFile.amdModuleName = amdModuleName; + sourceFile.moduleName = amdModuleName; } function setExternalModuleIndicator(sourceFile) { sourceFile.externalModuleIndicator = ts.forEach(sourceFile.statements, function (node) { return node.flags & 1 - || node.kind === 209 && node.moduleReference.kind === 220 - || node.kind === 210 - || node.kind === 215 - || node.kind === 216 + || node.kind === 211 && node.moduleReference.kind === 222 + || node.kind === 212 + || node.kind === 217 + || node.kind === 218 ? node : undefined; }); } + var JSDocParser; + (function (JSDocParser) { + function isJSDocType() { + switch (token) { + case 35: + case 50: + case 16: + case 18: + case 46: + case 14: + case 83: + case 21: + case 88: + case 93: + return true; + } + return isIdentifierOrKeyword(); + } + JSDocParser.isJSDocType = isJSDocType; + function parseJSDocTypeExpressionForTests(content, start, length) { + initializeState("file.js", content, 2, undefined); + var jsDocTypeExpression = parseJSDocTypeExpression(start, length); + var diagnostics = parseDiagnostics; + clearState(); + return jsDocTypeExpression ? { jsDocTypeExpression: jsDocTypeExpression, diagnostics: diagnostics } : undefined; + } + JSDocParser.parseJSDocTypeExpressionForTests = parseJSDocTypeExpressionForTests; + function parseJSDocTypeExpression(start, length) { + scanner.setText(sourceText, start, length); + token = nextToken(); + var result = createNode(231); + parseExpected(14); + result.type = parseJSDocTopLevelType(); + parseExpected(15); + fixupParentReferences(result); + return finishNode(result); + } + JSDocParser.parseJSDocTypeExpression = parseJSDocTypeExpression; + function parseJSDocTopLevelType() { + var type = parseJSDocType(); + if (token === 44) { + var unionType = createNode(235, type.pos); + unionType.types = parseJSDocTypeList(type); + type = finishNode(unionType); + } + if (token === 53) { + var optionalType = createNode(242, type.pos); + nextToken(); + optionalType.type = type; + type = finishNode(optionalType); + } + return type; + } + function parseJSDocType() { + var type = parseBasicTypeExpression(); + while (true) { + if (token === 18) { + var arrayType = createNode(234, type.pos); + arrayType.elementType = type; + nextToken(); + parseExpected(19); + type = finishNode(arrayType); + } + else if (token === 50) { + var nullableType = createNode(237, type.pos); + nullableType.type = type; + nextToken(); + type = finishNode(nullableType); + } + else if (token === 46) { + var nonNullableType = createNode(238, type.pos); + nonNullableType.type = type; + nextToken(); + type = finishNode(nonNullableType); + } + else { + break; + } + } + return type; + } + function parseBasicTypeExpression() { + switch (token) { + case 35: + return parseJSDocAllType(); + case 50: + return parseJSDocUnknownOrNullableType(); + case 16: + return parseJSDocUnionType(); + case 18: + return parseJSDocTupleType(); + case 46: + return parseJSDocNonNullableType(); + case 14: + return parseJSDocRecordType(); + case 83: + return parseJSDocFunctionType(); + case 21: + return parseJSDocVariadicType(); + case 88: + return parseJSDocConstructorType(); + case 93: + return parseJSDocThisType(); + case 112: + case 123: + case 121: + case 113: + case 124: + case 99: + return parseTokenNode(); + } + return parseJSDocTypeReference(); + } + function parseJSDocThisType() { + var result = createNode(246); + nextToken(); + parseExpected(51); + result.type = parseJSDocType(); + return finishNode(result); + } + function parseJSDocConstructorType() { + var result = createNode(245); + nextToken(); + parseExpected(51); + result.type = parseJSDocType(); + return finishNode(result); + } + function parseJSDocVariadicType() { + var result = createNode(244); + nextToken(); + result.type = parseJSDocType(); + return finishNode(result); + } + function parseJSDocFunctionType() { + var result = createNode(243); + nextToken(); + parseExpected(16); + result.parameters = parseDelimitedList(20, parseJSDocParameter); + checkForTrailingComma(result.parameters); + parseExpected(17); + if (token === 51) { + nextToken(); + result.type = parseJSDocType(); + } + return finishNode(result); + } + function parseJSDocParameter() { + var parameter = createNode(131); + parameter.type = parseJSDocType(); + return finishNode(parameter); + } + function parseJSDocOptionalType(type) { + var result = createNode(242, type.pos); + nextToken(); + result.type = type; + return finishNode(result); + } + function parseJSDocTypeReference() { + var result = createNode(241); + result.name = parseSimplePropertyName(); + while (parseOptional(20)) { + if (token === 24) { + result.typeArguments = parseTypeArguments(); + break; + } + else { + result.name = parseQualifiedName(result.name); + } + } + return finishNode(result); + } + function parseTypeArguments() { + nextToken(); + var typeArguments = parseDelimitedList(21, parseJSDocType); + checkForTrailingComma(typeArguments); + checkForEmptyTypeArgumentList(typeArguments); + parseExpected(25); + return typeArguments; + } + function checkForEmptyTypeArgumentList(typeArguments) { + if (parseDiagnostics.length === 0 && typeArguments && typeArguments.length === 0) { + var start = typeArguments.pos - "<".length; + var end = ts.skipTrivia(sourceText, typeArguments.end) + ">".length; + return parseErrorAtPosition(start, end - start, ts.Diagnostics.Type_argument_list_cannot_be_empty); + } + } + function parseQualifiedName(left) { + var result = createNode(128, left.pos); + result.left = left; + result.right = parseIdentifierName(); + return finishNode(result); + } + function parseJSDocRecordType() { + var result = createNode(239); + nextToken(); + result.members = parseDelimitedList(22, parseJSDocRecordMember); + checkForTrailingComma(result.members); + parseExpected(15); + return finishNode(result); + } + function parseJSDocRecordMember() { + var result = createNode(240); + result.name = parseSimplePropertyName(); + if (token === 51) { + nextToken(); + result.type = parseJSDocType(); + } + return finishNode(result); + } + function parseJSDocNonNullableType() { + var result = createNode(238); + nextToken(); + result.type = parseJSDocType(); + return finishNode(result); + } + function parseJSDocTupleType() { + var result = createNode(236); + nextToken(); + result.types = parseDelimitedList(23, parseJSDocType); + checkForTrailingComma(result.types); + parseExpected(19); + 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(235); + nextToken(); + result.types = parseJSDocTypeList(parseJSDocType()); + parseExpected(17); + return finishNode(result); + } + function parseJSDocTypeList(firstType) { + ts.Debug.assert(!!firstType); + var types = []; + types.pos = firstType.pos; + types.push(firstType); + while (parseOptional(44)) { + types.push(parseJSDocType()); + } + types.end = scanner.getStartPos(); + return types; + } + function parseJSDocAllType() { + var result = createNode(232); + nextToken(); + return finishNode(result); + } + function parseJSDocUnknownOrNullableType() { + var pos = scanner.getStartPos(); + nextToken(); + if (token === 23 || + token === 15 || + token === 17 || + token === 25 || + token === 53 || + token === 44) { + var result = createNode(233, pos); + return finishNode(result); + } + else { + var result = createNode(237, pos); + result.type = parseJSDocType(); + return finishNode(result); + } + } + function parseIsolatedJSDocComment(content, start, length) { + initializeState("file.js", content, 2, undefined); + var jsDocComment = parseJSDocComment(undefined, start, length); + var diagnostics = parseDiagnostics; + clearState(); + return jsDocComment ? { jsDocComment: jsDocComment, diagnostics: diagnostics } : undefined; + } + JSDocParser.parseIsolatedJSDocComment = parseIsolatedJSDocComment; + function parseJSDocComment(parent, start, length) { + var comment = parseJSDocCommentWorker(start, length); + if (comment) { + fixupParentReferences(comment); + comment.parent = parent; + } + return comment; + } + JSDocParser.parseJSDocComment = parseJSDocComment; + 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 pos; + if (length >= "/** */".length) { + if (content.charCodeAt(start) === 47 && + content.charCodeAt(start + 1) === 42 && + content.charCodeAt(start + 2) === 42 && + content.charCodeAt(start + 3) !== 42) { + var canParseTag = true; + var seenAsterisk = true; + for (pos = start + "/**".length; pos < end;) { + var ch = content.charCodeAt(pos); + pos++; + if (ch === 64 && canParseTag) { + parseTag(); + canParseTag = false; + continue; + } + if (ts.isLineBreak(ch)) { + canParseTag = true; + seenAsterisk = false; + continue; + } + if (ts.isWhiteSpace(ch)) { + continue; + } + if (ch === 42) { + if (seenAsterisk) { + canParseTag = false; + } + seenAsterisk = true; + continue; + } + canParseTag = false; + } + } + } + return createJSDocComment(); + function createJSDocComment() { + if (!tags) { + return undefined; + } + var result = createNode(247, start); + result.tags = tags; + return finishNode(result, end); + } + function skipWhitespace() { + while (pos < end && ts.isWhiteSpace(content.charCodeAt(pos))) { + pos++; + } + } + function parseTag() { + ts.Debug.assert(content.charCodeAt(pos - 1) === 64); + var atToken = createNode(52, pos - 1); + atToken.end = pos; + var startPos = pos; + var tagName = scanIdentifier(); + if (!tagName) { + return; + } + var tag = handleTag(atToken, tagName) || handleUnknownTag(atToken, tagName); + addTag(tag); + } + function handleTag(atToken, tagName) { + if (tagName) { + switch (tagName.text) { + case "param": + return handleParamTag(atToken, tagName); + case "return": + case "returns": + return handleReturnTag(atToken, tagName); + case "template": + return handleTemplateTag(atToken, tagName); + case "type": + return handleTypeTag(atToken, tagName); + } + } + return undefined; + } + function handleUnknownTag(atToken, tagName) { + var result = createNode(248, atToken.pos); + result.atToken = atToken; + result.tagName = tagName; + return finishNode(result, pos); + } + function addTag(tag) { + if (tag) { + if (!tags) { + tags = []; + tags.pos = tag.pos; + } + tags.push(tag); + tags.end = tag.end; + } + } + function tryParseTypeExpression() { + skipWhitespace(); + if (content.charCodeAt(pos) !== 123) { + return undefined; + } + var typeExpression = parseJSDocTypeExpression(pos, end - pos); + pos = typeExpression.end; + return typeExpression; + } + function handleParamTag(atToken, tagName) { + var typeExpression = tryParseTypeExpression(); + skipWhitespace(); + var name; + var isBracketed; + if (content.charCodeAt(pos) === 91) { + pos++; + skipWhitespace(); + name = scanIdentifier(); + isBracketed = true; + } + else { + name = scanIdentifier(); + } + if (!name) { + parseErrorAtPosition(pos, 0, ts.Diagnostics.Identifier_expected); + return undefined; + } + var preName, postName; + if (typeExpression) { + postName = name; + } + else { + preName = name; + } + if (!typeExpression) { + typeExpression = tryParseTypeExpression(); + } + var result = createNode(249, atToken.pos); + result.atToken = atToken; + result.tagName = tagName; + result.preParameterName = preName; + result.typeExpression = typeExpression; + result.postParameterName = postName; + result.isBracketed = isBracketed; + return finishNode(result, pos); + } + function handleReturnTag(atToken, tagName) { + if (ts.forEach(tags, function (t) { return t.kind === 250; })) { + parseErrorAtPosition(tagName.pos, pos - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.text); + } + var result = createNode(250, atToken.pos); + result.atToken = atToken; + result.tagName = tagName; + result.typeExpression = tryParseTypeExpression(); + return finishNode(result, pos); + } + function handleTypeTag(atToken, tagName) { + if (ts.forEach(tags, function (t) { return t.kind === 251; })) { + parseErrorAtPosition(tagName.pos, pos - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.text); + } + var result = createNode(251, atToken.pos); + result.atToken = atToken; + result.tagName = tagName; + result.typeExpression = tryParseTypeExpression(); + return finishNode(result, pos); + } + function handleTemplateTag(atToken, tagName) { + if (ts.forEach(tags, function (t) { return t.kind === 252; })) { + parseErrorAtPosition(tagName.pos, pos - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.text); + } + var typeParameters = []; + typeParameters.pos = pos; + while (true) { + skipWhitespace(); + var startPos = pos; + var name_7 = scanIdentifier(); + if (!name_7) { + parseErrorAtPosition(startPos, 0, ts.Diagnostics.Identifier_expected); + return undefined; + } + var typeParameter = createNode(130, name_7.pos); + typeParameter.name = name_7; + finishNode(typeParameter, pos); + typeParameters.push(typeParameter); + skipWhitespace(); + if (content.charCodeAt(pos) !== 44) { + break; + } + pos++; + } + typeParameters.end = pos; + var result = createNode(252, atToken.pos); + result.atToken = atToken; + result.tagName = tagName; + result.typeParameters = typeParameters; + return finishNode(result, pos); + } + function scanIdentifier() { + var startPos = pos; + for (; pos < end; pos++) { + var ch = content.charCodeAt(pos); + if (pos === startPos && ts.isIdentifierStart(ch, 2)) { + continue; + } + else if (pos > startPos && ts.isIdentifierPart(ch, 2)) { + continue; + } + break; + } + if (startPos === pos) { + return undefined; + } + var result = createNode(65, startPos); + result.text = content.substring(startPos, pos); + return finishNode(result, pos); + } + } + JSDocParser.parseJSDocCommentWorker = parseJSDocCommentWorker; + })(JSDocParser = Parser.JSDocParser || (Parser.JSDocParser = {})); })(Parser || (Parser = {})); var IncrementalParser; (function (IncrementalParser) { @@ -8281,7 +9365,12 @@ var ts; if (aggressiveChecks && shouldCheckNode(node)) { var text = oldText.substring(node.pos, node.end); } - node._children = undefined; + if (node._children) { + node._children = undefined; + } + if (node.jsDocComment) { + node.jsDocComment = undefined; + } node.pos += delta; node.end += delta; if (aggressiveChecks && shouldCheckNode(node)) { @@ -8592,18 +9681,20 @@ var ts; var stringType = createIntrinsicType(2, "string"); var numberType = createIntrinsicType(4, "number"); var booleanType = createIntrinsicType(8, "boolean"); - var esSymbolType = createIntrinsicType(1048576, "symbol"); + var esSymbolType = createIntrinsicType(2097152, "symbol"); var voidType = createIntrinsicType(16, "void"); - var undefinedType = createIntrinsicType(32 | 262144, "undefined"); - var nullType = createIntrinsicType(64 | 262144, "null"); + var undefinedType = createIntrinsicType(32 | 524288, "undefined"); + var nullType = createIntrinsicType(64 | 524288, "null"); var unknownType = createIntrinsicType(1, "unknown"); + var circularType = createIntrinsicType(1, "__circular__"); var emptyObjectType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); + var emptyGenericType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); + emptyGenericType.instantiations = {}; var anyFunctionType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); var noConstraintType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); - var anySignature = createSignature(undefined, undefined, emptyArray, anyType, 0, false, false); - var unknownSignature = createSignature(undefined, undefined, emptyArray, unknownType, 0, false, false); + var anySignature = createSignature(undefined, undefined, emptyArray, anyType, undefined, 0, false, false); + var unknownSignature = createSignature(undefined, undefined, emptyArray, unknownType, undefined, 0, false, false); var globals = {}; - var globalArraySymbol; var globalESSymbolConstructorSymbol; var globalObjectType; var globalFunctionType; @@ -8615,6 +9706,8 @@ var ts; var globalTemplateStringsArrayType; var globalESSymbolType; var globalIterableType; + var globalIteratorType; + var globalIterableIteratorType; var anyArrayType; var getGlobalClassDecoratorType; var getGlobalParameterDecoratorType; @@ -8648,9 +9741,14 @@ var ts; }, "symbol": { type: esSymbolType, - flags: 1048576 + flags: 2097152 } }; + var subtypeRelation = {}; + var assignableRelation = {}; + var identityRelation = {}; + initializeTypeChecker(); + return checker; function getEmitResolver(sourceFile) { getDiagnostics(sourceFile); return emitResolver; @@ -8790,10 +9888,10 @@ var ts; return nodeLinks[nodeId] || (nodeLinks[nodeId] = {}); } function getSourceFile(node) { - return ts.getAncestor(node, 228); + return ts.getAncestor(node, 230); } function isGlobalSourceFile(node) { - return node.kind === 228 && !ts.isExternalModule(node); + return node.kind === 230 && !ts.isExternalModule(node); } function getSymbol(symbols, name, meaning) { if (meaning && ts.hasProperty(symbols, name)) { @@ -8831,38 +9929,47 @@ var ts; loop: while (location) { if (location.locals && !isGlobalSourceFile(location)) { if (result = getSymbol(location.locals, name, meaning)) { - break loop; + if (!(meaning & 793056) || + !(result.flags & (793056 & ~262144)) || + !ts.isFunctionLike(location) || + lastLocation === location.body) { + break loop; + } + result = undefined; } } switch (location.kind) { - case 228: + case 230: if (!ts.isExternalModule(location)) break; - case 206: - if (result = getSymbol(getSymbolOfNode(location).exports, name, meaning & 8914931)) { - if (result.flags & meaning || !(result.flags & 8388608 && getDeclarationOfAliasSymbol(result).kind === 218)) { - break loop; + case 208: + var moduleExports = getSymbolOfNode(location).exports; + if (location.kind === 230 || + (location.kind === 208 && location.name.kind === 8)) { + if (ts.hasProperty(moduleExports, name) && + moduleExports[name].flags === 8388608 && + ts.getDeclarationOfKind(moduleExports[name], 220)) { + break; } - result = undefined; - } - else if (location.kind === 228 || - (location.kind === 206 && location.name.kind === 8)) { - result = getSymbolOfNode(location).exports["default"]; + result = moduleExports["default"]; var localSymbol = ts.getLocalSymbolForExportDefault(result); if (result && localSymbol && (result.flags & meaning) && localSymbol.name === name) { break loop; } result = undefined; } + if (result = getSymbol(moduleExports, name, meaning & 8914931)) { + break loop; + } break; - case 205: + case 207: if (result = getSymbol(getSymbolOfNode(location).exports, name, meaning & 8)) { break loop; } break; + case 134: case 133: - case 132: - if (location.parent.kind === 202 && !(location.flags & 128)) { + if (location.parent.kind === 204 && !(location.flags & 128)) { var ctor = findConstructorDeclaration(location.parent); if (ctor && ctor.locals) { if (getSymbol(ctor.locals, name, meaning & 107455)) { @@ -8871,8 +9978,8 @@ var ts; } } break; - case 202: - case 203: + case 204: + case 205: if (result = getSymbol(getSymbolOfNode(location).members, name, meaning & 793056)) { if (lastLocation && lastLocation.flags & 128) { error(errorLocation, ts.Diagnostics.Static_members_cannot_reference_class_type_parameters); @@ -8881,47 +9988,51 @@ var ts; break loop; } break; - case 128: + case 129: grandparent = location.parent.parent; - if (grandparent.kind === 202 || grandparent.kind === 203) { + if (grandparent.kind === 204 || grandparent.kind === 205) { if (result = getSymbol(getSymbolOfNode(grandparent).members, name, meaning & 793056)) { error(errorLocation, ts.Diagnostics.A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type); return undefined; } } break; - case 135: - case 134: case 136: + case 135: case 137: case 138: - case 201: - case 164: - if (name === "arguments") { + case 139: + case 203: + case 166: + if (meaning & 3 && name === "arguments") { result = argumentsSymbol; break loop; } break; - case 163: - if (name === "arguments") { + case 165: + if (meaning & 3 && name === "arguments") { result = argumentsSymbol; break loop; } - var functionName = location.name; - if (functionName && name === functionName.text) { - result = location.symbol; - break loop; + if (meaning & 16) { + var functionName = location.name; + if (functionName && name === functionName.text) { + result = location.symbol; + break loop; + } } break; - case 175: - var className = location.name; - if (className && name === className.text) { - result = location.symbol; - break loop; + case 177: + if (meaning & 32) { + var className = location.name; + if (className && name === className.text) { + result = location.symbol; + break loop; + } } break; - case 131: - if (location.parent && location.parent.kind === 130) { + case 132: + if (location.parent && location.parent.kind === 131) { location = location.parent; } if (location.parent && ts.isClassElement(location.parent)) { @@ -8959,14 +10070,14 @@ var ts; ts.Debug.assert(declaration !== undefined, "Block-scoped variable declaration is undefined"); var isUsedBeforeDeclaration = !isDefinedBefore(declaration, errorLocation); if (!isUsedBeforeDeclaration) { - var variableDeclaration = ts.getAncestor(declaration, 199); + var variableDeclaration = ts.getAncestor(declaration, 201); var container = ts.getEnclosingBlockScopeContainer(variableDeclaration); - if (variableDeclaration.parent.parent.kind === 181 || - variableDeclaration.parent.parent.kind === 187) { + if (variableDeclaration.parent.parent.kind === 183 || + variableDeclaration.parent.parent.kind === 189) { isUsedBeforeDeclaration = isSameScopeDescendentOf(errorLocation, variableDeclaration, container); } - else if (variableDeclaration.parent.parent.kind === 189 || - variableDeclaration.parent.parent.kind === 188) { + else if (variableDeclaration.parent.parent.kind === 191 || + variableDeclaration.parent.parent.kind === 190) { var expression = variableDeclaration.parent.parent.expression; isUsedBeforeDeclaration = isSameScopeDescendentOf(errorLocation, expression, container); } @@ -8988,10 +10099,10 @@ var ts; } function getAnyImportSyntax(node) { if (ts.isAliasSymbolDeclaration(node)) { - if (node.kind === 209) { + if (node.kind === 211) { return node; } - while (node && node.kind !== 210) { + while (node && node.kind !== 212) { node = node.parent; } return node; @@ -9001,7 +10112,7 @@ var ts; return ts.forEach(symbol.declarations, function (d) { return ts.isAliasSymbolDeclaration(d) ? d : undefined; }); } function getTargetOfImportEqualsDeclaration(node) { - if (node.moduleReference.kind === 220) { + if (node.moduleReference.kind === 222) { return resolveExternalModuleSymbol(resolveExternalModuleName(node, ts.getExternalModuleImportEqualsDeclarationExpression(node))); } return getSymbolOfPartOfRightHandSideOfImportEquals(node.moduleReference, node); @@ -9063,15 +10174,15 @@ var ts; var moduleSymbol = resolveExternalModuleName(node, node.moduleSpecifier); var targetSymbol = resolveESModuleSymbol(moduleSymbol, node.moduleSpecifier); if (targetSymbol) { - var name_4 = specifier.propertyName || specifier.name; - if (name_4.text) { - var symbolFromModule = getExportOfModule(targetSymbol, name_4.text); - var symbolFromVariable = getPropertyOfVariable(targetSymbol, name_4.text); + var name_8 = specifier.propertyName || specifier.name; + if (name_8.text) { + var symbolFromModule = getExportOfModule(targetSymbol, name_8.text); + var symbolFromVariable = getPropertyOfVariable(targetSymbol, name_8.text); var symbol = symbolFromModule && symbolFromVariable ? combineValueAndTypeSymbols(symbolFromVariable, symbolFromModule) : symbolFromModule || symbolFromVariable; if (!symbol) { - error(name_4, ts.Diagnostics.Module_0_has_no_exported_member_1, getFullyQualifiedName(moduleSymbol), ts.declarationNameToString(name_4)); + error(name_8, ts.Diagnostics.Module_0_has_no_exported_member_1, getFullyQualifiedName(moduleSymbol), ts.declarationNameToString(name_8)); } return symbol; } @@ -9090,17 +10201,17 @@ var ts; } function getTargetOfAliasDeclaration(node) { switch (node.kind) { - case 209: - return getTargetOfImportEqualsDeclaration(node); case 211: + return getTargetOfImportEqualsDeclaration(node); + case 213: return getTargetOfImportClause(node); - case 212: - return getTargetOfNamespaceImport(node); case 214: + return getTargetOfNamespaceImport(node); + case 216: return getTargetOfImportSpecifier(node); - case 218: + case 220: return getTargetOfExportSpecifier(node); - case 215: + case 217: return getTargetOfExportAssignment(node); } } @@ -9130,7 +10241,7 @@ var ts; var symbol = getSymbolOfNode(node); var target = resolveAlias(symbol); if (target) { - var markAlias = (target === unknownSymbol && compilerOptions.separateCompilation) || + var markAlias = (target === unknownSymbol && compilerOptions.isolatedModules) || (target !== unknownSymbol && (target.flags & 107455) && !isConstEnumOrConstEnumOnlyModule(target)); if (markAlias) { markAliasSymbolAsReferenced(symbol); @@ -9142,10 +10253,10 @@ var ts; if (!links.referenced) { links.referenced = true; var node = getDeclarationOfAliasSymbol(symbol); - if (node.kind === 215) { + if (node.kind === 217) { checkExpressionCached(node.expression); } - else if (node.kind === 218) { + else if (node.kind === 220) { checkExpressionCached(node.propertyName || node.name); } else if (ts.isInternalModuleImportEqualsDeclaration(node)) { @@ -9155,17 +10266,17 @@ var ts; } function getSymbolOfPartOfRightHandSideOfImportEquals(entityName, importDeclaration) { if (!importDeclaration) { - importDeclaration = ts.getAncestor(entityName, 209); + importDeclaration = ts.getAncestor(entityName, 211); ts.Debug.assert(importDeclaration !== undefined); } if (entityName.kind === 65 && ts.isRightSideOfQualifiedNameOrPropertyAccess(entityName)) { entityName = entityName.parent; } - if (entityName.kind === 65 || entityName.parent.kind === 127) { + if (entityName.kind === 65 || entityName.parent.kind === 128) { return resolveEntityName(entityName, 1536); } else { - ts.Debug.assert(entityName.parent.kind === 209); + ts.Debug.assert(entityName.parent.kind === 211); return resolveEntityName(entityName, 107455 | 793056 | 1536); } } @@ -9184,9 +10295,9 @@ var ts; return undefined; } } - else if (name.kind === 127 || name.kind === 156) { - var left = name.kind === 127 ? name.left : name.expression; - var right = name.kind === 127 ? name.right : name.name; + else if (name.kind === 128 || name.kind === 158) { + var left = name.kind === 128 ? name.left : name.expression; + var right = name.kind === 128 ? name.right : name.name; var namespace = resolveEntityName(left, 1536); if (!namespace || namespace === unknownSymbol || ts.nodeIsMissing(right)) { return undefined; @@ -9331,7 +10442,7 @@ var ts; var members = node.members; for (var _i = 0; _i < members.length; _i++) { var member = members[_i]; - if (member.kind === 136 && ts.nodeIsPresent(member.body)) { + if (member.kind === 137 && ts.nodeIsPresent(member.body)) { return member; } } @@ -9396,17 +10507,17 @@ var ts; } } switch (location_1.kind) { - case 228: + case 230: if (!ts.isExternalModule(location_1)) { break; } - case 206: + case 208: if (result = callback(getSymbolOfNode(location_1).exports)) { return result; } break; - case 202: - case 203: + case 204: + case 205: if (result = callback(getSymbolOfNode(location_1).members)) { return result; } @@ -9521,8 +10632,8 @@ var ts; } } function hasExternalModuleSymbol(declaration) { - return (declaration.kind === 206 && declaration.name.kind === 8) || - (declaration.kind === 228 && ts.isExternalModule(declaration)); + return (declaration.kind === 208 && declaration.name.kind === 8) || + (declaration.kind === 230 && ts.isExternalModule(declaration)); } function hasVisibleDeclarations(symbol) { var aliasesToMakeVisible; @@ -9554,11 +10665,11 @@ var ts; } function isEntityNameVisible(entityName, enclosingDeclaration) { var meaning; - if (entityName.parent.kind === 145) { + if (entityName.parent.kind === 147) { meaning = 107455 | 1048576; } - else if (entityName.kind === 127 || entityName.kind === 156 || - entityName.parent.kind === 209) { + else if (entityName.kind === 128 || entityName.kind === 158 || + entityName.parent.kind === 211) { meaning = 1536; } else { @@ -9588,6 +10699,13 @@ var ts; ts.releaseStringWriter(writer); return result; } + function signatureToString(signature, enclosingDeclaration, flags) { + var writer = ts.getSingleLineStringWriter(); + getSymbolDisplayBuilder().buildSignatureDisplay(signature, writer, enclosingDeclaration, flags); + var result = writer.string(); + ts.releaseStringWriter(writer); + return result; + } function typeToString(type, enclosingDeclaration, flags) { var writer = ts.getSingleLineStringWriter(); getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); @@ -9602,10 +10720,10 @@ var ts; function getTypeAliasForTypeLiteral(type) { if (type.symbol && type.symbol.flags & 2048) { var node = type.symbol.declarations[0].parent; - while (node.kind === 150) { + while (node.kind === 152) { node = node.parent; } - if (node.kind === 204) { + if (node.kind === 206) { return getSymbolOfNode(node); } } @@ -9673,13 +10791,14 @@ var ts; } return appendParentTypeArgumentsAndSymbolName(symbol); } - function buildTypeDisplay(type, writer, enclosingDeclaration, globalFlags, typeStack) { + function buildTypeDisplay(type, writer, enclosingDeclaration, globalFlags, symbolStack) { var globalFlagsToPass = globalFlags & 16; return writeType(type, globalFlags); function writeType(type, flags) { - if (type.flags & 1048703) { - writer.writeKeyword(!(globalFlags & 16) && - (type.flags & 1) ? "any" : type.intrinsicName); + if (type.flags & 2097279) { + writer.writeKeyword(!(globalFlags & 16) && isTypeAny(type) + ? "any" + : type.intrinsicName); } else if (type.flags & 4096) { writeTypeReference(type, flags); @@ -9719,17 +10838,46 @@ var ts; writeType(types[i], union ? 64 : 0); } } + function writeSymbolTypeReference(symbol, typeArguments, pos, end) { + if (!isReservedMemberName(symbol.name)) { + buildSymbolDisplay(symbol, writer, enclosingDeclaration, 793056); + } + if (pos < end) { + writePunctuation(writer, 24); + writeType(typeArguments[pos++], 0); + while (pos < end) { + writePunctuation(writer, 23); + writeSpace(writer); + writeType(typeArguments[pos++], 0); + } + writePunctuation(writer, 25); + } + } function writeTypeReference(type, flags) { + var typeArguments = type.typeArguments; if (type.target === globalArrayType && !(flags & 1)) { - writeType(type.typeArguments[0], 64); + writeType(typeArguments[0], 64); writePunctuation(writer, 18); writePunctuation(writer, 19); } else { - buildSymbolDisplay(type.target.symbol, writer, enclosingDeclaration, 793056); - writePunctuation(writer, 24); - writeTypeList(type.typeArguments, false); - writePunctuation(writer, 25); + var outerTypeParameters = type.target.outerTypeParameters; + var i = 0; + if (outerTypeParameters) { + var length_1 = outerTypeParameters.length; + while (i < length_1) { + var start = i; + var parent_3 = getParentSymbolOfTypeParameter(outerTypeParameters[i]); + do { + i++; + } while (i < length_1 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent_3); + if (!ts.rangeEquals(outerTypeParameters, typeArguments, start, i)) { + writeSymbolTypeReference(parent_3, typeArguments, start, i); + writePunctuation(writer, 20); + } + } + } + writeSymbolTypeReference(type.symbol, typeArguments, i, typeArguments.length); } } function writeTupleType(type) { @@ -9747,42 +10895,46 @@ var ts; } } function writeAnonymousType(type, flags) { - if (type.symbol && type.symbol.flags & (32 | 384 | 512)) { - writeTypeofSymbol(type, flags); - } - else if (shouldWriteTypeOfFunctionSymbol()) { - writeTypeofSymbol(type, flags); - } - else if (typeStack && ts.contains(typeStack, type)) { - var typeAlias = getTypeAliasForTypeLiteral(type); - if (typeAlias) { - buildSymbolDisplay(typeAlias, writer, enclosingDeclaration, 793056, 0, flags); + var symbol = type.symbol; + if (symbol) { + if (symbol.flags & (32 | 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, 793056, 0, flags); + } + else { + writeKeyword(writer, 112); + } } else { - writeKeyword(writer, 112); + if (!symbolStack) { + symbolStack = []; + } + symbolStack.push(symbol); + writeLiteralType(type, flags); + symbolStack.pop(); } } else { - if (!typeStack) { - typeStack = []; - } - typeStack.push(type); writeLiteralType(type, flags); - typeStack.pop(); } function shouldWriteTypeOfFunctionSymbol() { - if (type.symbol) { - var isStaticMethodSymbol = !!(type.symbol.flags & 8192 && - ts.forEach(type.symbol.declarations, function (declaration) { return declaration.flags & 128; })); - var isNonLocalFunctionSymbol = !!(type.symbol.flags & 16) && - (type.symbol.parent || - ts.forEach(type.symbol.declarations, function (declaration) { - return declaration.parent.kind === 228 || declaration.parent.kind === 207; - })); - if (isStaticMethodSymbol || isNonLocalFunctionSymbol) { - return !!(flags & 2) || - (typeStack && ts.contains(typeStack, type)); - } + var isStaticMethodSymbol = !!(symbol.flags & 8192 && + ts.forEach(symbol.declarations, function (declaration) { return declaration.flags & 128; })); + var isNonLocalFunctionSymbol = !!(symbol.flags & 16) && + (symbol.parent || + ts.forEach(symbol.declarations, function (declaration) { + return declaration.parent.kind === 230 || declaration.parent.kind === 209; + })); + if (isStaticMethodSymbol || isNonLocalFunctionSymbol) { + return !!(flags & 2) || + (ts.contains(symbolStack, symbol)); } } } @@ -9811,7 +10963,7 @@ var ts; if (flags & 64) { writePunctuation(writer, 16); } - buildSignatureDisplay(resolved.callSignatures[0], writer, enclosingDeclaration, globalFlagsToPass | 8, typeStack); + buildSignatureDisplay(resolved.callSignatures[0], writer, enclosingDeclaration, globalFlagsToPass | 8, symbolStack); if (flags & 64) { writePunctuation(writer, 17); } @@ -9823,7 +10975,7 @@ var ts; } writeKeyword(writer, 88); writeSpace(writer); - buildSignatureDisplay(resolved.constructSignatures[0], writer, enclosingDeclaration, globalFlagsToPass | 8, typeStack); + buildSignatureDisplay(resolved.constructSignatures[0], writer, enclosingDeclaration, globalFlagsToPass | 8, symbolStack); if (flags & 64) { writePunctuation(writer, 17); } @@ -9835,7 +10987,7 @@ var ts; writer.increaseIndent(); for (var _i = 0, _a = resolved.callSignatures; _i < _a.length; _i++) { var signature = _a[_i]; - buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, typeStack); + buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, symbolStack); writePunctuation(writer, 22); writer.writeLine(); } @@ -9843,7 +10995,7 @@ var ts; var signature = _c[_b]; writeKeyword(writer, 88); writeSpace(writer); - buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, typeStack); + buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, symbolStack); writePunctuation(writer, 22); writer.writeLine(); } @@ -9852,7 +11004,7 @@ var ts; writer.writeParameter(getIndexerParameterName(resolved, 0, "x")); writePunctuation(writer, 51); writeSpace(writer); - writeKeyword(writer, 122); + writeKeyword(writer, 123); writePunctuation(writer, 19); writePunctuation(writer, 51); writeSpace(writer); @@ -9865,7 +11017,7 @@ var ts; writer.writeParameter(getIndexerParameterName(resolved, 1, "x")); writePunctuation(writer, 51); writeSpace(writer); - writeKeyword(writer, 120); + writeKeyword(writer, 121); writePunctuation(writer, 19); writePunctuation(writer, 51); writeSpace(writer); @@ -9884,7 +11036,7 @@ var ts; if (p.flags & 536870912) { writePunctuation(writer, 50); } - buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, typeStack); + buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, symbolStack); writePunctuation(writer, 22); writer.writeLine(); } @@ -9908,32 +11060,33 @@ var ts; function buildTypeParameterDisplayFromSymbol(symbol, writer, enclosingDeclaraiton, flags) { var targetSymbol = getTargetSymbol(symbol); if (targetSymbol.flags & 32 || targetSymbol.flags & 64) { - buildDisplayForTypeParametersAndDelimiters(getTypeParametersOfClassOrInterface(symbol), writer, enclosingDeclaraiton, flags); + buildDisplayForTypeParametersAndDelimiters(getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol), writer, enclosingDeclaraiton, flags); } } - function buildTypeParameterDisplay(tp, writer, enclosingDeclaration, flags, typeStack) { + function buildTypeParameterDisplay(tp, writer, enclosingDeclaration, flags, symbolStack) { appendSymbolNameOnly(tp.symbol, writer); var constraint = getConstraintOfTypeParameter(tp); if (constraint) { writeSpace(writer); writeKeyword(writer, 79); writeSpace(writer); - buildTypeDisplay(constraint, writer, enclosingDeclaration, flags, typeStack); + buildTypeDisplay(constraint, writer, enclosingDeclaration, flags, symbolStack); } } - function buildParameterDisplay(p, writer, enclosingDeclaration, flags, typeStack) { - if (ts.hasDotDotDotToken(p.valueDeclaration)) { + function buildParameterDisplay(p, writer, enclosingDeclaration, flags, symbolStack) { + var parameterNode = p.valueDeclaration; + if (ts.isRestParameter(parameterNode)) { writePunctuation(writer, 21); } appendSymbolNameOnly(p, writer); - if (ts.hasQuestionToken(p.valueDeclaration) || p.valueDeclaration.initializer) { + if (isOptionalParameter(parameterNode)) { writePunctuation(writer, 50); } writePunctuation(writer, 51); writeSpace(writer); - buildTypeDisplay(getTypeOfSymbol(p), writer, enclosingDeclaration, flags, typeStack); + buildTypeDisplay(getTypeOfSymbol(p), writer, enclosingDeclaration, flags, symbolStack); } - function buildDisplayForTypeParametersAndDelimiters(typeParameters, writer, enclosingDeclaration, flags, typeStack) { + function buildDisplayForTypeParametersAndDelimiters(typeParameters, writer, enclosingDeclaration, flags, symbolStack) { if (typeParameters && typeParameters.length) { writePunctuation(writer, 24); for (var i = 0; i < typeParameters.length; i++) { @@ -9941,12 +11094,12 @@ var ts; writePunctuation(writer, 23); writeSpace(writer); } - buildTypeParameterDisplay(typeParameters[i], writer, enclosingDeclaration, flags, typeStack); + buildTypeParameterDisplay(typeParameters[i], writer, enclosingDeclaration, flags, symbolStack); } writePunctuation(writer, 25); } } - function buildDisplayForTypeArgumentsAndDelimiters(typeParameters, mapper, writer, enclosingDeclaration, flags, typeStack) { + function buildDisplayForTypeArgumentsAndDelimiters(typeParameters, mapper, writer, enclosingDeclaration, flags, symbolStack) { if (typeParameters && typeParameters.length) { writePunctuation(writer, 24); for (var i = 0; i < typeParameters.length; i++) { @@ -9959,18 +11112,18 @@ var ts; writePunctuation(writer, 25); } } - function buildDisplayForParametersAndDelimiters(parameters, writer, enclosingDeclaration, flags, typeStack) { + function buildDisplayForParametersAndDelimiters(parameters, writer, enclosingDeclaration, flags, symbolStack) { writePunctuation(writer, 16); for (var i = 0; i < parameters.length; i++) { if (i > 0) { writePunctuation(writer, 23); writeSpace(writer); } - buildParameterDisplay(parameters[i], writer, enclosingDeclaration, flags, typeStack); + buildParameterDisplay(parameters[i], writer, enclosingDeclaration, flags, symbolStack); } writePunctuation(writer, 17); } - function buildReturnTypeDisplay(signature, writer, enclosingDeclaration, flags, typeStack) { + function buildReturnTypeDisplay(signature, writer, enclosingDeclaration, flags, symbolStack) { if (flags & 8) { writeSpace(writer); writePunctuation(writer, 32); @@ -9979,17 +11132,17 @@ var ts; writePunctuation(writer, 51); } writeSpace(writer); - buildTypeDisplay(getReturnTypeOfSignature(signature), writer, enclosingDeclaration, flags, typeStack); + buildTypeDisplay(getReturnTypeOfSignature(signature), writer, enclosingDeclaration, flags, symbolStack); } - function buildSignatureDisplay(signature, writer, enclosingDeclaration, flags, typeStack) { + function buildSignatureDisplay(signature, writer, enclosingDeclaration, flags, symbolStack) { if (signature.target && (flags & 32)) { buildDisplayForTypeArgumentsAndDelimiters(signature.target.typeParameters, signature.mapper, writer, enclosingDeclaration); } else { - buildDisplayForTypeParametersAndDelimiters(signature.typeParameters, writer, enclosingDeclaration, flags, typeStack); + buildDisplayForTypeParametersAndDelimiters(signature.typeParameters, writer, enclosingDeclaration, flags, symbolStack); } - buildDisplayForParametersAndDelimiters(signature.parameters, writer, enclosingDeclaration, flags, typeStack); - buildReturnTypeDisplay(signature, writer, enclosingDeclaration, flags, typeStack); + buildDisplayForParametersAndDelimiters(signature.parameters, writer, enclosingDeclaration, flags, symbolStack); + buildReturnTypeDisplay(signature, writer, enclosingDeclaration, flags, symbolStack); } return _displayBuilder || (_displayBuilder = { symbolToString: symbolToString, @@ -10009,12 +11162,12 @@ var ts; function isDeclarationVisible(node) { function getContainingExternalModule(node) { for (; node; node = node.parent) { - if (node.kind === 206) { + if (node.kind === 208) { if (node.name.kind === 8) { return node; } } - else if (node.kind === 228) { + else if (node.kind === 230) { return ts.isExternalModule(node) ? node : undefined; } } @@ -10057,58 +11210,58 @@ var ts; } function determineIfDeclarationIsVisible() { switch (node.kind) { - case 153: + case 155: return isDeclarationVisible(node.parent.parent); - case 199: + case 201: if (ts.isBindingPattern(node.name) && !node.name.elements.length) { return false; } - case 206: - case 202: - case 203: + case 208: case 204: - case 201: case 205: - case 209: - var parent_2 = getDeclarationContainer(node); + case 206: + case 203: + case 207: + case 211: + var parent_4 = getDeclarationContainer(node); if (!(ts.getCombinedNodeFlags(node) & 1) && - !(node.kind !== 209 && parent_2.kind !== 228 && ts.isInAmbientContext(parent_2))) { - return isGlobalSourceFile(parent_2); + !(node.kind !== 211 && parent_4.kind !== 230 && ts.isInAmbientContext(parent_4))) { + return isGlobalSourceFile(parent_4); } - return isDeclarationVisible(parent_2); - case 133: - case 132: - case 137: - case 138: - case 135: + return isDeclarationVisible(parent_4); case 134: + case 133: + case 138: + case 139: + case 136: + case 135: if (node.flags & (32 | 64)) { return false; } - case 136: - case 140: - case 139: + case 137: case 141: - case 130: - case 207: - case 143: - case 144: - case 146: + case 140: case 142: - case 147: + case 131: + case 209: + case 145: + case 146: case 148: + case 144: case 149: case 150: + case 151: + case 152: return isDeclarationVisible(node.parent); - case 211: - case 212: + case 213: case 214: + case 216: return false; - case 129: - case 228: + case 130: + case 230: return true; - case 215: + case 217: return false; default: ts.Debug.fail("isDeclarationVisible unknown: SyntaxKind: " + node.kind); @@ -10124,10 +11277,10 @@ var ts; } function collectLinkedAliases(node) { var exportSymbol; - if (node.parent && node.parent.kind === 215) { + if (node.parent && node.parent.kind === 217) { exportSymbol = resolveName(node.parent, node.text, 107455 | 793056 | 1536, ts.Diagnostics.Cannot_find_name_0, node); } - else if (node.parent.kind === 218) { + else if (node.parent.kind === 220) { exportSymbol = getTargetOfExportSpecifier(node.parent); } var result = []; @@ -10173,7 +11326,7 @@ var ts; } function getDeclarationContainer(node) { node = ts.getRootDeclaration(node); - return node.kind === 199 ? node.parent.parent.parent : node.parent; + return node.kind === 201 ? node.parent.parent.parent : node.parent; } function getTypeOfPrototypeProperty(prototype) { var classType = getDeclaredTypeOfSymbol(prototype.parent); @@ -10183,33 +11336,36 @@ var ts; var prop = getPropertyOfType(type, name); return prop ? getTypeOfSymbol(prop) : undefined; } + function isTypeAny(type) { + return type && (type.flags & 1) !== 0; + } function getTypeForBindingElement(declaration) { var pattern = declaration.parent; var parentType = getTypeForVariableLikeDeclaration(pattern.parent); if (parentType === unknownType) { return unknownType; } - if (!parentType || parentType === anyType) { + if (!parentType || isTypeAny(parentType)) { if (declaration.initializer) { return checkExpressionCached(declaration.initializer); } return parentType; } var type; - if (pattern.kind === 151) { - var name_5 = declaration.propertyName || declaration.name; - type = getTypeOfPropertyOfType(parentType, name_5.text) || - isNumericLiteralName(name_5.text) && getIndexTypeOfType(parentType, 1) || + if (pattern.kind === 153) { + var name_9 = declaration.propertyName || declaration.name; + type = getTypeOfPropertyOfType(parentType, name_9.text) || + isNumericLiteralName(name_9.text) && getIndexTypeOfType(parentType, 1) || getIndexTypeOfType(parentType, 0); if (!type) { - error(name_5, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(parentType), ts.declarationNameToString(name_5)); + error(name_9, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(parentType), ts.declarationNameToString(name_9)); return unknownType; } } else { var elementType = checkIteratedTypeOrElementType(parentType, pattern, false); if (!declaration.dotDotDotToken) { - if (elementType.flags & 1) { + if (isTypeAny(elementType)) { return elementType; } var propName = "" + ts.indexOf(pattern.elements, declaration); @@ -10233,10 +11389,10 @@ var ts; return type; } function getTypeForVariableLikeDeclaration(declaration) { - if (declaration.parent.parent.kind === 188) { + if (declaration.parent.parent.kind === 190) { return anyType; } - if (declaration.parent.parent.kind === 189) { + if (declaration.parent.parent.kind === 191) { return checkRightHandSideOfForOf(declaration.parent.parent.expression) || anyType; } if (ts.isBindingPattern(declaration.parent)) { @@ -10245,10 +11401,10 @@ var ts; if (declaration.type) { return getTypeFromTypeNode(declaration.type); } - if (declaration.kind === 130) { + if (declaration.kind === 131) { var func = declaration.parent; - if (func.kind === 138 && !ts.hasDynamicName(func)) { - var getter = ts.getDeclarationOfKind(declaration.parent.symbol, 137); + if (func.kind === 139 && !ts.hasDynamicName(func)) { + var getter = ts.getDeclarationOfKind(declaration.parent.symbol, 138); if (getter) { return getReturnTypeOfSignature(getSignatureFromDeclaration(getter)); } @@ -10261,7 +11417,7 @@ var ts; if (declaration.initializer) { return checkExpressionCached(declaration.initializer); } - if (declaration.kind === 226) { + if (declaration.kind === 228) { return checkIdentifier(declaration.name); } return undefined; @@ -10290,7 +11446,7 @@ var ts; var hasSpreadElement = false; var elementTypes = []; ts.forEach(pattern.elements, function (e) { - elementTypes.push(e.kind === 176 || e.dotDotDotToken ? anyType : getTypeFromBindingElement(e)); + elementTypes.push(e.kind === 178 || e.dotDotDotToken ? anyType : getTypeFromBindingElement(e)); if (e.dotDotDotToken) { hasSpreadElement = true; } @@ -10305,7 +11461,7 @@ var ts; return createTupleType(elementTypes); } function getTypeFromBindingPattern(pattern) { - return pattern.kind === 151 + return pattern.kind === 153 ? getTypeFromObjectBindingPattern(pattern) : getTypeFromArrayBindingPattern(pattern); } @@ -10315,7 +11471,7 @@ var ts; if (reportErrors) { reportErrorsFromWidening(declaration, type); } - return declaration.kind !== 225 ? getWidenedType(type) : type; + return declaration.kind !== 227 ? getWidenedType(type) : type; } if (ts.isBindingPattern(declaration.name)) { return getTypeFromBindingPattern(declaration.name); @@ -10323,7 +11479,7 @@ var ts; type = declaration.dotDotDotToken ? anyArrayType : anyType; if (reportErrors && compilerOptions.noImplicitAny) { var root = ts.getRootDeclaration(declaration); - if (!isPrivateWithinAmbient(root) && !(root.kind === 130 && isPrivateWithinAmbient(root.parent))) { + if (!isPrivateWithinAmbient(root) && !(root.kind === 131 && isPrivateWithinAmbient(root.parent))) { reportImplicitAnyError(declaration, type); } } @@ -10336,10 +11492,10 @@ var ts; return links.type = getTypeOfPrototypeProperty(symbol); } var declaration = symbol.valueDeclaration; - if (declaration.parent.kind === 224) { + if (declaration.parent.kind === 226) { return links.type = anyType; } - if (declaration.kind === 215) { + if (declaration.kind === 217) { return links.type = checkExpression(declaration.expression); } if (!pushTypeResolution(symbol)) { @@ -10354,7 +11510,7 @@ var ts; else { type = anyType; if (compilerOptions.noImplicitAny) { - error(symbol.valueDeclaration, ts.Diagnostics._0_implicitly_has_type_any_because_it_is_does_not_have_a_type_annotation_and_is_referenced_directly_or_indirectly_in_its_own_initializer, symbolToString(symbol)); + 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)); } } } @@ -10367,7 +11523,7 @@ var ts; } function getAnnotatedAccessorType(accessor) { if (accessor) { - if (accessor.kind === 137) { + if (accessor.kind === 138) { return accessor.type && getTypeFromTypeNode(accessor.type); } else { @@ -10383,8 +11539,8 @@ var ts; if (!pushTypeResolution(symbol)) { return unknownType; } - var getter = ts.getDeclarationOfKind(symbol, 137); - var setter = ts.getDeclarationOfKind(symbol, 138); + var getter = ts.getDeclarationOfKind(symbol, 138); + var setter = ts.getDeclarationOfKind(symbol, 139); var type; var getterReturnType = getAnnotatedAccessorType(getter); if (getterReturnType) { @@ -10410,7 +11566,7 @@ var ts; if (!popTypeResolution()) { type = anyType; if (compilerOptions.noImplicitAny) { - var getter_1 = ts.getDeclarationOfKind(symbol, 137); + var getter_1 = ts.getDeclarationOfKind(symbol, 138); 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)); } } @@ -10480,74 +11636,156 @@ var ts; return target === checkBase || ts.forEach(getBaseTypes(target), check); } } - function getTypeParametersOfClassOrInterface(symbol) { - var result; - ts.forEach(symbol.declarations, function (node) { - if (node.kind === 203 || node.kind === 202) { - var declaration = node; - if (declaration.typeParameters && declaration.typeParameters.length) { - ts.forEach(declaration.typeParameters, function (node) { - var tp = getDeclaredTypeOfTypeParameter(getSymbolOfNode(node)); - if (!result) { - result = [tp]; - } - else if (!ts.contains(result, tp)) { - result.push(tp); - } - }); + function appendTypeParameters(typeParameters, declarations) { + for (var _i = 0; _i < declarations.length; _i++) { + var declaration = declarations[_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 === 204 || node.kind === 203 || + node.kind === 165 || node.kind === 136 || + node.kind === 166) { + var declarations = node.typeParameters; + if (declarations) { + return appendTypeParameters(appendOuterTypeParameters(typeParameters, node), declarations); } } - }); + } + } + function getOuterTypeParametersOfClassOrInterface(symbol) { + var kind = symbol.flags & 32 ? 204 : 205; + return appendOuterTypeParameters(undefined, ts.getDeclarationOfKind(symbol, kind)); + } + function getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol) { + var result; + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var node = _a[_i]; + if (node.kind === 205 || node.kind === 204 || node.kind === 206) { + var declaration = node; + if (declaration.typeParameters) { + result = appendTypeParameters(result, declaration.typeParameters); + } + } + } return result; } + function getTypeParametersOfClassOrInterface(symbol) { + return ts.concatenate(getOuterTypeParametersOfClassOrInterface(symbol), getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol)); + } + function isConstructorType(type) { + return type.flags & 48128 && getSignaturesOfType(type, 1).length > 0; + } + function getBaseTypeNodeOfClass(type) { + return ts.getClassExtendsHeritageClauseElement(type.symbol.valueDeclaration); + } + function getConstructorsForTypeArguments(type, typeArgumentNodes) { + var typeArgCount = typeArgumentNodes ? typeArgumentNodes.length : 0; + return ts.filter(getSignaturesOfType(type, 1), function (sig) { return (sig.typeParameters ? sig.typeParameters.length : 0) === typeArgCount; }); + } + function getInstantiatedConstructorsForTypeArguments(type, typeArgumentNodes) { + var signatures = getConstructorsForTypeArguments(type, typeArgumentNodes); + if (typeArgumentNodes) { + var typeArguments = ts.map(typeArgumentNodes, getTypeFromTypeNode); + signatures = ts.map(signatures, function (sig) { return getSignatureInstantiation(sig, typeArguments); }); + } + return signatures; + } + function getBaseConstructorTypeOfClass(type) { + if (!type.resolvedBaseConstructorType) { + var baseTypeNode = getBaseTypeNodeOfClass(type); + if (!baseTypeNode) { + return type.resolvedBaseConstructorType = undefinedType; + } + if (!pushTypeResolution(type)) { + return unknownType; + } + var baseConstructorType = checkExpression(baseTypeNode.expression); + if (baseConstructorType.flags & 48128) { + resolveObjectOrUnionTypeMembers(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 !== unknownType && baseConstructorType !== nullType && !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) { - var typeWithBaseTypes = type; - if (!typeWithBaseTypes.baseTypes) { + if (!type.resolvedBaseTypes) { if (type.symbol.flags & 32) { - resolveBaseTypesOfClass(typeWithBaseTypes); + resolveBaseTypesOfClass(type); } else if (type.symbol.flags & 64) { - resolveBaseTypesOfInterface(typeWithBaseTypes); + resolveBaseTypesOfInterface(type); } else { ts.Debug.fail("type must be class or interface"); } } - return typeWithBaseTypes.baseTypes; + return type.resolvedBaseTypes; } function resolveBaseTypesOfClass(type) { - type.baseTypes = []; - var declaration = ts.getDeclarationOfKind(type.symbol, 202); - var baseTypeNode = ts.getClassExtendsHeritageClauseElement(declaration); - if (baseTypeNode) { - var baseType = getTypeFromTypeNode(baseTypeNode); - if (baseType !== unknownType) { - if (getTargetType(baseType).flags & 1024) { - if (type !== baseType && !hasBaseType(baseType, type)) { - type.baseTypes.push(baseType); - } - else { - error(declaration, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, undefined, 1)); - } - } - else { - error(baseTypeNode, ts.Diagnostics.A_class_may_only_extend_another_class); - } - } + type.resolvedBaseTypes = emptyArray; + var baseContructorType = getBaseConstructorTypeOfClass(type); + if (!(baseContructorType.flags & 48128)) { + return; } + var baseTypeNode = getBaseTypeNodeOfClass(type); + var baseType; + if (baseContructorType.symbol && baseContructorType.symbol.flags & 32) { + baseType = getTypeFromClassOrInterfaceReference(baseTypeNode, baseContructorType.symbol); + } + else { + var constructors = getInstantiatedConstructorsForTypeArguments(baseContructorType, baseTypeNode.typeArguments); + if (!constructors.length) { + error(baseTypeNode.expression, ts.Diagnostics.No_base_constructor_has_the_specified_number_of_type_arguments); + return; + } + baseType = getReturnTypeOfSignature(constructors[0]); + } + if (baseType === unknownType) { + return; + } + if (!(getTargetType(baseType).flags & (1024 | 2048))) { + 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(type.symbol.valueDeclaration, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, undefined, 1)); + return; + } + type.resolvedBaseTypes = [baseType]; } function resolveBaseTypesOfInterface(type) { - type.baseTypes = []; + type.resolvedBaseTypes = []; for (var _i = 0, _a = type.symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (declaration.kind === 203 && ts.getInterfaceBaseTypeNodes(declaration)) { + if (declaration.kind === 205 && 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 (getTargetType(baseType).flags & (1024 | 2048)) { if (type !== baseType && !hasBaseType(baseType, type)) { - type.baseTypes.push(baseType); + type.resolvedBaseTypes.push(baseType); } else { error(declaration, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, undefined, 1)); @@ -10566,10 +11804,13 @@ var ts; if (!links.declaredType) { var kind = symbol.flags & 32 ? 1024 : 2048; var type = links.declaredType = createObjectType(kind, symbol); - var typeParameters = getTypeParametersOfClassOrInterface(symbol); - if (typeParameters) { + var outerTypeParameters = getOuterTypeParametersOfClassOrInterface(symbol); + var localTypeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); + if (outerTypeParameters || localTypeParameters) { type.flags |= 4096; - type.typeParameters = typeParameters; + type.typeParameters = ts.concatenate(outerTypeParameters, localTypeParameters); + type.outerTypeParameters = outerTypeParameters; + type.localTypeParameters = localTypeParameters; type.instantiations = {}; type.instantiations[getTypeListId(type.typeParameters)] = type; type.target = type; @@ -10584,9 +11825,16 @@ var ts; if (!pushTypeResolution(links)) { return unknownType; } - var declaration = ts.getDeclarationOfKind(symbol, 204); + var declaration = ts.getDeclarationOfKind(symbol, 206); var type = getTypeFromTypeNode(declaration.type); - if (!popTypeResolution()) { + if (popTypeResolution()) { + links.typeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); + if (links.typeParameters) { + links.instantiations = {}; + links.instantiations[getTypeListId(links.typeParameters)] = type; + } + } + else { type = unknownType; error(declaration.name, ts.Diagnostics.Type_alias_0_circularly_references_itself, symbolToString(symbol)); } @@ -10608,7 +11856,7 @@ var ts; if (!links.declaredType) { var type = createType(512); type.symbol = symbol; - if (!ts.getDeclarationOfKind(symbol, 129).constraint) { + if (!ts.getDeclarationOfKind(symbol, 130).constraint) { type.constraint = noConstraintType; } links.declaredType = type; @@ -10723,34 +11971,42 @@ var ts; }); setObjectTypeMembers(type, members, callSignatures, constructSignatures, stringIndexType, numberIndexType); } - function createSignature(declaration, typeParameters, parameters, resolvedReturnType, minArgumentCount, hasRestParameter, hasStringLiterals) { + function createSignature(declaration, typeParameters, parameters, resolvedReturnType, typePredicate, minArgumentCount, hasRestParameter, hasStringLiterals) { var sig = new Signature(checker); sig.declaration = declaration; sig.typeParameters = typeParameters; sig.parameters = parameters; sig.resolvedReturnType = resolvedReturnType; + sig.typePredicate = typePredicate; sig.minArgumentCount = minArgumentCount; sig.hasRestParameter = hasRestParameter; sig.hasStringLiterals = hasStringLiterals; return sig; } function cloneSignature(sig) { - return createSignature(sig.declaration, sig.typeParameters, sig.parameters, sig.resolvedReturnType, sig.minArgumentCount, sig.hasRestParameter, sig.hasStringLiterals); + return createSignature(sig.declaration, sig.typeParameters, sig.parameters, sig.resolvedReturnType, sig.typePredicate, sig.minArgumentCount, sig.hasRestParameter, sig.hasStringLiterals); } function getDefaultConstructSignatures(classType) { - var baseTypes = getBaseTypes(classType); - if (baseTypes.length) { - var baseType = baseTypes[0]; - var baseSignatures = getSignaturesOfType(getTypeOfSymbol(baseType.symbol), 1); - return ts.map(baseSignatures, function (baseSignature) { - var signature = baseType.flags & 4096 ? - getSignatureInstantiation(baseSignature, baseType.typeArguments) : cloneSignature(baseSignature); - signature.typeParameters = classType.typeParameters; - signature.resolvedReturnType = classType; - return signature; - }); + if (!getBaseTypes(classType).length) { + return [createSignature(undefined, classType.localTypeParameters, emptyArray, classType, undefined, 0, false, false)]; } - return [createSignature(undefined, classType.typeParameters, emptyArray, classType, 0, false, false)]; + var baseConstructorType = getBaseConstructorTypeOfClass(classType); + var baseSignatures = getSignaturesOfType(baseConstructorType, 1); + var baseTypeNode = getBaseTypeNodeOfClass(classType); + var typeArguments = ts.map(baseTypeNode.typeArguments, getTypeFromTypeNode); + var typeArgCount = typeArguments ? typeArguments.length : 0; + var result = []; + for (var _i = 0; _i < baseSignatures.length; _i++) { + var baseSig = baseSignatures[_i]; + var typeParamCount = baseSig.typeParameters ? baseSig.typeParameters.length : 0; + if (typeParamCount === typeArgCount) { + var sig = typeParamCount ? getSignatureInstantiation(baseSig, typeArguments) : cloneSignature(baseSig); + sig.typeParameters = classType.localTypeParameters; + sig.resolvedReturnType = classType; + result.push(sig); + } + } + return result; } function createTupleTypeMemberSymbols(memberTypes) { var members = {}; @@ -10849,10 +12105,10 @@ var ts; if (!constructSignatures.length) { constructSignatures = getDefaultConstructSignatures(classType); } - var baseTypes = getBaseTypes(classType); - if (baseTypes.length) { + var baseConstructorType = getBaseConstructorTypeOfClass(classType); + if (baseConstructorType.flags & 48128) { members = createSymbolTable(getNamedMembers(members)); - addInheritedMembers(members, getPropertiesOfObjectType(getTypeOfSymbol(baseTypes[0].symbol))); + addInheritedMembers(members, getPropertiesOfObjectType(baseConstructorType)); } } stringIndexType = undefined; @@ -10932,7 +12188,7 @@ var ts; else if (type.flags & 8) { type = globalBooleanType; } - else if (type.flags & 1048576) { + else if (type.flags & 2097152) { type = globalESSymbolType; } return type; @@ -11052,11 +12308,14 @@ var ts; } return result; } + function isOptionalParameter(node) { + return ts.hasQuestionToken(node) || !!node.initializer; + } function getSignatureFromDeclaration(declaration) { var links = getNodeLinks(declaration); if (!links.resolvedSignature) { - var classType = declaration.kind === 136 ? getDeclaredTypeOfClassOrInterface(declaration.parent.symbol) : undefined; - var typeParameters = classType ? classType.typeParameters : + var classType = declaration.kind === 137 ? getDeclaredTypeOfClassOrInterface(declaration.parent.symbol) : undefined; + var typeParameters = classType ? classType.localTypeParameters : declaration.typeParameters ? getTypeParametersFromDeclaration(declaration.typeParameters) : undefined; var parameters = []; var hasStringLiterals = false; @@ -11077,22 +12336,31 @@ var ts; minArgumentCount = declaration.parameters.length; } var returnType; + var typePredicate; if (classType) { returnType = classType; } else if (declaration.type) { returnType = getTypeFromTypeNode(declaration.type); + if (declaration.type.kind === 143) { + var typePredicateNode = declaration.type; + typePredicate = { + parameterName: typePredicateNode.parameterName ? typePredicateNode.parameterName.text : undefined, + parameterIndex: typePredicateNode.parameterName ? getTypePredicateParameterIndex(declaration.parameters, typePredicateNode.parameterName) : undefined, + type: getTypeFromTypeNode(typePredicateNode.type) + }; + } } else { - if (declaration.kind === 137 && !ts.hasDynamicName(declaration)) { - var setter = ts.getDeclarationOfKind(declaration.symbol, 138); + if (declaration.kind === 138 && !ts.hasDynamicName(declaration)) { + var setter = ts.getDeclarationOfKind(declaration.symbol, 139); returnType = getAnnotatedAccessorType(setter); } if (!returnType && ts.nodeIsMissing(declaration.body)) { returnType = anyType; } } - links.resolvedSignature = createSignature(declaration, typeParameters, parameters, returnType, minArgumentCount, ts.hasRestParameters(declaration), hasStringLiterals); + links.resolvedSignature = createSignature(declaration, typeParameters, parameters, returnType, typePredicate, minArgumentCount, ts.hasRestParameter(declaration), hasStringLiterals); } return links.resolvedSignature; } @@ -11103,19 +12371,19 @@ var ts; for (var i = 0, len = symbol.declarations.length; i < len; i++) { var node = symbol.declarations[i]; switch (node.kind) { - case 143: - case 144: - case 201: - case 135: - case 134: + case 145: + case 146: + case 203: case 136: - case 139: + case 135: + case 137: case 140: case 141: - case 137: + case 142: case 138: - case 163: - case 164: + case 139: + case 165: + case 166: if (i > 0 && node.body) { var previous = symbol.declarations[i - 1]; if (node.parent === previous.parent && node.kind === previous.kind && node.pos === previous.end) { @@ -11185,8 +12453,8 @@ var ts; } function getOrCreateTypeFromSignature(signature) { if (!signature.isolatedSignatureType) { - var isConstructor = signature.declaration.kind === 136 || signature.declaration.kind === 140; - var type = createObjectType(32768 | 65536); + var isConstructor = signature.declaration.kind === 137 || signature.declaration.kind === 141; + var type = createObjectType(32768 | 131072); type.members = emptySymbols; type.properties = emptyArray; type.callSignatures = !isConstructor ? [signature] : emptyArray; @@ -11199,7 +12467,7 @@ var ts; return symbol.members["__index"]; } function getIndexDeclarationOfSymbol(symbol, kind) { - var syntaxKind = kind === 1 ? 120 : 122; + var syntaxKind = kind === 1 ? 121 : 123; var indexSymbol = getIndexSymbol(symbol); if (indexSymbol) { var len = indexSymbol.declarations.length; @@ -11229,11 +12497,14 @@ var ts; type.constraint = targetConstraint ? instantiateType(targetConstraint, type.mapper) : noConstraintType; } else { - type.constraint = getTypeFromTypeNode(ts.getDeclarationOfKind(type.symbol, 129).constraint); + type.constraint = getTypeFromTypeNode(ts.getDeclarationOfKind(type.symbol, 130).constraint); } } return type.constraint === noConstraintType ? undefined : type.constraint; } + function getParentSymbolOfTypeParameter(typeParameter) { + return getSymbolOfNode(ts.getDeclarationOfKind(typeParameter.symbol, 130).parent); + } function getTypeListId(types) { switch (types.length) { case 1: @@ -11257,7 +12528,7 @@ var ts; var type = types[_i]; result |= type.flags; } - return result & 786432; + return result & 1572864; } function createTypeReference(target, typeArguments) { var id = getTypeListId(typeArguments); @@ -11279,18 +12550,18 @@ var ts; while (!ts.forEach(typeParameterSymbol.declarations, function (d) { return d.parent === currentNode.parent; })) { currentNode = currentNode.parent; } - links.isIllegalTypeReferenceInConstraint = currentNode.kind === 129; + links.isIllegalTypeReferenceInConstraint = currentNode.kind === 130; return links.isIllegalTypeReferenceInConstraint; } function checkTypeParameterHasIllegalReferencesInConstraint(typeParameter) { var typeParameterSymbol; function check(n) { - if (n.kind === 142 && n.typeName.kind === 65) { + if (n.kind === 144 && n.typeName.kind === 65) { var links = getNodeLinks(n); if (links.isIllegalTypeReferenceInConstraint === undefined) { var symbol = resolveName(typeParameter, n.typeName.text, 793056, undefined, undefined); if (symbol && (symbol.flags & 262144)) { - links.isIllegalTypeReferenceInConstraint = ts.forEach(symbol.declarations, function (d) { return d.parent == typeParameter.parent; }); + links.isIllegalTypeReferenceInConstraint = ts.forEach(symbol.declarations, function (d) { return d.parent === typeParameter.parent; }); } } if (links.isIllegalTypeReferenceInConstraint) { @@ -11304,48 +12575,71 @@ var ts; check(typeParameter.constraint); } } - function getTypeFromTypeReferenceOrExpressionWithTypeArguments(node) { + function getTypeFromClassOrInterfaceReference(node, symbol) { + var type = getDeclaredTypeOfSymbol(symbol); + var typeParameters = type.localTypeParameters; + if (typeParameters) { + if (!node.typeArguments || node.typeArguments.length !== typeParameters.length) { + error(node, ts.Diagnostics.Generic_type_0_requires_1_type_argument_s, typeToString(type, undefined, 1), typeParameters.length); + return unknownType; + } + return createTypeReference(type, ts.concatenate(type.outerTypeParameters, ts.map(node.typeArguments, getTypeFromTypeNode))); + } + if (node.typeArguments) { + error(node, ts.Diagnostics.Type_0_is_not_generic, typeToString(type)); + return unknownType; + } + return type; + } + function getTypeFromTypeAliasReference(node, symbol) { + var type = getDeclaredTypeOfSymbol(symbol); + var links = getSymbolLinks(symbol); + var typeParameters = links.typeParameters; + if (typeParameters) { + if (!node.typeArguments || node.typeArguments.length !== typeParameters.length) { + error(node, ts.Diagnostics.Generic_type_0_requires_1_type_argument_s, symbolToString(symbol), typeParameters.length); + return unknownType; + } + var typeArguments = ts.map(node.typeArguments, getTypeFromTypeNode); + var id = getTypeListId(typeArguments); + return links.instantiations[id] || (links.instantiations[id] = instantiateType(type, createTypeMapper(typeParameters, typeArguments))); + } + if (node.typeArguments) { + error(node, ts.Diagnostics.Type_0_is_not_generic, symbolToString(symbol)); + return unknownType; + } + return type; + } + function getTypeFromNonGenericTypeReference(node, symbol) { + if (symbol.flags & 262144 && isTypeParameterReferenceIllegalInConstraint(node, symbol)) { + return unknownType; + } + if (node.typeArguments) { + error(node, ts.Diagnostics.Type_0_is_not_generic, symbolToString(symbol)); + return unknownType; + } + return getDeclaredTypeOfSymbol(symbol); + } + function getTypeFromTypeReference(node) { var links = getNodeLinks(node); if (!links.resolvedType) { - var type; - if (node.kind !== 177 || ts.isSupportedExpressionWithTypeArguments(node)) { - var typeNameOrExpression = node.kind === 142 - ? node.typeName - : node.expression; - var symbol = resolveEntityName(typeNameOrExpression, 793056); - if (symbol) { - if ((symbol.flags & 262144) && isTypeParameterReferenceIllegalInConstraint(node, symbol)) { - type = unknownType; - } - else { - type = getDeclaredTypeOfSymbol(symbol); - if (type.flags & (1024 | 2048) && type.flags & 4096) { - var typeParameters = type.typeParameters; - if (node.typeArguments && node.typeArguments.length === typeParameters.length) { - type = createTypeReference(type, ts.map(node.typeArguments, getTypeFromTypeNode)); - } - else { - error(node, ts.Diagnostics.Generic_type_0_requires_1_type_argument_s, typeToString(type, undefined, 1), typeParameters.length); - type = undefined; - } - } - else { - if (node.typeArguments) { - error(node, ts.Diagnostics.Type_0_is_not_generic, typeToString(type)); - type = undefined; - } - } - } - } - } - links.resolvedType = type || unknownType; + var typeNameOrExpression = node.kind === 144 ? node.typeName : + ts.isSupportedExpressionWithTypeArguments(node) ? node.expression : + undefined; + var symbol = typeNameOrExpression && resolveEntityName(typeNameOrExpression, 793056) || unknownSymbol; + var type = symbol === unknownSymbol ? unknownType : + symbol.flags & (32 | 64) ? getTypeFromClassOrInterfaceReference(node, symbol) : + symbol.flags & 524288 ? getTypeFromTypeAliasReference(node, symbol) : + getTypeFromNonGenericTypeReference(node, symbol); + links.resolvedSymbol = symbol; + links.resolvedType = type; } return links.resolvedType; } function getTypeFromTypeQueryNode(node) { var links = getNodeLinks(node); if (!links.resolvedType) { - links.resolvedType = getWidenedType(checkExpressionOrQualifiedName(node.exprName)); + links.resolvedType = getWidenedType(checkExpression(node.exprName)); } return links.resolvedType; } @@ -11355,24 +12649,24 @@ var ts; for (var _i = 0; _i < declarations.length; _i++) { var declaration = declarations[_i]; switch (declaration.kind) { - case 202: - case 203: + case 204: case 205: + case 207: return declaration; } } } if (!symbol) { - return emptyObjectType; + return arity ? emptyGenericType : emptyObjectType; } var type = getDeclaredTypeOfSymbol(symbol); if (!(type.flags & 48128)) { error(getTypeDeclaration(symbol), ts.Diagnostics.Global_type_0_must_be_a_class_or_interface_type, symbol.name); - return emptyObjectType; + return arity ? emptyGenericType : emptyObjectType; } if ((type.typeParameters ? type.typeParameters.length : 0) !== arity) { error(getTypeDeclaration(symbol), ts.Diagnostics.Global_type_0_must_have_1_type_parameter_s, symbol.name, arity); - return emptyObjectType; + return arity ? emptyGenericType : emptyObjectType; } return type; } @@ -11392,12 +12686,17 @@ var ts; function getGlobalESSymbolConstructorSymbol() { return globalESSymbolConstructorSymbol || (globalESSymbolConstructorSymbol = getGlobalValueSymbol("Symbol")); } + function createTypeFromGenericGlobalType(genericGlobalType, elementType) { + return genericGlobalType !== emptyGenericType ? createTypeReference(genericGlobalType, [elementType]) : emptyObjectType; + } function createIterableType(elementType) { - return globalIterableType !== emptyObjectType ? createTypeReference(globalIterableType, [elementType]) : emptyObjectType; + return createTypeFromGenericGlobalType(globalIterableType, elementType); + } + function createIterableIteratorType(elementType) { + return createTypeFromGenericGlobalType(globalIterableIteratorType, elementType); } function createArrayType(elementType) { - var arrayType = globalArrayType || getDeclaredTypeOfSymbol(globalArraySymbol); - return arrayType !== emptyObjectType ? createTypeReference(arrayType, [elementType]) : emptyObjectType; + return createTypeFromGenericGlobalType(globalArrayType, elementType); } function getTypeFromArrayTypeNode(node) { var links = getNodeLinks(node); @@ -11452,13 +12751,7 @@ var ts; } return false; } - var removeSubtypesStack = []; function removeSubtypes(types) { - var typeListId = getTypeListId(types); - if (removeSubtypesStack.lastIndexOf(typeListId) >= 0) { - return; - } - removeSubtypesStack.push(typeListId); var i = types.length; while (i > 0) { i--; @@ -11466,12 +12759,11 @@ var ts; types.splice(i, 1); } } - removeSubtypesStack.pop(); } - function containsAnyType(types) { + function containsTypeAny(types) { for (var _i = 0; _i < types.length; _i++) { var type = types[_i]; - if (type.flags & 1) { + if (isTypeAny(type)) { return true; } } @@ -11493,7 +12785,7 @@ var ts; var sortedTypes = []; addTypesToSortedSet(sortedTypes, types); if (noSubtypeReduction) { - if (containsAnyType(sortedTypes)) { + if (containsTypeAny(sortedTypes)) { return anyType; } removeAllButLast(sortedTypes, undefinedType); @@ -11516,7 +12808,14 @@ var ts; } function getReducedTypeOfUnionType(type) { if (!type.reducedType) { - type.reducedType = getUnionType(type.types, false); + type.reducedType = circularType; + var reducedType = getUnionType(type.types, false); + if (type.reducedType === circularType) { + type.reducedType = reducedType; + } + } + else if (type.reducedType === circularType) { + type.reducedType = type; } return type.reducedType; } @@ -11553,38 +12852,40 @@ var ts; switch (node.kind) { case 112: return anyType; - case 122: + case 123: return stringType; - case 120: + case 121: return numberType; case 113: return booleanType; - case 123: + case 124: return esSymbolType; case 99: return voidType; case 8: return getTypeFromStringLiteral(node); - case 142: - return getTypeFromTypeReferenceOrExpressionWithTypeArguments(node); - case 177: - return getTypeFromTypeReferenceOrExpressionWithTypeArguments(node); - case 145: - return getTypeFromTypeQueryNode(node); - case 147: - return getTypeFromArrayTypeNode(node); - case 148: - return getTypeFromTupleTypeNode(node); - case 149: - return getTypeFromUnionTypeNode(node); - case 150: - return getTypeFromTypeNode(node.type); - case 143: case 144: + return getTypeFromTypeReference(node); + case 143: + return booleanType; + case 179: + return getTypeFromTypeReference(node); + case 147: + return getTypeFromTypeQueryNode(node); + case 149: + return getTypeFromArrayTypeNode(node); + case 150: + return getTypeFromTupleTypeNode(node); + case 151: + return getTypeFromUnionTypeNode(node); + case 152: + return getTypeFromTypeNode(node.type); + case 145: case 146: + case 148: return getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node); case 65: - case 127: + case 128: var symbol = getSymbolInfo(node); return symbol && getDeclaredTypeOfSymbol(symbol); default: @@ -11674,11 +12975,19 @@ var ts; } function instantiateSignature(signature, mapper, eraseTypeParameters) { var freshTypeParameters; + var freshTypePredicate; if (signature.typeParameters && !eraseTypeParameters) { freshTypeParameters = instantiateList(signature.typeParameters, mapper, instantiateTypeParameter); mapper = combineTypeMappers(createTypeMapper(signature.typeParameters, freshTypeParameters), mapper); } - var result = createSignature(signature.declaration, freshTypeParameters, instantiateList(signature.parameters, mapper, instantiateSymbol), signature.resolvedReturnType ? instantiateType(signature.resolvedReturnType, mapper) : undefined, signature.minArgumentCount, signature.hasRestParameter, signature.hasStringLiterals); + if (signature.typePredicate) { + freshTypePredicate = { + parameterName: signature.typePredicate.parameterName, + parameterIndex: signature.typePredicate.parameterIndex, + type: instantiateType(signature.typePredicate.type, mapper) + }; + } + var result = createSignature(signature.declaration, freshTypeParameters, instantiateList(signature.parameters, mapper, instantiateSymbol), signature.resolvedReturnType ? instantiateType(signature.resolvedReturnType, mapper) : undefined, freshTypePredicate, signature.minArgumentCount, signature.hasRestParameter, signature.hasStringLiterals); result.target = signature; result.mapper = mapper; return result; @@ -11700,7 +13009,7 @@ var ts; return result; } function instantiateAnonymousType(type, mapper) { - var result = createObjectType(32768, type.symbol); + var result = createObjectType(32768 | 65536, type.symbol); result.properties = instantiateList(getPropertiesOfObjectType(type), mapper, instantiateSymbol); result.members = createSymbolTable(result.properties); result.callSignatures = instantiateList(getSignaturesOfType(type, 0), mapper, instantiateSignature); @@ -11719,7 +13028,7 @@ var ts; return mapper(type); } if (type.flags & 32768) { - return type.symbol && type.symbol.flags & (16 | 8192 | 2048 | 4096) ? + return type.symbol && type.symbol.flags & (16 | 8192 | 32 | 2048 | 4096) ? instantiateAnonymousType(type, mapper) : type; } if (type.flags & 4096) { @@ -11735,27 +13044,27 @@ var ts; return type; } function isContextSensitive(node) { - ts.Debug.assert(node.kind !== 135 || ts.isObjectLiteralMethod(node)); + ts.Debug.assert(node.kind !== 136 || ts.isObjectLiteralMethod(node)); switch (node.kind) { - case 163: - case 164: + case 165: + case 166: return isContextSensitiveFunctionLikeDeclaration(node); - case 155: + case 157: return ts.forEach(node.properties, isContextSensitive); - case 154: + case 156: return ts.forEach(node.elements, isContextSensitive); - case 171: + case 173: return isContextSensitive(node.whenTrue) || isContextSensitive(node.whenFalse); - case 170: + case 172: return node.operatorToken.kind === 49 && (isContextSensitive(node.left) || isContextSensitive(node.right)); - case 225: + case 227: return isContextSensitive(node.initializer); + case 136: case 135: - case 134: return isContextSensitiveFunctionLikeDeclaration(node); - case 162: + case 164: return isContextSensitive(node.expression); } return false; @@ -11763,23 +13072,20 @@ var ts; function isContextSensitiveFunctionLikeDeclaration(node) { return !node.typeParameters && node.parameters.length && !ts.forEach(node.parameters, function (p) { return p.type; }); } - function getTypeWithoutConstructors(type) { + function getTypeWithoutSignatures(type) { if (type.flags & 48128) { var resolved = resolveObjectOrUnionTypeMembers(type); if (resolved.constructSignatures.length) { var result = createObjectType(32768, type.symbol); result.members = resolved.members; result.properties = resolved.properties; - result.callSignatures = resolved.callSignatures; + result.callSignatures = emptyArray; result.constructSignatures = emptyArray; type = result; } } return type; } - var subtypeRelation = {}; - var assignableRelation = {}; - var identityRelation = {}; function isTypeIdenticalTo(source, target) { return checkTypeRelatedTo(source, target, identityRelation, undefined); } @@ -11837,7 +13143,7 @@ var ts; if (source === target) return -1; if (relation !== identityRelation) { - if (target.flags & 1) + if (isTypeAny(target)) return -1; if (source === undefinedType) return -1; @@ -11848,7 +13154,7 @@ var ts; if (source.flags & 256 && target === stringType) return -1; if (relation === assignableRelation) { - if (source.flags & 1) + if (isTypeAny(source)) return -1; if (source === numberType && target.flags & 128) return -1; @@ -12030,9 +13336,9 @@ var ts; maybeStack[depth][id] = 1; depth++; var saveExpandingFlags = expandingFlags; - if (!(expandingFlags & 1) && isDeeplyNestedGeneric(source, sourceStack)) + if (!(expandingFlags & 1) && isDeeplyNestedGeneric(source, sourceStack, depth)) expandingFlags |= 1; - if (!(expandingFlags & 2) && isDeeplyNestedGeneric(target, targetStack)) + if (!(expandingFlags & 2) && isDeeplyNestedGeneric(target, targetStack, depth)) expandingFlags |= 2; var result; if (expandingFlags === 3) { @@ -12065,28 +13371,13 @@ var ts; } return result; } - function isDeeplyNestedGeneric(type, stack) { - if (type.flags & 4096 && depth >= 10) { - var target_1 = type.target; - var count = 0; - for (var i = 0; i < depth; i++) { - var t = stack[i]; - if (t.flags & 4096 && t.target === target_1) { - count++; - if (count >= 10) - return true; - } - } - } - return false; - } function propertiesRelatedTo(source, target, reportErrors) { if (relation === identityRelation) { return propertiesIdenticalTo(source, target); } var result = -1; var properties = getPropertiesOfObjectType(target); - var requireOptionalProperties = relation === subtypeRelation && !(source.flags & 131072); + var requireOptionalProperties = relation === subtypeRelation && !(source.flags & 262144); for (var _i = 0; _i < properties.length; _i++) { var targetProp = properties[_i]; var sourceProp = getPropertyOfType(source, targetProp.name); @@ -12185,11 +13476,11 @@ var ts; var saveErrorInfo = errorInfo; outer: for (var _i = 0; _i < targetSignatures.length; _i++) { var t = targetSignatures[_i]; - if (!t.hasStringLiterals || target.flags & 65536) { + if (!t.hasStringLiterals || target.flags & 131072) { var localErrors = reportErrors; for (var _a = 0; _a < sourceSignatures.length; _a++) { var s = sourceSignatures[_a]; - if (!s.hasStringLiterals || source.flags & 65536) { + if (!s.hasStringLiterals || source.flags & 131072) { var related = signatureRelatedTo(s, t, localErrors); if (related) { result &= related; @@ -12250,6 +13541,33 @@ var ts; } result &= related; } + if (source.typePredicate && target.typePredicate) { + var hasDifferentParameterIndex = source.typePredicate.parameterIndex !== target.typePredicate.parameterIndex; + var hasDifferentTypes; + if (hasDifferentParameterIndex || + (hasDifferentTypes = !isTypeIdenticalTo(source.typePredicate.type, target.typePredicate.type))) { + if (reportErrors) { + var sourceParamText = source.typePredicate.parameterName; + var targetParamText = target.typePredicate.parameterName; + var sourceTypeText = typeToString(source.typePredicate.type); + var targetTypeText = typeToString(target.typePredicate.type); + if (hasDifferentParameterIndex) { + reportError(ts.Diagnostics.Parameter_0_is_not_in_the_same_position_as_parameter_1, sourceParamText, targetParamText); + } + else if (hasDifferentTypes) { + reportError(ts.Diagnostics.Type_0_is_not_assignable_to_type_1, sourceTypeText, targetTypeText); + } + reportError(ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1, sourceParamText + " is " + sourceTypeText, targetParamText + " is " + targetTypeText); + } + return 0; + } + } + else if (!source.typePredicate && target.typePredicate) { + if (reportErrors) { + reportError(ts.Diagnostics.Signature_0_must_have_a_type_predicate, signatureToString(source)); + } + return 0; + } var t = getReturnTypeOfSignature(target); if (t === voidType) return result; @@ -12339,6 +13657,21 @@ var ts; return 0; } } + function isDeeplyNestedGeneric(type, stack, depth) { + if (type.flags & (4096 | 65536) && depth >= 5) { + var symbol = type.symbol; + var count = 0; + for (var i = 0; i < depth; i++) { + var t = stack[i]; + if (t.flags & (4096 | 65536) && t.symbol === symbol) { + count++; + if (count >= 5) + return true; + } + } + } + return false; + } function isPropertyIdenticalTo(sourceProp, targetProp) { return compareProperties(sourceProp, targetProp, compareTypes) !== 0; } @@ -12481,11 +13814,11 @@ var ts; return createAnonymousType(type.symbol, members, emptyArray, emptyArray, stringIndexType, numberIndexType); } function getWidenedType(type) { - if (type.flags & 786432) { + if (type.flags & 1572864) { if (type.flags & (32 | 64)) { return anyType; } - if (type.flags & 131072) { + if (type.flags & 262144) { return getWidenedTypeOfObjectLiteral(type); } if (type.flags & 16384) { @@ -12510,11 +13843,11 @@ var ts; if (isArrayType(type)) { return reportWideningErrorsInType(type.typeArguments[0]); } - if (type.flags & 131072) { + if (type.flags & 262144) { var errorReported = false; ts.forEach(getPropertiesOfObjectType(type), function (p) { var t = getTypeOfSymbol(p); - if (t.flags & 262144) { + if (t.flags & 524288) { if (!reportWideningErrorsInType(t)) { error(p.valueDeclaration, ts.Diagnostics.Object_literal_s_property_0_implicitly_has_an_1_type, p.name, typeToString(getWidenedType(t))); } @@ -12529,22 +13862,22 @@ var ts; var typeAsString = typeToString(getWidenedType(type)); var diagnostic; switch (declaration.kind) { + case 134: case 133: - case 132: diagnostic = ts.Diagnostics.Member_0_implicitly_has_an_1_type; break; - case 130: + case 131: diagnostic = declaration.dotDotDotToken ? ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type : ts.Diagnostics.Parameter_0_implicitly_has_an_1_type; break; - case 201: + case 203: + case 136: case 135: - case 134: - case 137: case 138: - case 163: - case 164: + case 139: + case 165: + case 166: if (!declaration.name) { error(declaration, ts.Diagnostics.Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeAsString); return; @@ -12557,7 +13890,7 @@ var ts; error(declaration, diagnostic, ts.declarationNameToString(declaration.name), typeAsString); } function reportErrorsFromWidening(declaration, type) { - if (produceDiagnostics && compilerOptions.noImplicitAny && type.flags & 262144) { + if (produceDiagnostics && compilerOptions.noImplicitAny && type.flags & 524288) { if (!reportWideningErrorsInType(type)) { reportImplicitAnyError(declaration, type); } @@ -12616,20 +13949,6 @@ var ts; } return false; } - function isWithinDepthLimit(type, stack) { - if (depth >= 5) { - var target_2 = type.target; - var count = 0; - for (var i = 0; i < depth; i++) { - var t = stack[i]; - if (t.flags & 4096 && t.target === target_2) { - count++; - } - } - return count < 5; - } - return true; - } function inferFromTypes(source, target) { if (source === anyFunctionType) { return; @@ -12687,22 +14006,26 @@ var ts; } else if (source.flags & 48128 && (target.flags & (4096 | 8192) || (target.flags & 32768) && target.symbol && target.symbol.flags & (8192 | 2048))) { - if (!isInProcess(source, target) && isWithinDepthLimit(source, sourceStack) && isWithinDepthLimit(target, targetStack)) { - if (depth === 0) { - sourceStack = []; - targetStack = []; - } - sourceStack[depth] = source; - targetStack[depth] = target; - depth++; - inferFromProperties(source, target); - inferFromSignatures(source, target, 0); - inferFromSignatures(source, target, 1); - inferFromIndexTypes(source, target, 0, 0); - inferFromIndexTypes(source, target, 1, 1); - inferFromIndexTypes(source, target, 0, 1); - depth--; + if (isInProcess(source, target)) { + return; } + if (isDeeplyNestedGeneric(source, sourceStack, depth) && isDeeplyNestedGeneric(target, targetStack, depth)) { + return; + } + if (depth === 0) { + sourceStack = []; + targetStack = []; + } + sourceStack[depth] = source; + targetStack[depth] = target; + depth++; + inferFromProperties(source, target); + inferFromSignatures(source, target, 0); + inferFromSignatures(source, target, 1); + inferFromIndexTypes(source, target, 0, 0); + inferFromIndexTypes(source, target, 1, 1); + inferFromIndexTypes(source, target, 0, 1); + depth--; } } function inferFromProperties(source, target) { @@ -12727,7 +14050,14 @@ var ts; } function inferFromSignature(source, target) { forEachMatchingParameterType(source, target, inferFromTypes); - inferFromTypes(getReturnTypeOfSignature(source), getReturnTypeOfSignature(target)); + if (source.typePredicate && target.typePredicate) { + if (target.typePredicate.parameterIndex === source.typePredicate.parameterIndex) { + inferFromTypes(source.typePredicate.type, target.typePredicate.type); + } + } + else { + inferFromTypes(getReturnTypeOfSignature(source), getReturnTypeOfSignature(target)); + } } function inferFromIndexTypes(source, target, sourceKind, targetKind) { var targetIndexType = getIndexTypeOfType(target, targetKind); @@ -12787,10 +14117,10 @@ var ts; function isInTypeQuery(node) { while (node) { switch (node.kind) { - case 145: + case 147: return true; case 65: - case 127: + case 128: node = node.parent; continue; default: @@ -12832,7 +14162,7 @@ var ts; function isAssignedInBinaryExpression(node) { if (node.operatorToken.kind >= 53 && node.operatorToken.kind <= 64) { var n = node.left; - while (n.kind === 162) { + while (n.kind === 164) { n = n.expression; } if (n.kind === 65 && getResolvedSymbol(n) === symbol) { @@ -12849,46 +14179,46 @@ var ts; } function isAssignedIn(node) { switch (node.kind) { - case 170: + case 172: return isAssignedInBinaryExpression(node); - case 199: - case 153: - return isAssignedInVariableDeclaration(node); - case 151: - case 152: - case 154: + case 201: case 155: + return isAssignedInVariableDeclaration(node); + case 153: + case 154: case 156: case 157: case 158: case 159: + case 160: case 161: - case 162: - case 168: - case 165: - case 166: + case 163: + case 164: + case 170: case 167: + case 168: case 169: case 171: - case 174: - case 180: - case 181: + case 173: + case 176: + case 182: case 183: - case 184: case 185: case 186: case 187: case 188: case 189: - case 192: - case 193: + case 190: + case 191: case 194: - case 221: - case 222: case 195: case 196: - case 197: + case 223: case 224: + case 197: + case 198: + case 199: + case 226: return ts.forEachChild(node, isAssignedIn); } return false; @@ -12896,10 +14226,10 @@ var ts; } function resolveLocation(node) { var containerNodes = []; - for (var parent_3 = node.parent; parent_3; parent_3 = parent_3.parent) { - if ((ts.isExpression(parent_3) || ts.isObjectLiteralMethod(node)) && - isContextSensitive(parent_3)) { - containerNodes.unshift(parent_3); + for (var parent_5 = node.parent; parent_5; parent_5 = parent_5.parent) { + if ((ts.isExpression(parent_5) || ts.isObjectLiteralMethod(node)) && + isContextSensitive(parent_5)) { + containerNodes.unshift(parent_5); } } ts.forEach(containerNodes, function (node) { getTypeOfNode(node); }); @@ -12918,53 +14248,55 @@ var ts; } function getNarrowedTypeOfSymbol(symbol, node) { var type = getTypeOfSymbol(symbol); - if (node && symbol.flags & 3 && type.flags & (1 | 48128 | 16384 | 512)) { - loop: while (node.parent) { - var child = node; - node = node.parent; - var narrowedType = type; - switch (node.kind) { - case 184: - if (child !== node.expression) { - narrowedType = narrowType(type, node.expression, child === node.thenStatement); - } - break; - case 171: - if (child !== node.condition) { - narrowedType = narrowType(type, node.condition, child === node.whenTrue); - } - break; - case 170: - if (child === node.right) { - if (node.operatorToken.kind === 48) { - narrowedType = narrowType(type, node.left, true); + if (node && symbol.flags & 3) { + if (isTypeAny(type) || type.flags & (48128 | 16384 | 512)) { + loop: while (node.parent) { + var child = node; + node = node.parent; + var narrowedType = type; + switch (node.kind) { + case 186: + if (child !== node.expression) { + narrowedType = narrowType(type, node.expression, child === node.thenStatement); } - else if (node.operatorToken.kind === 49) { - narrowedType = narrowType(type, node.left, false); + break; + case 173: + if (child !== node.condition) { + narrowedType = narrowType(type, node.condition, child === node.whenTrue); } - } - break; - case 228: - case 206: - case 201: - case 135: - case 134: - case 137: - case 138: - case 136: - break loop; - } - if (narrowedType !== type) { - if (isVariableAssignedWithin(symbol, node)) { - break; + break; + case 172: + if (child === node.right) { + if (node.operatorToken.kind === 48) { + narrowedType = narrowType(type, node.left, true); + } + else if (node.operatorToken.kind === 49) { + narrowedType = narrowType(type, node.left, false); + } + } + break; + case 230: + case 208: + case 203: + case 136: + case 135: + case 138: + case 139: + case 137: + break loop; + } + if (narrowedType !== type) { + if (isVariableAssignedWithin(symbol, node)) { + break; + } + type = narrowedType; } - type = narrowedType; } } } return type; function narrowTypeByEquality(type, expr, assumeTrue) { - if (expr.left.kind !== 166 || expr.right.kind !== 8) { + if (expr.left.kind !== 168 || expr.right.kind !== 8) { return type; } var left = expr.left; @@ -12978,7 +14310,7 @@ var ts; } if (assumeTrue) { if (!typeInfo) { - return removeTypesFromUnionType(type, 258 | 132 | 8 | 1048576, true, false); + return removeTypesFromUnionType(type, 258 | 132 | 8 | 2097152, true, false); } if (isTypeSubtypeOf(typeInfo.type, type)) { return typeInfo.type; @@ -13015,7 +14347,7 @@ var ts; } } function narrowTypeByInstanceof(type, expr, assumeTrue) { - if (type.flags & 1 || !assumeTrue || expr.left.kind !== 65 || getResolvedSymbol(expr.left) !== symbol) { + if (isTypeAny(type) || !assumeTrue || expr.left.kind !== 65 || getResolvedSymbol(expr.left) !== symbol) { return type; } var rightType = checkExpression(expr.right); @@ -13026,7 +14358,7 @@ var ts; var prototypeProperty = getPropertyOfType(rightType, "prototype"); if (prototypeProperty) { var prototypePropertyType = getTypeOfSymbol(prototypeProperty); - if (prototypePropertyType !== anyType) { + if (!isTypeAny(prototypePropertyType)) { targetType = prototypePropertyType; } } @@ -13043,20 +14375,44 @@ var ts; } } if (targetType) { - if (isTypeSubtypeOf(targetType, type)) { - return targetType; - } - if (type.flags & 16384) { - return getUnionType(ts.filter(type.types, function (t) { return isTypeSubtypeOf(t, targetType); })); + return getNarrowedType(type, targetType); + } + return type; + } + function getNarrowedType(originalType, narrowedTypeCandidate) { + if (isTypeSubtypeOf(narrowedTypeCandidate, originalType)) { + return narrowedTypeCandidate; + } + if (originalType.flags & 16384) { + return getUnionType(ts.filter(originalType.types, function (t) { return isTypeSubtypeOf(t, narrowedTypeCandidate); })); + } + return originalType; + } + function narrowTypeByTypePredicate(type, expr, assumeTrue) { + if (type.flags & 1) { + return type; + } + var signature = getResolvedSignature(expr); + if (signature.typePredicate && + expr.arguments[signature.typePredicate.parameterIndex] && + getSymbolAtLocation(expr.arguments[signature.typePredicate.parameterIndex]) === symbol) { + if (!assumeTrue) { + if (type.flags & 16384) { + return getUnionType(ts.filter(type.types, function (t) { return !isTypeSubtypeOf(t, signature.typePredicate.type); })); + } + return type; } + return getNarrowedType(type, signature.typePredicate.type); } return type; } function narrowType(type, expr, assumeTrue) { switch (expr.kind) { - case 162: + case 160: + return narrowTypeByTypePredicate(type, expr, assumeTrue); + case 164: return narrowType(type, expr.expression, assumeTrue); - case 170: + case 172: var operator = expr.operatorToken.kind; if (operator === 30 || operator === 31) { return narrowTypeByEquality(type, expr, assumeTrue); @@ -13071,7 +14427,7 @@ var ts; return narrowTypeByInstanceof(type, expr, assumeTrue); } break; - case 168: + case 170: if (expr.operator === 46) { return narrowType(type, expr.operand, !assumeTrue); } @@ -13082,7 +14438,7 @@ var ts; } function checkIdentifier(node) { var symbol = getResolvedSymbol(node); - if (symbol === argumentsSymbol && ts.getContainingFunction(node).kind === 164 && languageVersion < 2) { + if (symbol === argumentsSymbol && ts.getContainingFunction(node).kind === 166 && languageVersion < 2) { error(node, ts.Diagnostics.The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_standard_function_expression); } if (symbol.flags & 8388608 && !isInTypeQuery(node) && !isConstEnumOrConstEnumOnlyModule(resolveAlias(symbol))) { @@ -13106,15 +14462,15 @@ var ts; function checkBlockScopedBindingCapturedInLoop(node, symbol) { if (languageVersion >= 2 || (symbol.flags & 2) === 0 || - symbol.valueDeclaration.parent.kind === 224) { + symbol.valueDeclaration.parent.kind === 226) { return; } var container = symbol.valueDeclaration; - while (container.kind !== 200) { + while (container.kind !== 202) { container = container.parent; } container = container.parent; - if (container.kind === 181) { + if (container.kind === 183) { container = container.parent; } var inFunction = isInsideFunction(node.parent, container); @@ -13131,9 +14487,9 @@ var ts; } } function captureLexicalThis(node, container) { - var classNode = container.parent && container.parent.kind === 202 ? container.parent : undefined; + var classNode = container.parent && container.parent.kind === 204 ? container.parent : undefined; getNodeLinks(node).flags |= 2; - if (container.kind === 133 || container.kind === 136) { + if (container.kind === 134 || container.kind === 137) { getNodeLinks(classNode).flags |= 4; } else { @@ -13143,36 +14499,36 @@ var ts; function checkThisExpression(node) { var container = ts.getThisContainer(node, true); var needToCaptureLexicalThis = false; - if (container.kind === 164) { + if (container.kind === 166) { container = ts.getThisContainer(container, false); needToCaptureLexicalThis = (languageVersion < 2); } switch (container.kind) { - case 206: + case 208: error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_module_or_namespace_body); break; - case 205: + case 207: error(node, ts.Diagnostics.this_cannot_be_referenced_in_current_location); break; - case 136: + case 137: if (isInConstructorArgumentInitializer(node, container)) { error(node, ts.Diagnostics.this_cannot_be_referenced_in_constructor_arguments); } break; + case 134: case 133: - case 132: if (container.flags & 128) { error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_static_property_initializer); } break; - case 128: + case 129: error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_computed_property_name); break; } if (needToCaptureLexicalThis) { captureLexicalThis(node, container); } - var classNode = container.parent && container.parent.kind === 202 ? container.parent : undefined; + var classNode = container.parent && container.parent.kind === 204 ? container.parent : undefined; if (classNode) { var symbol = getSymbolOfNode(classNode); return container.flags & 128 ? getTypeOfSymbol(symbol) : getDeclaredTypeOfSymbol(symbol); @@ -13181,23 +14537,21 @@ var ts; } function isInConstructorArgumentInitializer(node, constructorDecl) { for (var n = node; n && n !== constructorDecl; n = n.parent) { - if (n.kind === 130) { + if (n.kind === 131) { return true; } } return false; } function checkSuperExpression(node) { - var isCallExpression = node.parent.kind === 158 && node.parent.expression === node; - var enclosingClass = ts.getAncestor(node, 202); - var baseClass; - if (enclosingClass && ts.getClassExtendsHeritageClauseElement(enclosingClass)) { - var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(enclosingClass)); - var baseTypes = getBaseTypes(classType); - baseClass = baseTypes.length && baseTypes[0]; - } - if (!baseClass) { - error(node, ts.Diagnostics.super_can_only_be_referenced_in_a_derived_class); + var isCallExpression = node.parent.kind === 160 && node.parent.expression === node; + var classDeclaration = ts.getAncestor(node, 204); + var classType = classDeclaration && getDeclaredTypeOfSymbol(getSymbolOfNode(classDeclaration)); + var baseClassType = classType && getBaseTypes(classType)[0]; + if (!baseClassType) { + if (!classDeclaration || !ts.getClassExtendsHeritageClauseElement(classDeclaration)) { + error(node, ts.Diagnostics.super_can_only_be_referenced_in_a_derived_class); + } return unknownType; } var container = ts.getSuperContainer(node, true); @@ -13205,31 +14559,31 @@ var ts; var canUseSuperExpression = false; var needToCaptureLexicalThis; if (isCallExpression) { - canUseSuperExpression = container.kind === 136; + canUseSuperExpression = container.kind === 137; } else { needToCaptureLexicalThis = false; - while (container && container.kind === 164) { + while (container && container.kind === 166) { container = ts.getSuperContainer(container, true); needToCaptureLexicalThis = languageVersion < 2; } - if (container && container.parent && container.parent.kind === 202) { + if (container && container.parent && container.parent.kind === 204) { if (container.flags & 128) { canUseSuperExpression = - container.kind === 135 || - container.kind === 134 || - container.kind === 137 || - container.kind === 138; + container.kind === 136 || + container.kind === 135 || + container.kind === 138 || + container.kind === 139; } else { canUseSuperExpression = - container.kind === 135 || - container.kind === 134 || - container.kind === 137 || + container.kind === 136 || + container.kind === 135 || container.kind === 138 || + container.kind === 139 || + container.kind === 134 || container.kind === 133 || - container.kind === 132 || - container.kind === 136; + container.kind === 137; } } } @@ -13237,13 +14591,13 @@ var ts; var returnType; if ((container.flags & 128) || isCallExpression) { getNodeLinks(node).flags |= 32; - returnType = getTypeOfSymbol(baseClass.symbol); + returnType = getBaseConstructorTypeOfClass(classType); } else { getNodeLinks(node).flags |= 16; - returnType = baseClass; + returnType = baseClassType; } - if (container.kind === 136 && isInConstructorArgumentInitializer(node, container)) { + if (container.kind === 137 && isInConstructorArgumentInitializer(node, container)) { error(node, ts.Diagnostics.super_cannot_be_referenced_in_constructor_arguments); returnType = unknownType; } @@ -13253,7 +14607,7 @@ var ts; return returnType; } } - if (container && container.kind === 128) { + if (container && container.kind === 129) { error(node, ts.Diagnostics.super_cannot_be_referenced_in_a_computed_property_name); } else if (isCallExpression) { @@ -13270,7 +14624,7 @@ var ts; if (isContextSensitive(func)) { var contextualSignature = getContextualSignature(func); if (contextualSignature) { - var funcHasRestParameters = ts.hasRestParameters(func); + var funcHasRestParameters = ts.hasRestParameter(func); var len = func.parameters.length - (funcHasRestParameters ? 1 : 0); var indexOfParameter = ts.indexOf(func.parameters, parameter); if (indexOfParameter < len) { @@ -13291,7 +14645,7 @@ var ts; if (declaration.type) { return getTypeFromTypeNode(declaration.type); } - if (declaration.kind === 130) { + if (declaration.kind === 131) { var type = getContextuallyTypedParameterType(declaration); if (type) { return type; @@ -13304,18 +14658,36 @@ var ts; return undefined; } function getContextualTypeForReturnExpression(node) { + var func = ts.getContainingFunction(node); + if (func && !func.asteriskToken) { + return getContextualReturnType(func); + } + return undefined; + } + function getContextualTypeForYieldOperand(node) { var func = ts.getContainingFunction(node); if (func) { - if (func.type || func.kind === 136 || func.kind === 137 && getSetAccessorTypeAnnotationNode(ts.getDeclarationOfKind(func.symbol, 138))) { - return getReturnTypeOfSignature(getSignatureFromDeclaration(func)); - } - var signature = getContextualSignatureForFunctionLikeDeclaration(func); - if (signature) { - return getReturnTypeOfSignature(signature); + var contextualReturnType = getContextualReturnType(func); + if (contextualReturnType) { + return node.asteriskToken + ? contextualReturnType + : getElementTypeOfIterableIterator(contextualReturnType); } } return undefined; } + function getContextualReturnType(functionDecl) { + if (functionDecl.type || + functionDecl.kind === 137 || + functionDecl.kind === 138 && getSetAccessorTypeAnnotationNode(ts.getDeclarationOfKind(functionDecl.symbol, 139))) { + 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); @@ -13326,7 +14698,7 @@ var ts; return undefined; } function getContextualTypeForSubstitutionExpression(template, substitutionExpression) { - if (template.parent.kind === 160) { + if (template.parent.kind === 162) { return getContextualTypeForArgument(template.parent, substitutionExpression); } return undefined; @@ -13417,7 +14789,7 @@ var ts; var index = ts.indexOf(arrayLiteral.elements, node); return getTypeOfPropertyOfContextualType(type, "" + index) || getIndexTypeOfContextualType(type, 1) - || (languageVersion >= 2 ? checkIteratedType(type, undefined) : undefined); + || (languageVersion >= 2 ? getElementTypeOfIterable(type, undefined) : undefined); } return undefined; } @@ -13434,32 +14806,34 @@ var ts; } var parent = node.parent; switch (parent.kind) { - case 199: - case 130: + case 201: + case 131: + case 134: case 133: - case 132: - case 153: + case 155: return getContextualTypeForInitializerExpression(node); - case 164: - case 192: + case 166: + case 194: return getContextualTypeForReturnExpression(node); - case 158: - case 159: - return getContextualTypeForArgument(parent, node); + case 175: + return getContextualTypeForYieldOperand(parent); + case 160: case 161: + return getContextualTypeForArgument(parent, node); + case 163: return getTypeFromTypeNode(parent.type); - case 170: + case 172: return getContextualTypeForBinaryOperand(node); - case 225: + case 227: return getContextualTypeForObjectLiteralElement(parent); - case 154: + case 156: return getContextualTypeForElementExpression(node); - case 171: + case 173: return getContextualTypeForConditionalOperand(node); - case 178: - ts.Debug.assert(parent.parent.kind === 172); + case 180: + ts.Debug.assert(parent.parent.kind === 174); return getContextualTypeForSubstitutionExpression(parent.parent, node); - case 162: + case 164: return getContextualType(parent); } return undefined; @@ -13474,13 +14848,15 @@ var ts; } } function isFunctionExpressionOrArrowFunction(node) { - return node.kind === 163 || node.kind === 164; + return node.kind === 165 || node.kind === 166; } function getContextualSignatureForFunctionLikeDeclaration(node) { - return isFunctionExpressionOrArrowFunction(node) ? getContextualSignature(node) : undefined; + return isFunctionExpressionOrArrowFunction(node) || ts.isObjectLiteralMethod(node) + ? getContextualSignature(node) + : undefined; } function getContextualSignature(node) { - ts.Debug.assert(node.kind !== 135 || ts.isObjectLiteralMethod(node)); + ts.Debug.assert(node.kind !== 136 || ts.isObjectLiteralMethod(node)); var type = ts.isObjectLiteralMethod(node) ? getContextualTypeForObjectLiteralMethod(node) : getContextualType(node); @@ -13524,13 +14900,13 @@ var ts; } function isAssignmentTarget(node) { var parent = node.parent; - if (parent.kind === 170 && parent.operatorToken.kind === 53 && parent.left === node) { + if (parent.kind === 172 && parent.operatorToken.kind === 53 && parent.left === node) { return true; } - if (parent.kind === 225) { + if (parent.kind === 227) { return isAssignmentTarget(parent.parent); } - if (parent.kind === 154) { + if (parent.kind === 156) { return isAssignmentTarget(parent); } return false; @@ -13549,10 +14925,10 @@ var ts; var inDestructuringPattern = isAssignmentTarget(node); for (var _i = 0; _i < elements.length; _i++) { var e = elements[_i]; - if (inDestructuringPattern && e.kind === 174) { + if (inDestructuringPattern && e.kind === 176) { var restArrayType = checkExpression(e.expression, contextualMapper); var restElementType = getIndexTypeOfType(restArrayType, 1) || - (languageVersion >= 2 ? checkIteratedType(restArrayType, undefined) : undefined); + (languageVersion >= 2 ? getElementTypeOfIterable(restArrayType, undefined) : undefined); if (restElementType) { elementTypes.push(restElementType); } @@ -13561,7 +14937,7 @@ var ts; var type = checkExpression(e, contextualMapper); elementTypes.push(type); } - hasSpreadElement = hasSpreadElement || e.kind === 174; + hasSpreadElement = hasSpreadElement || e.kind === 176; } if (!hasSpreadElement) { var contextualType = getContextualType(node); @@ -13572,10 +14948,13 @@ var ts; return createArrayType(getUnionType(elementTypes)); } function isNumericName(name) { - return name.kind === 128 ? isNumericComputedName(name) : isNumericLiteralName(name.text); + return name.kind === 129 ? isNumericComputedName(name) : isNumericLiteralName(name.text); } function isNumericComputedName(name) { - return allConstituentTypesHaveKind(checkComputedPropertyName(name), 1 | 132); + return isTypeAnyOrAllConstituentTypesHaveKind(checkComputedPropertyName(name), 132); + } + function isTypeAnyOrAllConstituentTypesHaveKind(type, kind) { + return isTypeAny(type) || allConstituentTypesHaveKind(type, kind); } function isNumericLiteralName(name) { return (+name).toString() === name; @@ -13584,7 +14963,7 @@ var ts; var links = getNodeLinks(node.expression); if (!links.resolvedType) { links.resolvedType = checkExpression(node.expression); - if (!allConstituentTypesHaveKind(links.resolvedType, 1 | 132 | 258 | 1048576)) { + if (!isTypeAnyOrAllConstituentTypesHaveKind(links.resolvedType, 132 | 258 | 2097152)) { error(node, ts.Diagnostics.A_computed_property_name_must_be_of_type_string_number_symbol_or_any); } else { @@ -13602,18 +14981,18 @@ var ts; for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { var memberDecl = _a[_i]; var member = memberDecl.symbol; - if (memberDecl.kind === 225 || - memberDecl.kind === 226 || + if (memberDecl.kind === 227 || + memberDecl.kind === 228 || ts.isObjectLiteralMethod(memberDecl)) { var type = void 0; - if (memberDecl.kind === 225) { + if (memberDecl.kind === 227) { type = checkPropertyAssignment(memberDecl, contextualMapper); } - else if (memberDecl.kind === 135) { + else if (memberDecl.kind === 136) { type = checkObjectLiteralMethod(memberDecl, contextualMapper); } else { - ts.Debug.assert(memberDecl.kind === 226); + ts.Debug.assert(memberDecl.kind === 228); type = checkExpression(memberDecl.name, contextualMapper); } typeFlags |= type.flags; @@ -13628,7 +15007,7 @@ var ts; member = prop; } else { - ts.Debug.assert(memberDecl.kind === 137 || memberDecl.kind === 138); + ts.Debug.assert(memberDecl.kind === 138 || memberDecl.kind === 139); checkAccessorDeclaration(memberDecl); } if (!ts.hasDynamicName(memberDecl)) { @@ -13639,7 +15018,7 @@ var ts; var stringIndexType = getIndexType(0); var numberIndexType = getIndexType(1); var result = createAnonymousType(node.symbol, propertiesTable, emptyArray, emptyArray, stringIndexType, numberIndexType); - result.flags |= 131072 | 524288 | (typeFlags & 262144); + result.flags |= 262144 | 1048576 | (typeFlags & 524288); return result; function getIndexType(kind) { if (contextualType && contextualTypeHasIndexSignature(contextualType, kind)) { @@ -13661,7 +15040,7 @@ var ts; } } function getDeclarationKindFromSymbol(s) { - return s.valueDeclaration ? s.valueDeclaration.kind : 133; + return s.valueDeclaration ? s.valueDeclaration.kind : 134; } function getDeclarationFlagsFromSymbol(s) { return s.valueDeclaration ? ts.getCombinedNodeFlags(s.valueDeclaration) : s.flags & 134217728 ? 16 | 128 : 0; @@ -13671,7 +15050,7 @@ var ts; if (!(flags & (32 | 64))) { return; } - var enclosingClassDeclaration = ts.getAncestor(node, 202); + var enclosingClassDeclaration = ts.getAncestor(node, 204); var enclosingClass = enclosingClassDeclaration ? getDeclaredTypeOfSymbol(getSymbolOfNode(enclosingClassDeclaration)) : undefined; var declaringClass = getDeclaredTypeOfSymbol(prop.parent); if (flags & 32) { @@ -13701,43 +15080,41 @@ var ts; return checkPropertyAccessExpressionOrQualifiedName(node, node.left, node.right); } function checkPropertyAccessExpressionOrQualifiedName(node, left, right) { - var type = checkExpressionOrQualifiedName(left); - if (type === unknownType) + var type = checkExpression(left); + if (isTypeAny(type)) { return type; - if (type !== anyType) { - var apparentType = getApparentType(getWidenedType(type)); - if (apparentType === unknownType) { - return unknownType; - } - var prop = getPropertyOfType(apparentType, right.text); - if (!prop) { - if (right.text) { - error(right, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(right), typeToString(type)); - } - return unknownType; - } - getNodeLinks(node).resolvedSymbol = prop; - if (prop.parent && prop.parent.flags & 32) { - if (left.kind === 91 && getDeclarationKindFromSymbol(prop) !== 135) { - error(right, ts.Diagnostics.Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword); - } - else { - checkClassPropertyAccess(node, left, type, prop); - } - } - return getTypeOfSymbol(prop); } - return anyType; + var apparentType = getApparentType(getWidenedType(type)); + if (apparentType === unknownType) { + return unknownType; + } + var prop = getPropertyOfType(apparentType, right.text); + if (!prop) { + if (right.text) { + error(right, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(right), typeToString(type)); + } + return unknownType; + } + getNodeLinks(node).resolvedSymbol = prop; + if (prop.parent && prop.parent.flags & 32) { + if (left.kind === 91 && getDeclarationKindFromSymbol(prop) !== 136) { + error(right, ts.Diagnostics.Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword); + } + else { + checkClassPropertyAccess(node, left, type, prop); + } + } + return getTypeOfSymbol(prop); } function isValidPropertyAccess(node, propertyName) { - var left = node.kind === 156 + var left = node.kind === 158 ? node.expression : node.left; - var type = checkExpressionOrQualifiedName(left); - if (type !== unknownType && type !== anyType) { + var type = checkExpression(left); + if (type !== unknownType && !isTypeAny(type)) { var prop = getPropertyOfType(getWidenedType(type), propertyName); if (prop && prop.parent && prop.parent.flags & 32) { - if (left.kind === 91 && getDeclarationKindFromSymbol(prop) !== 135) { + if (left.kind === 91 && getDeclarationKindFromSymbol(prop) !== 136) { return false; } else { @@ -13752,7 +15129,7 @@ var ts; function checkIndexedAccess(node) { if (!node.argumentExpression) { var sourceFile = getSourceFile(node); - if (node.parent.kind === 159 && node.parent.expression === node) { + if (node.parent.kind === 161 && 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); @@ -13775,21 +15152,21 @@ var ts; return unknownType; } if (node.argumentExpression) { - var name_6 = getPropertyNameForIndexedAccess(node.argumentExpression, indexType); - if (name_6 !== undefined) { - var prop = getPropertyOfType(objectType, name_6); + var name_10 = getPropertyNameForIndexedAccess(node.argumentExpression, indexType); + if (name_10 !== undefined) { + var prop = getPropertyOfType(objectType, name_10); if (prop) { getNodeLinks(node).resolvedSymbol = prop; return getTypeOfSymbol(prop); } else if (isConstEnum) { - error(node.argumentExpression, ts.Diagnostics.Property_0_does_not_exist_on_const_enum_1, name_6, symbolToString(objectType.symbol)); + error(node.argumentExpression, ts.Diagnostics.Property_0_does_not_exist_on_const_enum_1, name_10, symbolToString(objectType.symbol)); return unknownType; } } } - if (allConstituentTypesHaveKind(indexType, 1 | 258 | 132 | 1048576)) { - if (allConstituentTypesHaveKind(indexType, 1 | 132)) { + if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 258 | 132 | 2097152)) { + if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 132)) { var numberIndexType = getIndexTypeOfType(objectType, 1); if (numberIndexType) { return numberIndexType; @@ -13799,7 +15176,7 @@ var ts; if (stringIndexType) { return stringIndexType; } - if (compilerOptions.noImplicitAny && !compilerOptions.suppressImplicitAnyIndexErrors && objectType !== anyType) { + if (compilerOptions.noImplicitAny && !compilerOptions.suppressImplicitAnyIndexErrors && !isTypeAny(objectType)) { error(node, ts.Diagnostics.Index_signature_of_object_type_implicitly_has_an_any_type); } return anyType; @@ -13824,7 +15201,7 @@ var ts; if (!ts.isWellKnownSymbolSyntactically(expression)) { return false; } - if ((expressionType.flags & 1048576) === 0) { + if ((expressionType.flags & 2097152) === 0) { if (reportError) { error(expression, ts.Diagnostics.A_computed_property_name_of_the_form_0_must_be_of_type_symbol, ts.getTextOfNode(expression)); } @@ -13848,7 +15225,7 @@ var ts; return true; } function resolveUntypedCall(node) { - if (node.kind === 160) { + if (node.kind === 162) { checkExpression(node.template); } else { @@ -13873,19 +15250,19 @@ var ts; for (var _i = 0; _i < signatures.length; _i++) { var signature = signatures[_i]; var symbol = signature.declaration && getSymbolOfNode(signature.declaration); - var parent_4 = signature.declaration && signature.declaration.parent; + var parent_6 = signature.declaration && signature.declaration.parent; if (!lastSymbol || symbol === lastSymbol) { - if (lastParent && parent_4 === lastParent) { + if (lastParent && parent_6 === lastParent) { index++; } else { - lastParent = parent_4; + lastParent = parent_6; index = cutoffIndex; } } else { index = cutoffIndex = result.length; - lastParent = parent_4; + lastParent = parent_6; } lastSymbol = symbol; if (signature.hasStringLiterals) { @@ -13901,7 +15278,7 @@ var ts; } function getSpreadArgumentIndex(args) { for (var i = 0; i < args.length; i++) { - if (args[i].kind === 174) { + if (args[i].kind === 176) { return i; } } @@ -13911,11 +15288,11 @@ var ts; var adjustedArgCount; var typeArguments; var callIsIncomplete; - if (node.kind === 160) { + if (node.kind === 162) { var tagExpression = node; adjustedArgCount = args.length; typeArguments = undefined; - if (tagExpression.template.kind === 172) { + if (tagExpression.template.kind === 174) { var templateExpression = tagExpression.template; var lastSpan = ts.lastOrUndefined(templateExpression.templateSpans); ts.Debug.assert(lastSpan !== undefined); @@ -13930,7 +15307,7 @@ var ts; else { var callExpression = node; if (!callExpression.arguments) { - ts.Debug.assert(callExpression.kind === 159); + ts.Debug.assert(callExpression.kind === 161); return signature.minArgumentCount === 0; } adjustedArgCount = callExpression.arguments.hasTrailingComma ? args.length + 1 : args.length; @@ -13982,10 +15359,10 @@ var ts; } for (var i = 0; i < args.length; i++) { var arg = args[i]; - if (arg.kind !== 176) { + if (arg.kind !== 178) { var paramType = getTypeAtPosition(signature, i); var argType = void 0; - if (i === 0 && args[i].parent.kind === 160) { + if (i === 0 && args[i].parent.kind === 162) { argType = globalTemplateStringsArrayType; } else { @@ -14025,9 +15402,9 @@ var ts; function checkApplicableSignature(node, args, signature, relation, excludeArgument, reportErrors) { for (var i = 0; i < args.length; i++) { var arg = args[i]; - if (arg.kind !== 176) { + if (arg.kind !== 178) { var paramType = getTypeAtPosition(signature, i); - var argType = i === 0 && node.kind === 160 + var argType = i === 0 && node.kind === 162 ? globalTemplateStringsArrayType : arg.kind === 8 && !reportErrors ? getStringLiteralType(arg) @@ -14041,10 +15418,10 @@ var ts; } function getEffectiveCallArguments(node) { var args; - if (node.kind === 160) { + if (node.kind === 162) { var template = node.template; args = [template]; - if (template.kind === 172) { + if (template.kind === 174) { ts.forEach(template.templateSpans, function (span) { args.push(span.expression); }); @@ -14055,21 +15432,11 @@ var ts; } return args; } - function getEffectiveTypeArguments(callExpression) { - if (callExpression.expression.kind === 91) { - var containingClass = ts.getAncestor(callExpression, 202); - var baseClassTypeNode = containingClass && ts.getClassExtendsHeritageClauseElement(containingClass); - return baseClassTypeNode && baseClassTypeNode.typeArguments; - } - else { - return callExpression.typeArguments; - } - } function resolveCall(node, signatures, candidatesOutArray) { - var isTaggedTemplate = node.kind === 160; + var isTaggedTemplate = node.kind === 162; var typeArguments; if (!isTaggedTemplate) { - typeArguments = getEffectiveTypeArguments(node); + typeArguments = node.typeArguments; if (node.expression.kind !== 91) { ts.forEach(typeArguments, checkSourceElement); } @@ -14110,8 +15477,8 @@ var ts; checkApplicableSignature(node, args, candidateForArgumentError, assignableRelation, undefined, true); } else if (candidateForTypeArgumentError) { - if (!isTaggedTemplate && node.typeArguments) { - checkTypeArguments(candidateForTypeArgumentError, node.typeArguments, [], true); + if (!isTaggedTemplate && typeArguments) { + checkTypeArguments(candidateForTypeArgumentError, typeArguments, [], true); } else { ts.Debug.assert(resultOfFailedInference.failedTypeParameterIndex >= 0); @@ -14195,7 +15562,9 @@ var ts; if (node.expression.kind === 91) { var superType = checkSuperExpression(node.expression); if (superType !== unknownType) { - return resolveCall(node, getSignaturesOfType(superType, 1), candidatesOutArray); + var baseTypeNode = ts.getClassExtendsHeritageClauseElement(ts.getAncestor(node, 204)); + var baseConstructors = getInstantiatedConstructorsForTypeArguments(superType, baseTypeNode.typeArguments); + return resolveCall(node, baseConstructors, candidatesOutArray); } return resolveUntypedCall(node); } @@ -14206,8 +15575,8 @@ var ts; } var callSignatures = getSignaturesOfType(apparentType, 0); var constructSignatures = getSignaturesOfType(apparentType, 1); - if (funcType === anyType || (!callSignatures.length && !constructSignatures.length && !(funcType.flags & 16384) && isTypeAssignableTo(funcType, globalFunctionType))) { - if (node.typeArguments) { + if (isTypeAny(funcType) || (!callSignatures.length && !constructSignatures.length && !(funcType.flags & 16384) && isTypeAssignableTo(funcType, globalFunctionType))) { + if (funcType !== unknownType && node.typeArguments) { error(node, ts.Diagnostics.Untyped_function_calls_may_not_accept_type_arguments); } return resolveUntypedCall(node); @@ -14224,23 +15593,23 @@ var ts; return resolveCall(node, callSignatures, candidatesOutArray); } function resolveNewExpression(node, candidatesOutArray) { - if (node.arguments && languageVersion < 2) { + 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_6_and_higher); + error(node.arguments[spreadIndex], ts.Diagnostics.Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher); } } var expressionType = checkExpression(node.expression); - if (expressionType === anyType) { + expressionType = getApparentType(expressionType); + if (expressionType === unknownType) { + return resolveErrorCall(node); + } + if (isTypeAny(expressionType)) { if (node.typeArguments) { error(node, ts.Diagnostics.Untyped_function_calls_may_not_accept_type_arguments); } return resolveUntypedCall(node); } - expressionType = getApparentType(expressionType); - if (expressionType === unknownType) { - return resolveErrorCall(node); - } var constructSignatures = getSignaturesOfType(expressionType, 1); if (constructSignatures.length) { return resolveCall(node, constructSignatures, candidatesOutArray); @@ -14263,7 +15632,7 @@ var ts; return resolveErrorCall(node); } var callSignatures = getSignaturesOfType(apparentType, 0); - if (tagType === anyType || (!callSignatures.length && !(tagType.flags & 16384) && isTypeAssignableTo(tagType, globalFunctionType))) { + if (isTypeAny(tagType) || (!callSignatures.length && !(tagType.flags & 16384) && isTypeAssignableTo(tagType, globalFunctionType))) { return resolveUntypedCall(node); } if (!callSignatures.length) { @@ -14276,13 +15645,13 @@ var ts; var links = getNodeLinks(node); if (!links.resolvedSignature || candidatesOutArray) { links.resolvedSignature = anySignature; - if (node.kind === 158) { + if (node.kind === 160) { links.resolvedSignature = resolveCallExpression(node, candidatesOutArray); } - else if (node.kind === 159) { + else if (node.kind === 161) { links.resolvedSignature = resolveNewExpression(node, candidatesOutArray); } - else if (node.kind === 160) { + else if (node.kind === 162) { links.resolvedSignature = resolveTaggedTemplateExpression(node, candidatesOutArray); } else { @@ -14297,12 +15666,12 @@ var ts; if (node.expression.kind === 91) { return voidType; } - if (node.kind === 159) { + if (node.kind === 161) { var declaration = signature.declaration; if (declaration && - declaration.kind !== 136 && - declaration.kind !== 140 && - declaration.kind !== 144) { + declaration.kind !== 137 && + declaration.kind !== 141 && + declaration.kind !== 146) { if (compilerOptions.noImplicitAny) { error(node, ts.Diagnostics.new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type); } @@ -14349,18 +15718,41 @@ var ts; return unknownType; } var type; - if (func.body.kind !== 180) { + if (func.body.kind !== 182) { type = checkExpressionCached(func.body, contextualMapper); } else { - var types = checkAndAggregateReturnExpressionTypes(func.body, contextualMapper); - if (types.length === 0) { - return voidType; + var types; + var funcIsGenerator = !!func.asteriskToken; + if (funcIsGenerator) { + types = checkAndAggregateYieldOperandTypes(func.body, contextualMapper); + if (types.length === 0) { + var iterableIteratorAny = createIterableIteratorType(anyType); + if (compilerOptions.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.body, contextualMapper); + if (types.length === 0) { + return voidType; + } } type = contextualSignature ? getUnionType(types) : getCommonSupertype(types); if (!type) { - error(func, ts.Diagnostics.No_best_common_type_exists_among_return_expressions); - return unknownType; + if (funcIsGenerator) { + error(func, ts.Diagnostics.No_best_common_type_exists_among_yield_expressions); + return createIterableIteratorType(unknownType); + } + else { + error(func, ts.Diagnostics.No_best_common_type_exists_among_return_expressions); + return unknownType; + } + } + if (funcIsGenerator) { + type = createIterableIteratorType(type); } } if (!contextualSignature) { @@ -14368,6 +15760,22 @@ var ts; } return getWidenedType(type); } + function checkAndAggregateYieldOperandTypes(body, contextualMapper) { + var aggregatedTypes = []; + ts.forEachYieldExpression(body, function (yieldExpression) { + var expr = yieldExpression.expression; + if (expr) { + var type = checkExpressionCached(expr, contextualMapper); + if (yieldExpression.asteriskToken) { + type = checkElementTypeOfIterable(type, yieldExpression.expression); + } + if (!ts.contains(aggregatedTypes, type)) { + aggregatedTypes.push(type); + } + } + }); + return aggregatedTypes; + } function checkAndAggregateReturnExpressionTypes(body, contextualMapper) { var aggregatedTypes = []; ts.forEachReturnStatement(body, function (returnStatement) { @@ -14387,16 +15795,16 @@ var ts; }); } function bodyContainsSingleThrowStatement(body) { - return (body.statements.length === 1) && (body.statements[0].kind === 196); + return (body.statements.length === 1) && (body.statements[0].kind === 198); } function checkIfNonVoidFunctionHasReturnExpressionsOrSingleThrowStatment(func, returnType) { if (!produceDiagnostics) { return; } - if (returnType === voidType || returnType === anyType) { + if (returnType === voidType || isTypeAny(returnType)) { return; } - if (ts.nodeIsMissing(func.body) || func.body.kind !== 180) { + if (ts.nodeIsMissing(func.body) || func.body.kind !== 182) { return; } var bodyBlock = func.body; @@ -14409,10 +15817,10 @@ var ts; error(func.type, ts.Diagnostics.A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value_or_consist_of_a_single_throw_statement); } function checkFunctionExpressionOrObjectLiteralMethod(node, contextualMapper) { - ts.Debug.assert(node.kind !== 135 || ts.isObjectLiteralMethod(node)); - var hasGrammarError = checkGrammarDeclarationNameInStrictMode(node) || checkGrammarFunctionLikeDeclaration(node); - if (!hasGrammarError && node.kind === 163) { - checkGrammarFunctionName(node.name) || checkGrammarForGenerator(node); + ts.Debug.assert(node.kind !== 136 || ts.isObjectLiteralMethod(node)); + var hasGrammarError = checkGrammarFunctionLikeDeclaration(node); + if (!hasGrammarError && node.kind === 165) { + checkGrammarForGenerator(node); } if (contextualMapper === identityMapper && isContextSensitive(node)) { return anyFunctionType; @@ -14438,19 +15846,22 @@ var ts; checkSignatureDeclaration(node); } } - if (produceDiagnostics && node.kind !== 135 && node.kind !== 134) { + if (produceDiagnostics && node.kind !== 136 && node.kind !== 135) { checkCollisionWithCapturedSuperVariable(node, node.name); checkCollisionWithCapturedThisVariable(node, node.name); } return type; } function checkFunctionExpressionOrObjectLiteralMethodBody(node) { - ts.Debug.assert(node.kind !== 135 || ts.isObjectLiteralMethod(node)); + ts.Debug.assert(node.kind !== 136 || ts.isObjectLiteralMethod(node)); if (node.type && !node.asteriskToken) { checkIfNonVoidFunctionHasReturnExpressionsOrSingleThrowStatment(node, getTypeFromTypeNode(node.type)); } if (node.body) { - if (node.body.kind === 180) { + if (!node.type) { + getReturnTypeOfSignature(getSignatureFromDeclaration(node)); + } + if (node.body.kind === 182) { checkSourceElement(node.body); } else { @@ -14463,7 +15874,7 @@ var ts; } } function checkArithmeticOperandType(operand, type, diagnostic) { - if (!allConstituentTypesHaveKind(type, 1 | 132)) { + if (!isTypeAnyOrAllConstituentTypesHaveKind(type, 132)) { error(operand, diagnostic); return false; } @@ -14480,13 +15891,13 @@ var ts; var symbol = findSymbol(n); return !symbol || symbol === unknownSymbol || symbol === argumentsSymbol || (symbol.flags & 3) !== 0; } - case 156: { + case 158: { var symbol = findSymbol(n); return !symbol || symbol === unknownSymbol || (symbol.flags & ~8) !== 0; } - case 157: + case 159: return true; - case 162: + case 164: return isReferenceOrErrorExpression(n.expression); default: return false; @@ -14495,21 +15906,21 @@ var ts; function isConstVariableReference(n) { switch (n.kind) { case 65: - case 156: { + case 158: { var symbol = findSymbol(n); return symbol && (symbol.flags & 3) !== 0 && (getDeclarationFlagsFromSymbol(symbol) & 8192) !== 0; } - case 157: { + case 159: { var index = n.argumentExpression; var symbol = findSymbol(n.expression); if (symbol && index && index.kind === 8) { - var name_7 = index.text; - var prop = getPropertyOfType(getTypeOfSymbol(symbol), name_7); + var name_11 = index.text; + var prop = getPropertyOfType(getTypeOfSymbol(symbol), name_11); return prop && (prop.flags & 3) !== 0 && (getDeclarationFlagsFromSymbol(prop) & 8192) !== 0; } return false; } - case 162: + case 164: return isConstVariableReference(n.expression); default: return false; @@ -14526,10 +15937,7 @@ var ts; return true; } function checkDeleteExpression(node) { - if (node.parserContextFlags & 1 && node.expression.kind === 65) { - grammarErrorOnNode(node.expression, ts.Diagnostics.delete_cannot_be_called_on_an_identifier_in_strict_mode); - } - var operandType = checkExpression(node.expression); + checkExpression(node.expression); return booleanType; } function checkTypeOfExpression(node) { @@ -14541,15 +15949,12 @@ var ts; return undefinedType; } function checkPrefixUnaryExpression(node) { - if ((node.operator === 38 || node.operator === 39)) { - checkGrammarEvalOrArgumentsInStrictMode(node, node.operand); - } var operandType = checkExpression(node.operand); switch (node.operator) { case 33: case 34: case 47: - if (someConstituentTypeHasKind(operandType, 1048576)) { + if (someConstituentTypeHasKind(operandType, 2097152)) { error(node.operand, ts.Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, ts.tokenToString(node.operator)); } return numberType; @@ -14566,7 +15971,6 @@ var ts; return unknownType; } function checkPostfixUnaryExpression(node) { - checkGrammarEvalOrArgumentsInStrictMode(node, node.operand); var operandType = checkExpression(node.operand); var ok = checkArithmeticOperandType(node.operand, operandType, ts.Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type); if (ok) { @@ -14613,19 +16017,19 @@ var ts; return (symbol.flags & 128) !== 0; } function checkInstanceOfExpression(node, leftType, rightType) { - if (allConstituentTypesHaveKind(leftType, 1049086)) { + if (allConstituentTypesHaveKind(leftType, 2097662)) { error(node.left, ts.Diagnostics.The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_parameter); } - if (!(rightType.flags & 1 || isTypeSubtypeOf(rightType, globalFunctionType))) { + if (!(isTypeAny(rightType) || isTypeSubtypeOf(rightType, globalFunctionType))) { error(node.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(node, leftType, rightType) { - if (!allConstituentTypesHaveKind(leftType, 1 | 258 | 132 | 1048576)) { + if (!isTypeAnyOrAllConstituentTypesHaveKind(leftType, 258 | 132 | 2097152)) { error(node.left, ts.Diagnostics.The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol); } - if (!allConstituentTypesHaveKind(rightType, 1 | 48128 | 512)) { + if (!isTypeAnyOrAllConstituentTypesHaveKind(rightType, 48128 | 512)) { error(node.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; @@ -14634,17 +16038,18 @@ var ts; var properties = node.properties; for (var _i = 0; _i < properties.length; _i++) { var p = properties[_i]; - if (p.kind === 225 || p.kind === 226) { - var name_8 = p.name; - var type = sourceType.flags & 1 ? sourceType : - getTypeOfPropertyOfType(sourceType, name_8.text) || - isNumericLiteralName(name_8.text) && getIndexTypeOfType(sourceType, 1) || + if (p.kind === 227 || p.kind === 228) { + var name_12 = p.name; + var type = isTypeAny(sourceType) + ? sourceType + : getTypeOfPropertyOfType(sourceType, name_12.text) || + isNumericLiteralName(name_12.text) && getIndexTypeOfType(sourceType, 1) || getIndexTypeOfType(sourceType, 0); if (type) { - checkDestructuringAssignment(p.initializer || name_8, type); + checkDestructuringAssignment(p.initializer || name_12, type); } else { - error(name_8, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(sourceType), ts.declarationNameToString(name_8)); + error(name_12, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(sourceType), ts.declarationNameToString(name_12)); } } else { @@ -14658,11 +16063,12 @@ var ts; var elements = node.elements; for (var i = 0; i < elements.length; i++) { var e = elements[i]; - if (e.kind !== 176) { - if (e.kind !== 174) { + if (e.kind !== 178) { + if (e.kind !== 176) { var propName = "" + i; - var type = sourceType.flags & 1 ? sourceType : - isTupleLikeType(sourceType) + var type = isTypeAny(sourceType) + ? sourceType + : isTupleLikeType(sourceType) ? getTypeOfPropertyOfType(sourceType, propName) : elementType; if (type) { @@ -14683,7 +16089,7 @@ var ts; } else { var restExpression = e.expression; - if (restExpression.kind === 170 && restExpression.operatorToken.kind === 53) { + if (restExpression.kind === 172 && restExpression.operatorToken.kind === 53) { error(restExpression.operatorToken, ts.Diagnostics.A_rest_element_cannot_have_an_initializer); } else { @@ -14696,14 +16102,14 @@ var ts; return sourceType; } function checkDestructuringAssignment(target, sourceType, contextualMapper) { - if (target.kind === 170 && target.operatorToken.kind === 53) { + if (target.kind === 172 && target.operatorToken.kind === 53) { checkBinaryExpression(target, contextualMapper); target = target.left; } - if (target.kind === 155) { + if (target.kind === 157) { return checkObjectLiteralAssignment(target, sourceType, contextualMapper); } - if (target.kind === 154) { + if (target.kind === 156) { return checkArrayLiteralAssignment(target, sourceType, contextualMapper); } return checkReferenceAssignment(target, sourceType, contextualMapper); @@ -14716,11 +16122,8 @@ var ts; return sourceType; } function checkBinaryExpression(node, contextualMapper) { - if (ts.isLeftHandSideExpression(node.left) && ts.isAssignmentOperator(node.operatorToken.kind)) { - checkGrammarEvalOrArgumentsInStrictMode(node, node.left); - } var operator = node.operatorToken.kind; - if (operator === 53 && (node.left.kind === 155 || node.left.kind === 154)) { + if (operator === 53 && (node.left.kind === 157 || node.left.kind === 156)) { return checkDestructuringAssignment(node.left, checkExpression(node.right, contextualMapper), contextualMapper); } var leftType = checkExpression(node.left, contextualMapper); @@ -14778,8 +16181,8 @@ var ts; if (allConstituentTypesHaveKind(leftType, 258) || allConstituentTypesHaveKind(rightType, 258)) { resultType = stringType; } - else if (leftType.flags & 1 || rightType.flags & 1) { - resultType = anyType; + else if (isTypeAny(leftType) || isTypeAny(rightType)) { + resultType = leftType === unknownType || rightType === unknownType ? unknownType : anyType; } if (resultType && !checkForDisallowedESSymbolOperand(operator)) { return resultType; @@ -14823,8 +16226,8 @@ var ts; return rightType; } function checkForDisallowedESSymbolOperand(operator) { - var offendingSymbolOperand = someConstituentTypeHasKind(leftType, 1048576) ? node.left : - someConstituentTypeHasKind(rightType, 1048576) ? node.right : + var offendingSymbolOperand = someConstituentTypeHasKind(leftType, 2097152) ? node.left : + someConstituentTypeHasKind(rightType, 2097152) ? node.right : undefined; if (offendingSymbolOperand) { error(offendingSymbolOperand, ts.Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, ts.tokenToString(operator)); @@ -14859,13 +16262,46 @@ var ts; error(node, ts.Diagnostics.Operator_0_cannot_be_applied_to_types_1_and_2, ts.tokenToString(node.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 (current.kind === 204 || current.kind === 177) { + return true; + } + current = parent; + parent = parent.parent; + } + return false; + } function checkYieldExpression(node) { - if (!(node.parserContextFlags & 4)) { - grammarErrorOnFirstToken(node, ts.Diagnostics.yield_expression_must_be_contained_within_a_generator_declaration); + if (!(node.parserContextFlags & 4) || isYieldExpressionInClass(node)) { + grammarErrorOnFirstToken(node, ts.Diagnostics.A_yield_expression_is_only_allowed_in_a_generator_body); } - else { - grammarErrorOnFirstToken(node, ts.Diagnostics.yield_expressions_are_not_currently_supported); + if (node.expression) { + var func = ts.getContainingFunction(node); + if (func && func.asteriskToken) { + var expressionType = checkExpressionCached(node.expression, undefined); + var expressionElementType; + var nodeIsYieldStar = !!node.asteriskToken; + if (nodeIsYieldStar) { + expressionElementType = checkElementTypeOfIterable(expressionType, node.expression); + } + if (func.type) { + var signatureElementType = getElementTypeOfIterableIterator(getTypeFromTypeNode(func.type)) || anyType; + if (nodeIsYieldStar) { + checkTypeAssignableTo(expressionElementType, signatureElementType, node.expression, undefined); + } + else { + checkTypeAssignableTo(expressionType, signatureElementType, node.expression, undefined); + } + } + } } + return anyType; } function checkConditionalExpression(node, contextualMapper) { checkExpression(node.condition); @@ -14894,14 +16330,14 @@ var ts; return links.resolvedType; } function checkPropertyAssignment(node, contextualMapper) { - if (node.name.kind === 128) { + if (node.name.kind === 129) { checkComputedPropertyName(node.name); } return checkExpression(node.initializer, contextualMapper); } function checkObjectLiteralMethod(node, contextualMapper) { checkGrammarMethod(node); - if (node.name.kind === 128) { + if (node.name.kind === 129) { checkComputedPropertyName(node.name); } var uninstantiatedType = checkFunctionExpressionOrObjectLiteralMethod(node, contextualMapper); @@ -14923,12 +16359,8 @@ var ts; return type; } function checkExpression(node, contextualMapper) { - checkGrammarIdentifierInStrictMode(node); - return checkExpressionOrQualifiedName(node, contextualMapper); - } - function checkExpressionOrQualifiedName(node, contextualMapper) { var type; - if (node.kind == 127) { + if (node.kind === 128) { type = checkQualifiedName(node); } else { @@ -14936,9 +16368,9 @@ var ts; type = instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, contextualMapper); } if (isConstEnumObjectType(type)) { - var ok = (node.parent.kind === 156 && node.parent.expression === node) || - (node.parent.kind === 157 && node.parent.expression === node) || - ((node.kind === 65 || node.kind === 127) && isInRightSideOfImportOrExportAssignment(node)); + var ok = (node.parent.kind === 158 && node.parent.expression === node) || + (node.parent.kind === 159 && node.parent.expression === node) || + ((node.kind === 65 || node.kind === 128) && 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); } @@ -14964,61 +16396,59 @@ var ts; return booleanType; case 7: return checkNumericLiteral(node); - case 172: + case 174: return checkTemplateExpression(node); case 8: case 10: return stringType; case 9: return globalRegExpType; - case 154: - return checkArrayLiteral(node, contextualMapper); - case 155: - return checkObjectLiteral(node, contextualMapper); case 156: - return checkPropertyAccessExpression(node); + return checkArrayLiteral(node, contextualMapper); case 157: - return checkIndexedAccess(node); + return checkObjectLiteral(node, contextualMapper); case 158: + return checkPropertyAccessExpression(node); case 159: - return checkCallExpression(node); + return checkIndexedAccess(node); case 160: - return checkTaggedTemplateExpression(node); case 161: - return checkTypeAssertion(node); + return checkCallExpression(node); case 162: - return checkExpression(node.expression, contextualMapper); - case 175: - return checkClassExpression(node); + return checkTaggedTemplateExpression(node); case 163: + return checkTypeAssertion(node); case 164: - return checkFunctionExpressionOrObjectLiteralMethod(node, contextualMapper); - case 166: - return checkTypeOfExpression(node); + return checkExpression(node.expression, contextualMapper); + case 177: + return checkClassExpression(node); case 165: - return checkDeleteExpression(node); - case 167: - return checkVoidExpression(node); + case 166: + return checkFunctionExpressionOrObjectLiteralMethod(node, contextualMapper); case 168: - return checkPrefixUnaryExpression(node); + return checkTypeOfExpression(node); + case 167: + return checkDeleteExpression(node); case 169: - return checkPostfixUnaryExpression(node); + return checkVoidExpression(node); case 170: - return checkBinaryExpression(node, contextualMapper); + return checkPrefixUnaryExpression(node); case 171: - return checkConditionalExpression(node, contextualMapper); - case 174: - return checkSpreadElementExpression(node, contextualMapper); - case 176: - return undefinedType; + return checkPostfixUnaryExpression(node); + case 172: + return checkBinaryExpression(node, contextualMapper); case 173: - checkYieldExpression(node); - return unknownType; + return checkConditionalExpression(node, contextualMapper); + case 176: + return checkSpreadElementExpression(node, contextualMapper); + case 178: + return undefinedType; + case 175: + return checkYieldExpression(node); } return unknownType; } function checkTypeParameter(node) { - checkGrammarDeclarationNameInStrictMode(node); if (node.expression) { grammarErrorOnFirstToken(node.expression, ts.Diagnostics.Type_expected); } @@ -15033,14 +16463,12 @@ var ts; // 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). - // It is a SyntaxError if the identifier eval or arguments appears within a FormalParameterList of a - // strict mode FunctionLikeDeclaration or FunctionExpression(13.1) - checkGrammarDecorators(node) || checkGrammarModifiers(node) || checkGrammarEvalOrArgumentsInStrictMode(node, node.name); + checkGrammarDecorators(node) || checkGrammarModifiers(node); checkVariableLikeDeclaration(node); var func = ts.getContainingFunction(node); if (node.flags & 112) { func = ts.getContainingFunction(node); - if (!(func.kind === 136 && ts.nodeIsPresent(func.body))) { + if (!(func.kind === 137 && ts.nodeIsPresent(func.body))) { error(node, ts.Diagnostics.A_parameter_property_is_only_allowed_in_a_constructor_implementation); } } @@ -15051,37 +16479,132 @@ var ts; error(node, ts.Diagnostics.A_rest_parameter_must_be_of_an_array_type); } } + function isSyntacticallyValidGenerator(node) { + if (!node.asteriskToken || !node.body) { + return false; + } + return node.kind === 136 || + node.kind === 203 || + node.kind === 165; + } + function getTypePredicateParameterIndex(parameterList, parameter) { + if (parameterList) { + for (var i = 0; i < parameterList.length; i++) { + var param = parameterList[i]; + if (param.name.kind === 65 && + param.name.text === parameter.text) { + return i; + } + } + } + return -1; + } + function isInLegalTypePredicatePosition(node) { + switch (node.parent.kind) { + case 166: + case 140: + case 203: + case 165: + case 145: + case 136: + case 135: + return node === node.parent.type; + } + return false; + } function checkSignatureDeclaration(node) { - if (node.kind === 141) { + if (node.kind === 142) { checkGrammarIndexSignature(node); } - else if (node.kind === 143 || node.kind === 201 || node.kind === 144 || - node.kind === 139 || node.kind === 136 || - node.kind === 140) { + else if (node.kind === 145 || node.kind === 203 || node.kind === 146 || + node.kind === 140 || node.kind === 137 || + node.kind === 141) { checkGrammarFunctionLikeDeclaration(node); } checkTypeParameters(node.typeParameters); ts.forEach(node.parameters, checkParameter); if (node.type) { - checkSourceElement(node.type); + if (node.type.kind === 143) { + var typePredicate = getSignatureFromDeclaration(node).typePredicate; + var typePredicateNode = node.type; + if (isInLegalTypePredicatePosition(typePredicateNode)) { + if (typePredicate.parameterIndex >= 0) { + if (node.parameters[typePredicate.parameterIndex].dotDotDotToken) { + error(typePredicateNode.parameterName, ts.Diagnostics.A_type_predicate_cannot_reference_a_rest_parameter); + } + else { + checkTypeAssignableTo(typePredicate.type, getTypeAtLocation(node.parameters[typePredicate.parameterIndex]), typePredicateNode.type); + } + } + else if (typePredicateNode.parameterName) { + var hasReportedError = false; + for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) { + var param = _a[_i]; + if (hasReportedError) { + break; + } + if (param.name.kind === 153 || + param.name.kind === 154) { + (function checkBindingPattern(pattern) { + for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) { + var element = _a[_i]; + if (element.name.kind === 65 && + element.name.text === typePredicate.parameterName) { + error(typePredicateNode.parameterName, ts.Diagnostics.A_type_predicate_cannot_reference_element_0_in_a_binding_pattern, typePredicate.parameterName); + hasReportedError = true; + break; + } + else if (element.name.kind === 154 || + element.name.kind === 153) { + checkBindingPattern(element.name); + } + } + })(param.name); + } + } + if (!hasReportedError) { + error(typePredicateNode.parameterName, ts.Diagnostics.Cannot_find_parameter_0, typePredicate.parameterName); + } + } + } + else { + error(typePredicateNode, ts.Diagnostics.A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods); + } + } + else { + checkSourceElement(node.type); + } } if (produceDiagnostics) { checkCollisionWithArgumentsInGeneratedCode(node); if (compilerOptions.noImplicitAny && !node.type) { switch (node.kind) { - case 140: + case 141: error(node, ts.Diagnostics.Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type); break; - case 139: + case 140: error(node, ts.Diagnostics.Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type); break; } } + if (node.type) { + if (languageVersion >= 2 && isSyntacticallyValidGenerator(node)) { + var returnType = getTypeFromTypeNode(node.type); + if (returnType === voidType) { + error(node.type, ts.Diagnostics.A_generator_cannot_have_a_void_type_annotation); + } + else { + var generatorElementType = getElementTypeOfIterableIterator(returnType) || anyType; + var iterableIteratorInstantiation = createIterableIteratorType(generatorElementType); + checkTypeAssignableTo(iterableIteratorInstantiation, returnType, node.type); + } + } + } } checkSpecializedSignatureDeclaration(node); } function checkTypeForDuplicateIndexSignatures(node) { - if (node.kind === 203) { + if (node.kind === 205) { var nodeSymbol = getSymbolOfNode(node); if (nodeSymbol.declarations.length > 0 && nodeSymbol.declarations[0] !== node) { return; @@ -15096,7 +16619,7 @@ var ts; var declaration = decl; if (declaration.parameters.length === 1 && declaration.parameters[0].type) { switch (declaration.parameters[0].type.kind) { - case 122: + case 123: if (!seenStringIndexer) { seenStringIndexer = true; } @@ -15104,7 +16627,7 @@ var ts; error(declaration, ts.Diagnostics.Duplicate_string_index_signature); } break; - case 120: + case 121: if (!seenNumericIndexer) { seenNumericIndexer = true; } @@ -15141,17 +16664,17 @@ var ts; return; } function isSuperCallExpression(n) { - return n.kind === 158 && n.expression.kind === 91; + return n.kind === 160 && n.expression.kind === 91; } function containsSuperCall(n) { if (isSuperCallExpression(n)) { return true; } switch (n.kind) { - case 163: - case 201: - case 164: - case 155: return false; + case 165: + case 203: + case 166: + case 157: return false; default: return ts.forEachChild(n, containsSuperCall); } } @@ -15159,12 +16682,12 @@ var ts; if (n.kind === 93) { error(n, ts.Diagnostics.this_cannot_be_referenced_in_current_location); } - else if (n.kind !== 163 && n.kind !== 201) { + else if (n.kind !== 165 && n.kind !== 203) { ts.forEachChild(n, markThisReferencesAsErrors); } } function isInstancePropertyWithInitializer(n) { - return n.kind === 133 && + return n.kind === 134 && !(n.flags & 128) && !!n.initializer; } @@ -15174,7 +16697,7 @@ var ts; ts.forEach(node.parameters, function (p) { return p.flags & (16 | 32 | 64); }); if (superCallShouldBeFirst) { var statements = node.body.statements; - if (!statements.length || statements[0].kind !== 183 || !isSuperCallExpression(statements[0].expression)) { + if (!statements.length || statements[0].kind !== 185 || !isSuperCallExpression(statements[0].expression)) { 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 { @@ -15190,13 +16713,13 @@ var ts; function checkAccessorDeclaration(node) { if (produceDiagnostics) { checkGrammarFunctionLikeDeclaration(node) || checkGrammarAccessor(node) || checkGrammarComputedPropertyName(node.name); - if (node.kind === 137) { + if (node.kind === 138) { if (!ts.isInAmbientContext(node) && ts.nodeIsPresent(node.body) && !(bodyContainsAReturnStatement(node.body) || bodyContainsSingleThrowStatement(node.body))) { error(node.name, ts.Diagnostics.A_get_accessor_must_return_a_value_or_consist_of_a_single_throw_statement); } } if (!ts.hasDynamicName(node)) { - var otherKind = node.kind === 137 ? 138 : 137; + var otherKind = node.kind === 138 ? 139 : 138; var otherAccessor = ts.getDeclarationOfKind(node.symbol, otherKind); if (otherAccessor) { if (((node.flags & 112) !== (otherAccessor.flags & 112))) { @@ -15218,26 +16741,26 @@ var ts; function checkMissingDeclaration(node) { checkDecorators(node); } + function checkTypeArgumentConstraints(typeParameters, typeArguments) { + var result = true; + for (var i = 0; i < typeParameters.length; i++) { + var constraint = getConstraintOfTypeParameter(typeParameters[i]); + if (constraint) { + var typeArgument = typeArguments[i]; + result = result && checkTypeAssignableTo(getTypeFromTypeNode(typeArgument), constraint, typeArgument, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); + } + } + return result; + } function checkTypeReferenceNode(node) { - checkGrammarTypeReferenceInStrictMode(node.typeName); - return checkTypeReferenceOrExpressionWithTypeArguments(node); - } - function checkExpressionWithTypeArguments(node) { - checkGrammarExpressionWithTypeArgumentsInStrictMode(node.expression); - return checkTypeReferenceOrExpressionWithTypeArguments(node); - } - function checkTypeReferenceOrExpressionWithTypeArguments(node) { checkGrammarTypeArguments(node, node.typeArguments); - var type = getTypeFromTypeReferenceOrExpressionWithTypeArguments(node); + var type = getTypeFromTypeReference(node); if (type !== unknownType && node.typeArguments) { - var len = node.typeArguments.length; - for (var i = 0; i < len; i++) { - checkSourceElement(node.typeArguments[i]); - var constraint = getConstraintOfTypeParameter(type.target.typeParameters[i]); - if (produceDiagnostics && constraint) { - var typeArgument = type.typeArguments[i]; - checkTypeAssignableTo(typeArgument, constraint, node, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); - } + 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); } } } @@ -15281,9 +16804,9 @@ var ts; return; } var signaturesToCheck; - if (!signatureDeclarationNode.name && signatureDeclarationNode.parent && signatureDeclarationNode.parent.kind === 203) { - ts.Debug.assert(signatureDeclarationNode.kind === 139 || signatureDeclarationNode.kind === 140); - var signatureKind = signatureDeclarationNode.kind === 139 ? 0 : 1; + if (!signatureDeclarationNode.name && signatureDeclarationNode.parent && signatureDeclarationNode.parent.kind === 205) { + ts.Debug.assert(signatureDeclarationNode.kind === 140 || signatureDeclarationNode.kind === 141); + var signatureKind = signatureDeclarationNode.kind === 140 ? 0 : 1; var containingSymbol = getSymbolOfNode(signatureDeclarationNode.parent); var containingType = getDeclaredTypeOfSymbol(containingSymbol); signaturesToCheck = getSignaturesOfType(containingType, signatureKind); @@ -15301,7 +16824,7 @@ var ts; } function getEffectiveDeclarationFlags(n, flagsToCheck) { var flags = ts.getCombinedNodeFlags(n); - if (n.parent.kind !== 203 && ts.isInAmbientContext(n)) { + if (n.parent.kind !== 205 && ts.isInAmbientContext(n)) { if (!(flags & 2)) { flags |= 1; } @@ -15374,7 +16897,7 @@ var ts; if (subsequentNode.kind === node.kind) { var errorNode_1 = subsequentNode.name || subsequentNode; if (node.name && subsequentNode.name && node.name.text === subsequentNode.name.text) { - ts.Debug.assert(node.kind === 135 || node.kind === 134); + ts.Debug.assert(node.kind === 136 || node.kind === 135); ts.Debug.assert((node.flags & 128) !== (subsequentNode.flags & 128)); var diagnostic = node.flags & 128 ? ts.Diagnostics.Function_overload_must_be_static : ts.Diagnostics.Function_overload_must_not_be_static; error(errorNode_1, diagnostic); @@ -15401,11 +16924,11 @@ var ts; var current = declarations[_i]; var node = current; var inAmbientContext = ts.isInAmbientContext(node); - var inAmbientContextOrInterface = node.parent.kind === 203 || node.parent.kind === 146 || inAmbientContext; + var inAmbientContextOrInterface = node.parent.kind === 205 || node.parent.kind === 148 || inAmbientContext; if (inAmbientContextOrInterface) { previousDeclaration = undefined; } - if (node.kind === 201 || node.kind === 135 || node.kind === 134 || node.kind === 136) { + if (node.kind === 203 || node.kind === 136 || node.kind === 135 || node.kind === 137) { var currentNodeFlags = getEffectiveDeclarationFlags(node, flagsToCheck); someNodeFlags |= currentNodeFlags; allNodeFlags &= currentNodeFlags; @@ -15502,16 +17025,16 @@ var ts; } function getDeclarationSpaces(d) { switch (d.kind) { - case 203: + case 205: return 2097152; - case 206: + case 208: return d.name.kind === 8 || ts.getModuleInstanceState(d) !== 0 ? 4194304 | 1048576 : 4194304; - case 202: - case 205: + case 204: + case 207: return 2097152 | 1048576; - case 209: + case 211: var result = 0; var target = resolveAlias(getSymbolOfNode(d)); ts.forEach(target.declarations, function (d) { result |= getDeclarationSpaces(d); }); @@ -15525,54 +17048,54 @@ var ts; var expression = node.expression; var exprType = checkExpression(expression); switch (node.parent.kind) { - case 202: + case 204: var classSymbol = getSymbolOfNode(node.parent); var classConstructorType = getTypeOfSymbol(classSymbol); var classDecoratorType = instantiateSingleCallFunctionType(getGlobalClassDecoratorType(), [classConstructorType]); checkTypeAssignableTo(exprType, classDecoratorType, node); break; - case 133: + case 134: checkTypeAssignableTo(exprType, getGlobalPropertyDecoratorType(), node); break; - case 135: - case 137: + case 136: case 138: + case 139: var methodType = getTypeOfNode(node.parent); var methodDecoratorType = instantiateSingleCallFunctionType(getGlobalMethodDecoratorType(), [methodType]); checkTypeAssignableTo(exprType, methodDecoratorType, node); break; - case 130: + case 131: checkTypeAssignableTo(exprType, getGlobalParameterDecoratorType(), node); break; } } function checkTypeNodeAsExpression(node) { - if (node && node.kind === 142) { + if (node && node.kind === 144) { var type = getTypeFromTypeNode(node); - var shouldCheckIfUnknownType = type === unknownType && compilerOptions.separateCompilation; - if (!type || (!shouldCheckIfUnknownType && type.flags & (1048703 | 132 | 258))) { + var shouldCheckIfUnknownType = type === unknownType && compilerOptions.isolatedModules; + if (!type || (!shouldCheckIfUnknownType && type.flags & (2097279 | 132 | 258))) { return; } if (shouldCheckIfUnknownType || type.symbol.valueDeclaration) { - checkExpressionOrQualifiedName(node.typeName); + checkExpression(node.typeName); } } } function checkTypeAnnotationAsExpression(node) { switch (node.kind) { - case 133: + case 134: checkTypeNodeAsExpression(node.type); break; - case 130: + case 131: checkTypeNodeAsExpression(node.type); break; - case 135: - checkTypeNodeAsExpression(node.type); - break; - case 137: + case 136: checkTypeNodeAsExpression(node.type); break; case 138: + checkTypeNodeAsExpression(node.type); + break; + case 139: checkTypeNodeAsExpression(getSetAccessorTypeAnnotationNode(node)); break; } @@ -15590,46 +17113,45 @@ var ts; 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_Specify_experimentalDecorators_to_remove_this_warning); + } if (compilerOptions.emitDecoratorMetadata) { switch (node.kind) { - case 202: + case 204: var constructor = ts.getFirstConstructorWithBody(node); if (constructor) { checkParameterTypeAnnotationsAsExpressions(constructor); } break; - case 135: + case 136: checkParameterTypeAnnotationsAsExpressions(node); + case 139: case 138: - case 137: - case 133: - case 130: + case 134: + case 131: checkTypeAnnotationAsExpression(node); break; } } emitDecorate = true; - if (node.kind === 130) { + if (node.kind === 131) { emitParam = true; } ts.forEach(node.decorators, checkDecorator); } function checkFunctionDeclaration(node) { if (produceDiagnostics) { - checkFunctionLikeDeclaration(node) || - checkGrammarDisallowedModifiersInBlockOrObjectLiteralExpression(node) || - checkGrammarFunctionName(node.name) || - checkGrammarForGenerator(node); + checkFunctionLikeDeclaration(node) || checkGrammarForGenerator(node); checkCollisionWithCapturedSuperVariable(node, node.name); checkCollisionWithCapturedThisVariable(node, node.name); checkCollisionWithRequireExportsInGeneratedCode(node, node.name); } } function checkFunctionLikeDeclaration(node) { - checkGrammarDeclarationNameInStrictMode(node); checkDecorators(node); checkSignatureDeclaration(node); - if (node.name && node.name.kind === 128) { + if (node.name && node.name.kind === 129) { checkComputedPropertyName(node.name); } if (!ts.hasDynamicName(node)) { @@ -15649,21 +17171,26 @@ var ts; if (node.type && !isAccessor(node.kind) && !node.asteriskToken) { checkIfNonVoidFunctionHasReturnExpressionsOrSingleThrowStatment(node, getTypeFromTypeNode(node.type)); } - if (compilerOptions.noImplicitAny && ts.nodeIsMissing(node.body) && !node.type && !isPrivateWithinAmbient(node)) { - reportImplicitAnyError(node, anyType); + if (produceDiagnostics && !node.type) { + if (compilerOptions.noImplicitAny && ts.nodeIsMissing(node.body) && !isPrivateWithinAmbient(node)) { + reportImplicitAnyError(node, anyType); + } + if (node.asteriskToken && ts.nodeIsPresent(node.body)) { + getReturnTypeOfSignature(getSignatureFromDeclaration(node)); + } } } function checkBlock(node) { - if (node.kind === 180) { + if (node.kind === 182) { checkGrammarStatementInAmbientContext(node); } ts.forEach(node.statements, checkSourceElement); - if (ts.isFunctionBlock(node) || node.kind === 207) { + if (ts.isFunctionBlock(node) || node.kind === 209) { checkFunctionExpressionBodies(node); } } function checkCollisionWithArgumentsInGeneratedCode(node) { - if (!ts.hasRestParameters(node) || ts.isInAmbientContext(node) || ts.nodeIsMissing(node.body)) { + if (!ts.hasRestParameter(node) || ts.isInAmbientContext(node) || ts.nodeIsMissing(node.body)) { return; } ts.forEach(node.parameters, function (p) { @@ -15676,19 +17203,19 @@ var ts; if (!(identifier && identifier.text === name)) { return false; } - if (node.kind === 133 || - node.kind === 132 || + if (node.kind === 134 || + node.kind === 133 || + node.kind === 136 || node.kind === 135 || - node.kind === 134 || - node.kind === 137 || - node.kind === 138) { + node.kind === 138 || + node.kind === 139) { return false; } if (ts.isInAmbientContext(node)) { return false; } var root = ts.getRootDeclaration(node); - if (root.kind === 130 && ts.nodeIsMissing(root.parent.body)) { + if (root.kind === 131 && ts.nodeIsMissing(root.parent.body)) { return false; } return true; @@ -15718,7 +17245,7 @@ var ts; if (!needCollisionCheckForIdentifier(node, name, "_super")) { return; } - var enclosingClass = ts.getAncestor(node, 202); + var enclosingClass = ts.getAncestor(node, 204); if (!enclosingClass || ts.isInAmbientContext(enclosingClass)) { return; } @@ -15736,11 +17263,11 @@ var ts; if (!needCollisionCheckForIdentifier(node, name, "require") && !needCollisionCheckForIdentifier(node, name, "exports")) { return; } - if (node.kind === 206 && ts.getModuleInstanceState(node) !== 1) { + if (node.kind === 208 && ts.getModuleInstanceState(node) !== 1) { return; } var parent = getDeclarationContainer(node); - if (parent.kind === 228 && ts.isExternalModule(parent)) { + if (parent.kind === 230 && ts.isExternalModule(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)); } } @@ -15751,7 +17278,7 @@ var ts; if ((ts.getCombinedNodeFlags(node) & 12288) !== 0 || ts.isParameterDeclaration(node)) { return; } - if (node.kind === 199 && !node.initializer) { + if (node.kind === 201 && !node.initializer) { return; } var symbol = getSymbolOfNode(node); @@ -15761,25 +17288,25 @@ var ts; localDeclarationSymbol !== symbol && localDeclarationSymbol.flags & 2) { if (getDeclarationFlagsFromSymbol(localDeclarationSymbol) & 12288) { - var varDeclList = ts.getAncestor(localDeclarationSymbol.valueDeclaration, 200); - var container = varDeclList.parent.kind === 181 && varDeclList.parent.parent + var varDeclList = ts.getAncestor(localDeclarationSymbol.valueDeclaration, 202); + var container = varDeclList.parent.kind === 183 && varDeclList.parent.parent ? varDeclList.parent.parent : undefined; var namesShareScope = container && - (container.kind === 180 && ts.isFunctionLike(container.parent) || - container.kind === 207 || - container.kind === 206 || - container.kind === 228); + (container.kind === 182 && ts.isFunctionLike(container.parent) || + container.kind === 209 || + container.kind === 208 || + container.kind === 230); if (!namesShareScope) { - var name_9 = symbolToString(localDeclarationSymbol); - error(node, ts.Diagnostics.Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1, name_9, name_9); + var name_13 = symbolToString(localDeclarationSymbol); + error(node, ts.Diagnostics.Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1, name_13, name_13); } } } } } function checkParameterInitializer(node) { - if (ts.getRootDeclaration(node).kind !== 130) { + if (ts.getRootDeclaration(node).kind !== 131) { return; } var func = ts.getContainingFunction(node); @@ -15788,7 +17315,7 @@ var ts; if (n.kind === 65) { var referencedSymbol = getNodeLinks(n).resolvedSymbol; if (referencedSymbol && referencedSymbol !== unknownSymbol && getSymbol(func.locals, referencedSymbol.name, 107455) === referencedSymbol) { - if (referencedSymbol.valueDeclaration.kind === 130) { + if (referencedSymbol.valueDeclaration.kind === 131) { if (referencedSymbol.valueDeclaration === node) { error(n, ts.Diagnostics.Parameter_0_cannot_be_referenced_in_its_initializer, ts.declarationNameToString(node.name)); return; @@ -15806,10 +17333,9 @@ var ts; } } function checkVariableLikeDeclaration(node) { - checkGrammarDeclarationNameInStrictMode(node); checkDecorators(node); checkSourceElement(node.type); - if (node.name.kind === 128) { + if (node.name.kind === 129) { checkComputedPropertyName(node.name); if (node.initializer) { checkExpressionCached(node.initializer); @@ -15818,7 +17344,7 @@ var ts; if (ts.isBindingPattern(node.name)) { ts.forEach(node.name.elements, checkSourceElement); } - if (node.initializer && ts.getRootDeclaration(node).kind === 130 && ts.nodeIsMissing(ts.getContainingFunction(node).body)) { + if (node.initializer && ts.getRootDeclaration(node).kind === 131 && ts.nodeIsMissing(ts.getContainingFunction(node).body)) { error(node, ts.Diagnostics.A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation); return; } @@ -15846,9 +17372,9 @@ var ts; checkTypeAssignableTo(checkExpressionCached(node.initializer), declarationType, node, undefined); } } - if (node.kind !== 133 && node.kind !== 132) { + if (node.kind !== 134 && node.kind !== 133) { checkExportsOnMergedDeclarations(node); - if (node.kind === 199 || node.kind === 153) { + if (node.kind === 201 || node.kind === 155) { checkVarDeclaredNamesNotShadowed(node); } checkCollisionWithCapturedSuperVariable(node, node.name); @@ -15865,7 +17391,7 @@ var ts; return checkVariableLikeDeclaration(node); } function checkVariableStatement(node) { - checkGrammarDecorators(node) || checkGrammarDisallowedModifiersInBlockOrObjectLiteralExpression(node) || checkGrammarModifiers(node) || checkGrammarVariableDeclarationList(node.declarationList) || checkGrammarForDisallowedLetOrConstStatement(node); + checkGrammarDecorators(node) || checkGrammarModifiers(node) || checkGrammarVariableDeclarationList(node.declarationList) || checkGrammarForDisallowedLetOrConstStatement(node); ts.forEach(node.declarationList.declarations, checkSourceElement); } function checkGrammarDisallowedModifiersInBlockOrObjectLiteralExpression(node) { @@ -15877,7 +17403,7 @@ var ts; } function inBlockOrObjectLiteralExpression(node) { while (node) { - if (node.kind === 180 || node.kind === 155) { + if (node.kind === 182 || node.kind === 157) { return true; } node = node.parent; @@ -15905,12 +17431,12 @@ var ts; } function checkForStatement(node) { if (!checkGrammarStatementInAmbientContext(node)) { - if (node.initializer && node.initializer.kind == 200) { + if (node.initializer && node.initializer.kind === 202) { checkGrammarVariableDeclarationList(node.initializer); } } if (node.initializer) { - if (node.initializer.kind === 200) { + if (node.initializer.kind === 202) { ts.forEach(node.initializer.declarations, checkVariableDeclaration); } else { @@ -15925,13 +17451,13 @@ var ts; } function checkForOfStatement(node) { checkGrammarForInOrForOfStatement(node); - if (node.initializer.kind === 200) { + if (node.initializer.kind === 202) { checkForInOrForOfVariableDeclaration(node); } else { var varExpr = node.initializer; var iteratedType = checkRightHandSideOfForOf(node.expression); - if (varExpr.kind === 154 || varExpr.kind === 155) { + if (varExpr.kind === 156 || varExpr.kind === 157) { checkDestructuringAssignment(varExpr, iteratedType || unknownType); } else { @@ -15946,7 +17472,7 @@ var ts; } function checkForInStatement(node) { checkGrammarForInOrForOfStatement(node); - if (node.initializer.kind === 200) { + if (node.initializer.kind === 202) { 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); @@ -15956,10 +17482,10 @@ var ts; else { var varExpr = node.initializer; var leftType = checkExpression(varExpr); - if (varExpr.kind === 154 || varExpr.kind === 155) { + if (varExpr.kind === 156 || varExpr.kind === 157) { error(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern); } - else if (!allConstituentTypesHaveKind(leftType, 1 | 258)) { + else if (!isTypeAnyOrAllConstituentTypesHaveKind(leftType, 258)) { error(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any); } else { @@ -15967,7 +17493,7 @@ var ts; } } var rightType = checkExpression(node.expression); - if (!allConstituentTypesHaveKind(rightType, 1 | 48128 | 512)) { + if (!isTypeAnyOrAllConstituentTypesHaveKind(rightType, 48128 | 512)) { 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); @@ -15984,11 +17510,11 @@ var ts; return checkIteratedTypeOrElementType(expressionType, rhsExpression, true); } function checkIteratedTypeOrElementType(inputType, errorNode, allowStringInput) { - if (inputType.flags & 1) { + if (isTypeAny(inputType)) { return inputType; } if (languageVersion >= 2) { - return checkIteratedType(inputType, errorNode) || anyType; + return checkElementTypeOfIterable(inputType, errorNode); } if (allowStringInput) { return checkElementTypeOfArrayOrString(inputType, errorNode); @@ -16002,84 +17528,85 @@ var ts; error(errorNode, ts.Diagnostics.Type_0_is_not_an_array_type, typeToString(inputType)); return unknownType; } - function checkIteratedType(iterable, errorNode) { - ts.Debug.assert(languageVersion >= 2); - var iteratedType = getIteratedType(iterable, errorNode); - if (errorNode && iteratedType) { - checkTypeAssignableTo(iterable, createIterableType(iteratedType), errorNode); + function checkElementTypeOfIterable(iterable, errorNode) { + var elementType = getElementTypeOfIterable(iterable, errorNode); + if (errorNode && elementType) { + checkTypeAssignableTo(iterable, createIterableType(elementType), errorNode); } - return iteratedType; - function getIteratedType(iterable, errorNode) { - // 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]: { // iteratorFunction - // (): { // iterator - // next: { // iteratorNextFunction - // (): { // iteratorNextResult - // value: T // iteratorNextValue - // } - // } - // } - // } - // } - // - // 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'. - if (allConstituentTypesHaveKind(iterable, 1)) { - return undefined; - } - if ((iterable.flags & 4096) && iterable.target === globalIterableType) { - return iterable.typeArguments[0]; - } - var iteratorFunction = getTypeOfPropertyOfType(iterable, ts.getPropertyNameForKnownSymbolName("iterator")); - if (iteratorFunction && allConstituentTypesHaveKind(iteratorFunction, 1)) { - return undefined; - } - var iteratorFunctionSignatures = iteratorFunction ? getSignaturesOfType(iteratorFunction, 0) : emptyArray; - if (iteratorFunctionSignatures.length === 0) { - if (errorNode) { - error(errorNode, ts.Diagnostics.Type_must_have_a_Symbol_iterator_method_that_returns_an_iterator); - } - return undefined; - } - var iterator = getUnionType(ts.map(iteratorFunctionSignatures, getReturnTypeOfSignature)); - if (allConstituentTypesHaveKind(iterator, 1)) { - return undefined; - } - var iteratorNextFunction = getTypeOfPropertyOfType(iterator, "next"); - if (iteratorNextFunction && allConstituentTypesHaveKind(iteratorNextFunction, 1)) { - return undefined; - } - var iteratorNextFunctionSignatures = iteratorNextFunction ? getSignaturesOfType(iteratorNextFunction, 0) : emptyArray; - if (iteratorNextFunctionSignatures.length === 0) { - if (errorNode) { - error(errorNode, ts.Diagnostics.An_iterator_must_have_a_next_method); - } - return undefined; - } - var iteratorNextResult = getUnionType(ts.map(iteratorNextFunctionSignatures, getReturnTypeOfSignature)); - if (allConstituentTypesHaveKind(iteratorNextResult, 1)) { - return undefined; - } - var iteratorNextValue = getTypeOfPropertyOfType(iteratorNextResult, "value"); - if (!iteratorNextValue) { - if (errorNode) { - error(errorNode, ts.Diagnostics.The_type_returned_by_the_next_method_of_an_iterator_must_have_a_value_property); - } - return undefined; - } - return iteratorNextValue; + return elementType || anyType; + } + function getElementTypeOfIterable(type, errorNode) { + if (isTypeAny(type)) { + return undefined; } + var typeAsIterable = type; + if (!typeAsIterable.iterableElementType) { + if ((type.flags & 4096) && type.target === globalIterableType) { + typeAsIterable.iterableElementType = type.typeArguments[0]; + } + else { + var iteratorFunction = getTypeOfPropertyOfType(type, ts.getPropertyNameForKnownSymbolName("iterator")); + if (isTypeAny(iteratorFunction)) { + return undefined; + } + var iteratorFunctionSignatures = iteratorFunction ? getSignaturesOfType(iteratorFunction, 0) : emptyArray; + if (iteratorFunctionSignatures.length === 0) { + if (errorNode) { + error(errorNode, ts.Diagnostics.Type_must_have_a_Symbol_iterator_method_that_returns_an_iterator); + } + return undefined; + } + typeAsIterable.iterableElementType = getElementTypeOfIterator(getUnionType(ts.map(iteratorFunctionSignatures, getReturnTypeOfSignature)), errorNode); + } + } + return typeAsIterable.iterableElementType; + } + function getElementTypeOfIterator(type, errorNode) { + if (isTypeAny(type)) { + return undefined; + } + var typeAsIterator = type; + if (!typeAsIterator.iteratorElementType) { + if ((type.flags & 4096) && type.target === globalIteratorType) { + typeAsIterator.iteratorElementType = type.typeArguments[0]; + } + else { + var iteratorNextFunction = getTypeOfPropertyOfType(type, "next"); + if (isTypeAny(iteratorNextFunction)) { + return undefined; + } + var iteratorNextFunctionSignatures = iteratorNextFunction ? getSignaturesOfType(iteratorNextFunction, 0) : emptyArray; + if (iteratorNextFunctionSignatures.length === 0) { + if (errorNode) { + error(errorNode, ts.Diagnostics.An_iterator_must_have_a_next_method); + } + return undefined; + } + var iteratorNextResult = getUnionType(ts.map(iteratorNextFunctionSignatures, getReturnTypeOfSignature)); + if (isTypeAny(iteratorNextResult)) { + return undefined; + } + var iteratorNextValue = getTypeOfPropertyOfType(iteratorNextResult, "value"); + if (!iteratorNextValue) { + if (errorNode) { + error(errorNode, ts.Diagnostics.The_type_returned_by_the_next_method_of_an_iterator_must_have_a_value_property); + } + return undefined; + } + typeAsIterator.iteratorElementType = iteratorNextValue; + } + } + return typeAsIterator.iteratorElementType; + } + function getElementTypeOfIterableIterator(type) { + if (isTypeAny(type)) { + return undefined; + } + if ((type.flags & 4096) && type.target === globalIterableIteratorType) { + return type.typeArguments[0]; + } + return getElementTypeOfIterable(type, undefined) || + getElementTypeOfIterator(type, undefined); } function checkElementTypeOfArrayOrString(arrayOrStringType, errorNode) { ts.Debug.assert(languageVersion < 2); @@ -16117,7 +17644,7 @@ var ts; checkGrammarStatementInAmbientContext(node) || checkGrammarBreakOrContinueStatement(node); } function isGetAccessorWithAnnotatatedSetAccessor(node) { - return !!(node.kind === 137 && getSetAccessorTypeAnnotationNode(ts.getDeclarationOfKind(node.symbol, 138))); + return !!(node.kind === 138 && getSetAccessorTypeAnnotationNode(ts.getDeclarationOfKind(node.symbol, 139))); } function checkReturnStatement(node) { if (!checkGrammarStatementInAmbientContext(node)) { @@ -16129,30 +17656,28 @@ var ts; if (node.expression) { var func = ts.getContainingFunction(node); if (func) { - var returnType = getReturnTypeOfSignature(getSignatureFromDeclaration(func)); + var signature = getSignatureFromDeclaration(func); + var returnType = getReturnTypeOfSignature(signature); var exprType = checkExpressionCached(node.expression); - if (func.kind === 138) { + if (func.asteriskToken) { + return; + } + if (func.kind === 139) { error(node.expression, ts.Diagnostics.Setters_cannot_return_a_value); } - else { - if (func.kind === 136) { - if (!isTypeAssignableTo(exprType, returnType)) { - error(node.expression, ts.Diagnostics.Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class); - } - } - else if (func.type || isGetAccessorWithAnnotatatedSetAccessor(func)) { - checkTypeAssignableTo(exprType, returnType, node.expression, undefined); + else if (func.kind === 137) { + if (!isTypeAssignableTo(exprType, returnType)) { + error(node.expression, ts.Diagnostics.Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class); } } + else if (func.type || isGetAccessorWithAnnotatatedSetAccessor(func) || signature.typePredicate) { + checkTypeAssignableTo(exprType, returnType, node.expression, undefined); + } } } } function checkWithStatement(node) { - if (!checkGrammarStatementInAmbientContext(node)) { - if (node.parserContextFlags & 1) { - grammarErrorOnFirstToken(node, ts.Diagnostics.with_statements_are_not_allowed_in_strict_mode); - } - } + checkGrammarStatementInAmbientContext(node); checkExpression(node.expression); error(node.expression, ts.Diagnostics.All_symbols_within_a_with_block_will_be_resolved_to_any); } @@ -16162,7 +17687,7 @@ var ts; var hasDuplicateDefaultClause = false; var expressionType = checkExpression(node.expression); ts.forEach(node.caseBlock.clauses, function (clause) { - if (clause.kind === 222 && !hasDuplicateDefaultClause) { + if (clause.kind === 224 && !hasDuplicateDefaultClause) { if (firstDefaultClause === undefined) { firstDefaultClause = clause; } @@ -16174,7 +17699,7 @@ var ts; hasDuplicateDefaultClause = true; } } - if (produceDiagnostics && clause.kind === 221) { + if (produceDiagnostics && clause.kind === 223) { var caseClause = clause; var caseType = checkExpression(caseClause.expression); if (!isTypeAssignableTo(expressionType, caseType)) { @@ -16191,7 +17716,7 @@ var ts; if (ts.isFunctionLike(current)) { break; } - if (current.kind === 195 && current.label.text === node.label.text) { + if (current.kind === 197 && 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)); break; @@ -16235,7 +17760,6 @@ var ts; grammarErrorOnNode(localSymbol.valueDeclaration, ts.Diagnostics.Cannot_redeclare_identifier_0_in_catch_clause, identifierName); } } - checkGrammarEvalOrArgumentsInStrictMode(node, catchClause.variableDeclaration.name); } } checkBlock(catchClause.block); @@ -16255,7 +17779,7 @@ var ts; checkIndexConstraintForProperty(prop, propType, type, declaredStringIndexer, stringIndexType, 0); checkIndexConstraintForProperty(prop, propType, type, declaredNumberIndexer, numberIndexType, 1); }); - if (type.flags & 1024 && type.symbol.valueDeclaration.kind === 202) { + if (type.flags & 1024 && type.symbol.valueDeclaration.kind === 204) { var classDeclaration = type.symbol.valueDeclaration; for (var _i = 0, _a = classDeclaration.members; _i < _a.length; _i++) { var member = _a[_i]; @@ -16286,7 +17810,7 @@ var ts; return; } var errorNode; - if (prop.valueDeclaration.name.kind === 128 || prop.parent === containingType.symbol) { + if (prop.valueDeclaration.name.kind === 129 || prop.parent === containingType.symbol) { errorNode = prop.valueDeclaration; } else if (indexDeclaration) { @@ -16336,10 +17860,6 @@ var ts; return unknownType; } function checkClassDeclaration(node) { - checkGrammarDeclarationNameInStrictMode(node); - if (node.parent.kind !== 207 && node.parent.kind !== 228) { - grammarErrorOnNode(node, ts.Diagnostics.class_declarations_are_only_supported_directly_inside_a_module_or_as_a_top_level_declaration); - } if (!node.name && !(node.flags & 256)) { grammarErrorOnFirstToken(node, ts.Diagnostics.A_class_declaration_without_the_default_modifier_must_have_a_name); } @@ -16357,35 +17877,38 @@ var ts; var staticType = getTypeOfSymbol(symbol); var baseTypeNode = ts.getClassExtendsHeritageClauseElement(node); if (baseTypeNode) { - if (!ts.isSupportedExpressionWithTypeArguments(baseTypeNode)) { - error(baseTypeNode.expression, ts.Diagnostics.Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_class_extends_clauses); - } emitExtends = emitExtends || !ts.isInAmbientContext(node); - checkExpressionWithTypeArguments(baseTypeNode); - } - var baseTypes = getBaseTypes(type); - if (baseTypes.length) { - if (produceDiagnostics) { + var baseTypes = getBaseTypes(type); + if (baseTypes.length && produceDiagnostics) { var baseType = baseTypes[0]; + var staticBaseType = getBaseConstructorTypeOfClass(type); + if (baseTypeNode.typeArguments) { + ts.forEach(baseTypeNode.typeArguments, checkSourceElement); + for (var _i = 0, _a = getConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments); _i < _a.length; _i++) { + var constructor = _a[_i]; + if (!checkTypeArgumentConstraints(constructor.typeParameters, baseTypeNode.typeArguments)) { + break; + } + } + } checkTypeAssignableTo(type, baseType, node.name || node, ts.Diagnostics.Class_0_incorrectly_extends_base_class_1); - var staticBaseType = getTypeOfSymbol(baseType.symbol); - checkTypeAssignableTo(staticType, getTypeWithoutConstructors(staticBaseType), node.name || node, ts.Diagnostics.Class_static_side_0_incorrectly_extends_base_class_static_side_1); - if (baseType.symbol !== resolveEntityName(baseTypeNode.expression, 107455)) { - error(baseTypeNode, ts.Diagnostics.Type_name_0_in_extends_clause_does_not_reference_constructor_function_for_0, typeToString(baseType)); + checkTypeAssignableTo(staticType, getTypeWithoutSignatures(staticBaseType), node.name || node, ts.Diagnostics.Class_static_side_0_incorrectly_extends_base_class_static_side_1); + if (!(staticBaseType.symbol && staticBaseType.symbol.flags & 32)) { + var constructors = getInstantiatedConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments); + if (ts.forEach(constructors, function (sig) { return getReturnTypeOfSignature(sig) !== baseType; })) { + error(baseTypeNode.expression, ts.Diagnostics.Base_constructors_must_all_have_the_same_return_type); + } } checkKindsOfPropertyMemberOverrides(type, baseType); } } - if (baseTypes.length || (baseTypeNode && compilerOptions.separateCompilation)) { - checkExpressionOrQualifiedName(baseTypeNode.expression); - } var implementedTypeNodes = ts.getClassImplementsHeritageClauseElements(node); if (implementedTypeNodes) { ts.forEach(implementedTypeNodes, function (typeRefNode) { if (!ts.isSupportedExpressionWithTypeArguments(typeRefNode)) { error(typeRefNode.expression, ts.Diagnostics.A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments); } - checkExpressionWithTypeArguments(typeRefNode); + checkTypeReferenceNode(typeRefNode); if (produceDiagnostics) { var t = getTypeFromTypeNode(typeRefNode); if (t !== unknownType) { @@ -16467,7 +17990,7 @@ var ts; } } function isAccessor(kind) { - return kind === 137 || kind === 138; + return kind === 138 || kind === 139; } function areTypeParametersIdentical(list1, list2) { if (!list1 && !list2) { @@ -16527,13 +18050,13 @@ var ts; return ok; } function checkInterfaceDeclaration(node) { - checkGrammarDeclarationNameInStrictMode(node) || checkGrammarDecorators(node) || checkGrammarModifiers(node) || checkGrammarInterfaceDeclaration(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); - var firstInterfaceDecl = ts.getDeclarationOfKind(symbol, 203); + var firstInterfaceDecl = ts.getDeclarationOfKind(symbol, 205); if (symbol.declarations.length > 1) { if (node !== firstInterfaceDecl && !areTypeParametersIdentical(firstInterfaceDecl.typeParameters, node.typeParameters)) { error(node.name, ts.Diagnostics.All_declarations_of_an_interface_must_have_identical_type_parameters); @@ -16553,7 +18076,7 @@ var ts; if (!ts.isSupportedExpressionWithTypeArguments(heritageElement)) { error(heritageElement.expression, ts.Diagnostics.An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments); } - checkExpressionWithTypeArguments(heritageElement); + checkTypeReferenceNode(heritageElement); }); ts.forEach(node.members, checkSourceElement); if (produceDiagnostics) { @@ -16574,7 +18097,7 @@ var ts; var ambient = ts.isInAmbientContext(node); var enumIsConst = ts.isConst(node); ts.forEach(node.members, function (member) { - if (member.name.kind !== 128 && isNumericLiteralName(member.name.text)) { + if (member.name.kind !== 129 && isNumericLiteralName(member.name.text)) { error(member.name, ts.Diagnostics.An_enum_member_cannot_have_a_numeric_name); } var initializer = member.initializer; @@ -16610,7 +18133,7 @@ var ts; return evalConstant(initializer); function evalConstant(e) { switch (e.kind) { - case 168: + case 170: var value = evalConstant(e.operand); if (value === undefined) { return undefined; @@ -16621,7 +18144,7 @@ var ts; case 47: return ~value; } return undefined; - case 170: + case 172: var left = evalConstant(e.left); if (left === undefined) { return undefined; @@ -16646,11 +18169,11 @@ var ts; return undefined; case 7: return +e.text; - case 162: + case 164: return evalConstant(e.expression); case 65: - case 157: - case 156: + case 159: + case 158: var member = initializer.parent; var currentType = getTypeOfSymbol(getSymbolOfNode(member.parent)); var enumType; @@ -16661,7 +18184,7 @@ var ts; } else { var expression; - if (e.kind === 157) { + if (e.kind === 159) { if (e.argumentExpression === undefined || e.argumentExpression.kind !== 8) { return undefined; @@ -16678,7 +18201,7 @@ var ts; if (current.kind === 65) { break; } - else if (current.kind === 156) { + else if (current.kind === 158) { current = current.expression; } else { @@ -16713,15 +18236,15 @@ var ts; if (!produceDiagnostics) { return; } - checkGrammarDeclarationNameInStrictMode(node) || checkGrammarDecorators(node) || checkGrammarModifiers(node) || checkGrammarEnumDeclaration(node); + checkGrammarDecorators(node) || checkGrammarModifiers(node) || checkGrammarEnumDeclaration(node); checkTypeNameIsReserved(node.name, ts.Diagnostics.Enum_name_cannot_be_0); checkCollisionWithCapturedThisVariable(node, node.name); checkCollisionWithRequireExportsInGeneratedCode(node, node.name); checkExportsOnMergedDeclarations(node); computeEnumMemberValues(node); var enumIsConst = ts.isConst(node); - if (compilerOptions.separateCompilation && enumIsConst && ts.isInAmbientContext(node)) { - error(node.name, ts.Diagnostics.Ambient_const_enums_are_not_allowed_when_the_separateCompilation_flag_is_provided); + 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); @@ -16735,7 +18258,7 @@ var ts; } var seenEnumMissingInitialInitializer = false; ts.forEach(enumSymbol.declarations, function (declaration) { - if (declaration.kind !== 205) { + if (declaration.kind !== 207) { return false; } var enumDeclaration = declaration; @@ -16758,8 +18281,8 @@ var ts; var declarations = symbol.declarations; for (var _i = 0; _i < declarations.length; _i++) { var declaration = declarations[_i]; - if ((declaration.kind === 202 || - (declaration.kind === 201 && ts.nodeIsPresent(declaration.body))) && + if ((declaration.kind === 204 || + (declaration.kind === 203 && ts.nodeIsPresent(declaration.body))) && !ts.isInAmbientContext(declaration)) { return declaration; } @@ -16781,7 +18304,14 @@ var ts; } function checkModuleDeclaration(node) { if (produceDiagnostics) { - if (!checkGrammarDeclarationNameInStrictMode(node) && !checkGrammarDecorators(node) && !checkGrammarModifiers(node)) { + var isAmbientExternalModule = node.name.kind === 8; + 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 (!ts.isInAmbientContext(node) && node.name.kind === 8) { grammarErrorOnNode(node.name, ts.Diagnostics.Only_ambient_modules_can_use_quoted_names); } @@ -16793,7 +18323,7 @@ var ts; if (symbol.flags & 512 && symbol.declarations.length > 1 && !ts.isInAmbientContext(node) - && ts.isInstantiatedModule(node, compilerOptions.preserveConstEnums || compilerOptions.separateCompilation)) { + && ts.isInstantiatedModule(node, compilerOptions.preserveConstEnums || compilerOptions.isolatedModules)) { var firstNonAmbientClassOrFunc = getFirstNonAmbientClassOrFunctionDeclaration(symbol); if (firstNonAmbientClassOrFunc) { if (ts.getSourceFileOfNode(node) !== ts.getSourceFileOfNode(firstNonAmbientClassOrFunc)) { @@ -16803,13 +18333,13 @@ var ts; 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, 202); + var mergedClass = ts.getDeclarationOfKind(symbol, 204); if (mergedClass && inSameLexicalScope(node, mergedClass)) { getNodeLinks(node).flags |= 2048; } } - if (node.name.kind === 8) { + if (isAmbientExternalModule) { if (!isGlobalSourceFile(node.parent)) { error(node.name, ts.Diagnostics.Ambient_modules_cannot_be_nested_in_other_modules); } @@ -16822,10 +18352,10 @@ var ts; } function getFirstIdentifier(node) { while (true) { - if (node.kind === 127) { + if (node.kind === 128) { node = node.left; } - else if (node.kind === 156) { + else if (node.kind === 158) { node = node.expression; } else { @@ -16841,9 +18371,9 @@ var ts; error(moduleName, ts.Diagnostics.String_literal_expected); return false; } - var inAmbientExternalModule = node.parent.kind === 207 && node.parent.parent.name.kind === 8; - if (node.parent.kind !== 228 && !inAmbientExternalModule) { - error(moduleName, node.kind === 216 ? + var inAmbientExternalModule = node.parent.kind === 209 && node.parent.parent.name.kind === 8; + if (node.parent.kind !== 230 && !inAmbientExternalModule) { + error(moduleName, node.kind === 218 ? ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace : ts.Diagnostics.Import_declarations_in_a_namespace_cannot_reference_a_module); return false; @@ -16862,7 +18392,7 @@ var ts; (symbol.flags & 793056 ? 793056 : 0) | (symbol.flags & 1536 ? 1536 : 0); if (target.flags & excludedMeanings) { - var message = node.kind === 218 ? + var message = node.kind === 220 ? 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)); @@ -16875,7 +18405,10 @@ var ts; checkAliasSymbol(node); } function checkImportDeclaration(node) { - if (!checkGrammarImportDeclarationNameInStrictMode(node) && !checkGrammarDecorators(node) && !checkGrammarModifiers(node) && (node.flags & 499)) { + if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_import_declaration_can_only_be_used_in_a_namespace_or_module)) { + return; + } + if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && (node.flags & 499)) { grammarErrorOnFirstToken(node, ts.Diagnostics.An_import_declaration_cannot_have_modifiers); } if (checkExternalImportOrExportDeclaration(node)) { @@ -16885,7 +18418,7 @@ var ts; checkImportBinding(importClause); } if (importClause.namedBindings) { - if (importClause.namedBindings.kind === 212) { + if (importClause.namedBindings.kind === 214) { checkImportBinding(importClause.namedBindings); } else { @@ -16896,7 +18429,10 @@ var ts; } } function checkImportEqualsDeclaration(node) { - checkGrammarDeclarationNameInStrictMode(node) || checkGrammarDecorators(node) || checkGrammarModifiers(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 (node.flags & 1) { @@ -16924,14 +18460,17 @@ var ts; } } function checkExportDeclaration(node) { + if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_export_declaration_can_only_be_used_in_a_module)) { + return; + } if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && (node.flags & 499)) { 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 === 207 && node.parent.parent.name.kind === 8; - if (node.parent.kind !== 228 && !inAmbientExternalModule) { + var inAmbientExternalModule = node.parent.kind === 209 && node.parent.parent.name.kind === 8; + if (node.parent.kind !== 230 && !inAmbientExternalModule) { error(node, ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace); } } @@ -16943,6 +18482,11 @@ var ts; } } } + function checkGrammarModuleElementContext(node, errorMessage) { + if (node.parent.kind !== 230 && node.parent.kind !== 209 && node.parent.kind !== 208) { + return grammarErrorOnFirstToken(node, errorMessage); + } + } function checkExportSpecifier(node) { checkAliasSymbol(node); if (!node.parent.parent.moduleSpecifier) { @@ -16950,8 +18494,11 @@ var ts; } } function checkExportAssignment(node) { - var container = node.parent.kind === 228 ? node.parent : node.parent.parent; - if (container.kind === 206 && container.name.kind === 65) { + if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_export_assignment_can_only_be_used_in_a_module)) { + return; + } + var container = node.parent.kind === 230 ? node.parent : node.parent.parent; + if (container.kind === 208 && container.name.kind === 65) { error(node, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_namespace); return; } @@ -16975,10 +18522,10 @@ var ts; } } function getModuleStatements(node) { - if (node.kind === 228) { + if (node.kind === 230) { return node.statements; } - if (node.kind === 206 && node.body.kind === 207) { + if (node.kind === 208 && node.body.kind === 209) { return node.body.statements; } return emptyArray; @@ -17003,168 +18550,175 @@ var ts; links.exportsChecked = true; } } + function checkTypePredicate(node) { + if (!isInLegalTypePredicatePosition(node)) { + error(node, ts.Diagnostics.A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods); + } + } function checkSourceElement(node) { if (!node) return; switch (node.kind) { - case 129: - return checkTypeParameter(node); case 130: + return checkTypeParameter(node); + case 131: return checkParameter(node); + case 134: case 133: - case 132: return checkPropertyDeclaration(node); - case 143: - case 144: - case 139: + case 145: + case 146: case 140: - return checkSignatureDeclaration(node); case 141: return checkSignatureDeclaration(node); - case 135: - case 134: - return checkMethodDeclaration(node); - case 136: - return checkConstructorDeclaration(node); - case 137: - case 138: - return checkAccessorDeclaration(node); case 142: + return checkSignatureDeclaration(node); + case 136: + case 135: + return checkMethodDeclaration(node); + case 137: + return checkConstructorDeclaration(node); + case 138: + case 139: + return checkAccessorDeclaration(node); + case 144: return checkTypeReferenceNode(node); - case 145: - return checkTypeQuery(node); - case 146: - return checkTypeLiteral(node); + case 143: + return checkTypePredicate(node); case 147: - return checkArrayType(node); + return checkTypeQuery(node); case 148: - return checkTupleType(node); + return checkTypeLiteral(node); case 149: - return checkUnionType(node); + return checkArrayType(node); case 150: + return checkTupleType(node); + case 151: + return checkUnionType(node); + case 152: return checkSourceElement(node.type); - case 201: - return checkFunctionDeclaration(node); - case 180: - case 207: - return checkBlock(node); - case 181: - return checkVariableStatement(node); - case 183: - return checkExpressionStatement(node); - case 184: - return checkIfStatement(node); - case 185: - return checkDoStatement(node); - case 186: - return checkWhileStatement(node); - case 187: - return checkForStatement(node); - case 188: - return checkForInStatement(node); - case 189: - return checkForOfStatement(node); - case 190: - case 191: - return checkBreakOrContinueStatement(node); - case 192: - return checkReturnStatement(node); - case 193: - return checkWithStatement(node); - case 194: - return checkSwitchStatement(node); - case 195: - return checkLabeledStatement(node); - case 196: - return checkThrowStatement(node); - case 197: - return checkTryStatement(node); - case 199: - return checkVariableDeclaration(node); - case 153: - return checkBindingElement(node); - case 202: - return checkClassDeclaration(node); case 203: - return checkInterfaceDeclaration(node); - case 204: - return checkTypeAliasDeclaration(node); - case 205: - return checkEnumDeclaration(node); - case 206: - return checkModuleDeclaration(node); - case 210: - return checkImportDeclaration(node); - case 209: - return checkImportEqualsDeclaration(node); - case 216: - return checkExportDeclaration(node); - case 215: - return checkExportAssignment(node); + return checkFunctionDeclaration(node); case 182: - checkGrammarStatementInAmbientContext(node); - return; + case 209: + return checkBlock(node); + case 183: + return checkVariableStatement(node); + case 185: + return checkExpressionStatement(node); + case 186: + return checkIfStatement(node); + case 187: + return checkDoStatement(node); + case 188: + return checkWhileStatement(node); + case 189: + return checkForStatement(node); + case 190: + return checkForInStatement(node); + case 191: + return checkForOfStatement(node); + case 192: + case 193: + return checkBreakOrContinueStatement(node); + case 194: + return checkReturnStatement(node); + case 195: + return checkWithStatement(node); + case 196: + return checkSwitchStatement(node); + case 197: + return checkLabeledStatement(node); case 198: + return checkThrowStatement(node); + case 199: + return checkTryStatement(node); + case 201: + return checkVariableDeclaration(node); + case 155: + return checkBindingElement(node); + case 204: + return checkClassDeclaration(node); + case 205: + return checkInterfaceDeclaration(node); + case 206: + return checkTypeAliasDeclaration(node); + case 207: + return checkEnumDeclaration(node); + case 208: + return checkModuleDeclaration(node); + case 212: + return checkImportDeclaration(node); + case 211: + return checkImportEqualsDeclaration(node); + case 218: + return checkExportDeclaration(node); + case 217: + return checkExportAssignment(node); + case 184: checkGrammarStatementInAmbientContext(node); return; - case 219: + case 200: + checkGrammarStatementInAmbientContext(node); + return; + case 221: return checkMissingDeclaration(node); } } function checkFunctionExpressionBodies(node) { switch (node.kind) { - case 163: - case 164: + case 165: + case 166: ts.forEach(node.parameters, checkFunctionExpressionBodies); checkFunctionExpressionOrObjectLiteralMethodBody(node); break; + case 136: case 135: - case 134: + ts.forEach(node.decorators, checkFunctionExpressionBodies); ts.forEach(node.parameters, checkFunctionExpressionBodies); if (ts.isObjectLiteralMethod(node)) { checkFunctionExpressionOrObjectLiteralMethodBody(node); } break; - case 136: case 137: case 138: - case 201: + case 139: + case 203: ts.forEach(node.parameters, checkFunctionExpressionBodies); break; - case 193: + case 195: checkFunctionExpressionBodies(node.expression); break; - case 130: - case 133: case 132: - case 151: - case 152: + case 131: + case 134: + case 133: case 153: case 154: case 155: - case 225: case 156: case 157: + case 227: case 158: case 159: case 160: - case 172: - case 178: case 161: case 162: - case 166: - case 167: - case 165: - case 168: - case 169: - case 170: - case 171: case 174: case 180: - case 207: - case 181: + case 163: + case 164: + case 168: + case 169: + case 167: + case 170: + case 171: + case 172: + case 173: + case 176: + case 182: + case 209: case 183: - case 184: case 185: case 186: case 187: @@ -17173,21 +18727,23 @@ var ts; case 190: case 191: case 192: + case 193: case 194: - case 208: - case 221: - case 222: - case 195: case 196: - case 197: + case 210: + case 223: case 224: + case 197: + case 198: case 199: - case 200: + case 226: + case 201: case 202: - case 205: - case 227: - case 215: - case 228: + case 204: + case 207: + case 229: + case 217: + case 230: ts.forEachChild(node, checkFunctionExpressionBodies); break; } @@ -17200,6 +18756,9 @@ var ts; function checkSourceFileWorker(node) { var links = getNodeLinks(node); if (!(links.flags & 1)) { + if (node.isDefaultLib && compilerOptions.skipDefaultLibCheck) { + return; + } checkGrammarSourceFile(node); emitExtends = false; emitDecorate = false; @@ -17247,7 +18806,7 @@ var ts; function isInsideWithStatementBody(node) { if (node) { while (node.parent) { - if (node.parent.kind === 193 && node.parent.statement === node) { + if (node.parent.kind === 195 && node.parent.statement === node) { return true; } node = node.parent; @@ -17269,23 +18828,23 @@ var ts; copySymbols(location.locals, meaning); } switch (location.kind) { - case 228: + case 230: if (!ts.isExternalModule(location)) { break; } - case 206: + case 208: copySymbols(getSymbolOfNode(location).exports, meaning & 8914931); break; - case 205: + case 207: copySymbols(getSymbolOfNode(location).exports, meaning & 8); break; - case 202: - case 203: + case 204: + case 205: if (!(memberFlags & 128)) { copySymbols(getSymbolOfNode(location).members, meaning & 793056); } break; - case 163: + case 165: if (location.name) { copySymbol(location.symbol, meaning); } @@ -17321,22 +18880,22 @@ var ts; copySymbols(location.locals, meaning); } switch (location.kind) { - case 228: + case 230: if (!ts.isExternalModule(location)) break; - case 206: + case 208: copySymbols(getSymbolOfNode(location).exports, meaning & 8914931); break; - case 205: + case 207: copySymbols(getSymbolOfNode(location).exports, meaning & 8); break; - case 202: - case 203: + case 204: + case 205: if (!(memberFlags & 128)) { copySymbols(getSymbolOfNode(location).members, meaning & 793056); } break; - case 163: + case 165: if (location.name) { copySymbol(location.symbol, meaning); } @@ -17349,110 +18908,42 @@ var ts; return symbolsToArray(symbols); } function isTypeDeclarationName(name) { - return name.kind == 65 && + return name.kind === 65 && isTypeDeclaration(name.parent) && name.parent.name === name; } function isTypeDeclaration(node) { switch (node.kind) { - case 129: - case 202: - case 203: + case 130: case 204: case 205: + case 206: + case 207: return true; } } function isTypeReferenceIdentifier(entityName) { var node = entityName; - while (node.parent && node.parent.kind === 127) { + while (node.parent && node.parent.kind === 128) { node = node.parent; } - return node.parent && node.parent.kind === 142; + return node.parent && node.parent.kind === 144; } function isHeritageClauseElementIdentifier(entityName) { var node = entityName; - while (node.parent && node.parent.kind === 156) { + while (node.parent && node.parent.kind === 158) { node = node.parent; } - return node.parent && node.parent.kind === 177; - } - function isTypeNode(node) { - if (142 <= node.kind && node.kind <= 150) { - return true; - } - switch (node.kind) { - case 112: - case 120: - case 122: - case 113: - case 123: - return true; - case 99: - return node.parent.kind !== 167; - case 8: - return node.parent.kind === 130; - case 177: - return true; - case 65: - if (node.parent.kind === 127 && node.parent.right === node) { - node = node.parent; - } - else if (node.parent.kind === 156 && node.parent.name === node) { - node = node.parent; - } - case 127: - case 156: - ts.Debug.assert(node.kind === 65 || node.kind === 127 || node.kind === 156, "'node' was expected to be a qualified name, identifier or property access in 'isTypeNode'."); - var parent_5 = node.parent; - if (parent_5.kind === 145) { - return false; - } - if (142 <= parent_5.kind && parent_5.kind <= 150) { - return true; - } - switch (parent_5.kind) { - case 177: - return true; - case 129: - return node === parent_5.constraint; - case 133: - case 132: - case 130: - case 199: - return node === parent_5.type; - case 201: - case 163: - case 164: - case 136: - case 135: - case 134: - case 137: - case 138: - return node === parent_5.type; - case 139: - case 140: - case 141: - return node === parent_5.type; - case 161: - return node === parent_5.type; - case 158: - case 159: - return parent_5.typeArguments && ts.indexOf(parent_5.typeArguments, node) >= 0; - case 160: - return false; - } - } - return false; + return node.parent && node.parent.kind === 179; } function getLeftSideOfImportEqualsOrExportAssignment(nodeOnRightSide) { - while (nodeOnRightSide.parent.kind === 127) { + while (nodeOnRightSide.parent.kind === 128) { nodeOnRightSide = nodeOnRightSide.parent; } - if (nodeOnRightSide.parent.kind === 209) { + if (nodeOnRightSide.parent.kind === 211) { return nodeOnRightSide.parent.moduleReference === nodeOnRightSide && nodeOnRightSide.parent; } - if (nodeOnRightSide.parent.kind === 215) { + if (nodeOnRightSide.parent.kind === 217) { return nodeOnRightSide.parent.expression === nodeOnRightSide && nodeOnRightSide.parent; } return undefined; @@ -17464,10 +18955,10 @@ var ts; if (ts.isDeclarationName(entityName)) { return getSymbolOfNode(entityName.parent); } - if (entityName.parent.kind === 215) { + if (entityName.parent.kind === 217) { return resolveEntityName(entityName, 107455 | 793056 | 1536 | 8388608); } - if (entityName.kind !== 156) { + if (entityName.kind !== 158) { if (isInRightSideOfImportOrExportAssignment(entityName)) { return getSymbolOfPartOfRightHandSideOfImportEquals(entityName); } @@ -17476,7 +18967,7 @@ var ts; entityName = entityName.parent; } if (isHeritageClauseElementIdentifier(entityName)) { - var meaning = entityName.parent.kind === 177 ? 793056 : 1536; + var meaning = entityName.parent.kind === 179 ? 793056 : 1536; meaning |= 8388608; return resolveEntityName(entityName, meaning); } @@ -17488,14 +18979,14 @@ var ts; var meaning = 107455 | 8388608; return resolveEntityName(entityName, meaning); } - else if (entityName.kind === 156) { + else if (entityName.kind === 158) { var symbol = getNodeLinks(entityName).resolvedSymbol; if (!symbol) { checkPropertyAccessExpression(entityName); } return getNodeLinks(entityName).resolvedSymbol; } - else if (entityName.kind === 127) { + else if (entityName.kind === 128) { var symbol = getNodeLinks(entityName).resolvedSymbol; if (!symbol) { checkQualifiedName(entityName); @@ -17504,7 +18995,7 @@ var ts; } } else if (isTypeReferenceIdentifier(entityName)) { - var meaning = entityName.parent.kind === 142 ? 793056 : 1536; + var meaning = entityName.parent.kind === 144 ? 793056 : 1536; meaning |= 8388608; return resolveEntityName(entityName, meaning); } @@ -17518,14 +19009,14 @@ var ts; return getSymbolOfNode(node.parent); } if (node.kind === 65 && isInRightSideOfImportOrExportAssignment(node)) { - return node.parent.kind === 215 + return node.parent.kind === 217 ? getSymbolOfEntityNameOrPropertyAccessExpression(node) : getSymbolOfPartOfRightHandSideOfImportEquals(node); } switch (node.kind) { case 65: - case 156: - case 127: + case 158: + case 128: return getSymbolOfEntityNameOrPropertyAccessExpression(node); case 93: case 91: @@ -17533,7 +19024,7 @@ var ts; return type.symbol; case 114: var constructorDeclaration = node.parent; - if (constructorDeclaration && constructorDeclaration.kind === 136) { + if (constructorDeclaration && constructorDeclaration.kind === 137) { return constructorDeclaration.parent.symbol; } return undefined; @@ -17541,12 +19032,12 @@ var ts; var moduleName; if ((ts.isExternalModuleImportEqualsDeclaration(node.parent.parent) && ts.getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node) || - ((node.parent.kind === 210 || node.parent.kind === 216) && + ((node.parent.kind === 212 || node.parent.kind === 218) && node.parent.moduleSpecifier === node)) { return resolveExternalModuleName(node, node); } case 7: - if (node.parent.kind == 157 && node.parent.argumentExpression === node) { + if (node.parent.kind === 159 && node.parent.argumentExpression === node) { var objectType = checkExpression(node.parent.expression); if (objectType === unknownType) return undefined; @@ -17560,7 +19051,7 @@ var ts; return undefined; } function getShorthandAssignmentValueSymbol(location) { - if (location && location.kind === 226) { + if (location && location.kind === 228) { return resolveEntityName(location.name, 107455); } return undefined; @@ -17569,12 +19060,15 @@ var ts; if (isInsideWithStatementBody(node)) { return unknownType; } - if (isTypeNode(node)) { + if (ts.isTypeNode(node)) { return getTypeFromTypeNode(node); } if (ts.isExpression(node)) { return getTypeOfExpression(node); } + if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(node)) { + return getBaseTypes(getDeclaredTypeOfSymbol(getSymbolOfNode(node.parent.parent)))[0]; + } if (isTypeDeclaration(node)) { var symbol = getSymbolOfNode(node); return getDeclaredTypeOfSymbol(symbol); @@ -17619,9 +19113,9 @@ var ts; function getRootSymbols(symbol) { if (symbol.flags & 268435456) { var symbols = []; - var name_10 = symbol.name; + var name_14 = symbol.name; ts.forEach(getSymbolLinks(symbol).unionType.types, function (t) { - symbols.push(getPropertyOfType(t, name_10)); + symbols.push(getPropertyOfType(t, name_14)); }); return symbols; } @@ -17633,81 +19127,81 @@ var ts; } return [symbol]; } - function isExternalModuleSymbol(symbol) { - return symbol.flags & 512 && symbol.declarations.length === 1 && symbol.declarations[0].kind === 228; - } - function getAliasNameSubstitution(symbol, getGeneratedNameForNode) { - if (languageVersion >= 2) { - return undefined; - } - var node = getDeclarationOfAliasSymbol(symbol); - if (node) { - if (node.kind === 211) { - var defaultKeyword; - if (languageVersion === 0) { - defaultKeyword = "[\"default\"]"; - } - else { - defaultKeyword = ".default"; - } - return getGeneratedNameForNode(node.parent) + defaultKeyword; - } - if (node.kind === 214) { - var moduleName = getGeneratedNameForNode(node.parent.parent.parent); - var propertyName = node.propertyName || node.name; - return moduleName + "." + ts.unescapeIdentifier(propertyName.text); - } - } - } - function getExportNameSubstitution(symbol, location, getGeneratedNameForNode) { - if (isExternalModuleSymbol(symbol.parent)) { - if (languageVersion >= 2 || compilerOptions.module === 4) { - return undefined; - } - return "exports." + ts.unescapeIdentifier(symbol.name); - } - var node = location; - var containerSymbol = getParentOfSymbol(symbol); - while (node) { - if ((node.kind === 206 || node.kind === 205) && getSymbolOfNode(node) === containerSymbol) { - return getGeneratedNameForNode(node) + "." + ts.unescapeIdentifier(symbol.name); - } - node = node.parent; - } - } - function getExpressionNameSubstitution(node, getGeneratedNameForNode) { - var symbol = getNodeLinks(node).resolvedSymbol || (ts.isDeclarationName(node) ? getSymbolOfNode(node.parent) : undefined); + function getReferencedExportContainer(node) { + var symbol = getReferencedValueSymbol(node); if (symbol) { - if (symbol.parent) { - return getExportNameSubstitution(symbol, node.parent, getGeneratedNameForNode); + if (symbol.flags & 1048576) { + var exportSymbol = getMergedSymbol(symbol.exportSymbol); + if (exportSymbol.flags & 944) { + return undefined; + } + symbol = exportSymbol; } - var exportSymbol = getExportSymbolOfValueSymbolIfExported(symbol); - if (symbol !== exportSymbol && !(exportSymbol.flags & 944)) { - return getExportNameSubstitution(exportSymbol, node.parent, getGeneratedNameForNode); - } - if (symbol.flags & 8388608) { - return getAliasNameSubstitution(symbol, getGeneratedNameForNode); + var parentSymbol = getParentOfSymbol(symbol); + if (parentSymbol) { + if (parentSymbol.flags & 512 && parentSymbol.valueDeclaration.kind === 230) { + return parentSymbol.valueDeclaration; + } + for (var n = node.parent; n; n = n.parent) { + if ((n.kind === 208 || n.kind === 207) && getSymbolOfNode(n) === parentSymbol) { + return n; + } + } } } } + function getReferencedImportDeclaration(node) { + var symbol = getReferencedValueSymbol(node); + return symbol && symbol.flags & 8388608 ? getDeclarationOfAliasSymbol(symbol) : undefined; + } + function isStatementWithLocals(node) { + switch (node.kind) { + case 182: + case 210: + case 189: + case 190: + case 191: + return true; + } + return false; + } + function isNestedRedeclarationSymbol(symbol) { + if (symbol.flags & 418) { + var links = getSymbolLinks(symbol); + if (links.isNestedRedeclaration === undefined) { + var container = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration); + links.isNestedRedeclaration = isStatementWithLocals(container) && + !!resolveName(container.parent, symbol.name, 107455, undefined, undefined); + } + return links.isNestedRedeclaration; + } + return false; + } + function getReferencedNestedRedeclaration(node) { + var symbol = getReferencedValueSymbol(node); + return symbol && isNestedRedeclarationSymbol(symbol) ? symbol.valueDeclaration : undefined; + } + function isNestedRedeclaration(node) { + return isNestedRedeclarationSymbol(getSymbolOfNode(node)); + } function isValueAliasDeclaration(node) { switch (node.kind) { - case 209: case 211: - case 212: + case 213: case 214: - case 218: - return isAliasResolvedToValue(getSymbolOfNode(node)); case 216: + case 220: + return isAliasResolvedToValue(getSymbolOfNode(node)); + case 218: var exportClause = node.exportClause; return exportClause && ts.forEach(exportClause.elements, isValueAliasDeclaration); - case 215: + case 217: return node.expression && node.expression.kind === 65 ? isAliasResolvedToValue(getSymbolOfNode(node)) : true; } return false; } function isTopLevelValueImportEqualsWithEntityName(node) { - if (node.parent.kind !== 228 || !ts.isInternalModuleImportEqualsDeclaration(node)) { + if (node.parent.kind !== 230 || !ts.isInternalModuleImportEqualsDeclaration(node)) { return false; } var isValue = isAliasResolvedToValue(getSymbolOfNode(node)); @@ -17715,7 +19209,7 @@ var ts; } function isAliasResolvedToValue(symbol) { var target = resolveAlias(symbol); - if (target === unknownSymbol && compilerOptions.separateCompilation) { + if (target === unknownSymbol && compilerOptions.isolatedModules) { return true; } return target !== unknownSymbol && target && target.flags & 107455 && !isConstEnumOrConstEnumOnlyModule(target); @@ -17752,7 +19246,7 @@ var ts; return getNodeLinks(node).enumMemberValue; } function getConstantValue(node) { - if (node.kind === 227) { + if (node.kind === 229) { return getEnumMemberValue(node); } var symbol = getNodeLinks(node).resolvedSymbol; @@ -17763,10 +19257,9 @@ var ts; } return undefined; } - function serializeEntityName(node, getGeneratedNameForNode, fallbackPath) { + function serializeEntityName(node, fallbackPath) { if (node.kind === 65) { - var substitution = getExpressionNameSubstitution(node, getGeneratedNameForNode); - var text = substitution || node.text; + var text = node.text; if (fallbackPath) { fallbackPath.push(text); } @@ -17775,14 +19268,14 @@ var ts; } } else { - var left = serializeEntityName(node.left, getGeneratedNameForNode, fallbackPath); - var right = serializeEntityName(node.right, getGeneratedNameForNode, fallbackPath); + var left = serializeEntityName(node.left, fallbackPath); + var right = serializeEntityName(node.right, fallbackPath); if (!fallbackPath) { return left + "." + right; } } } - function serializeTypeReferenceNode(node, getGeneratedNameForNode) { + function serializeTypeReferenceNode(node) { var type = getTypeFromTypeNode(node); if (type.flags & 16) { return "void 0"; @@ -17799,47 +19292,47 @@ var ts; else if (type.flags & 8192) { return "Array"; } - else if (type.flags & 1048576) { + else if (type.flags & 2097152) { return "Symbol"; } else if (type === unknownType) { var fallbackPath = []; - serializeEntityName(node.typeName, getGeneratedNameForNode, fallbackPath); + serializeEntityName(node.typeName, fallbackPath); return fallbackPath; } else if (type.symbol && type.symbol.valueDeclaration) { - return serializeEntityName(node.typeName, getGeneratedNameForNode); + return serializeEntityName(node.typeName); } else if (typeHasCallOrConstructSignatures(type)) { return "Function"; } return "Object"; } - function serializeTypeNode(node, getGeneratedNameForNode) { + function serializeTypeNode(node) { if (node) { switch (node.kind) { case 99: return "void 0"; - case 150: - return serializeTypeNode(node.type, getGeneratedNameForNode); - case 143: - case 144: + case 152: + return serializeTypeNode(node.type); + case 145: + case 146: return "Function"; - case 147: - case 148: + case 149: + case 150: return "Array"; case 113: return "Boolean"; - case 122: + case 123: case 8: return "String"; - case 120: + case 121: return "Number"; - case 142: - return serializeTypeReferenceNode(node, getGeneratedNameForNode); - case 145: - case 146: - case 149: + case 144: + return serializeTypeReferenceNode(node); + case 147: + case 148: + case 151: case 112: break; default: @@ -17849,23 +19342,23 @@ var ts; } return "Object"; } - function serializeTypeOfNode(node, getGeneratedNameForNode) { + function serializeTypeOfNode(node) { switch (node.kind) { - case 202: return "Function"; - case 133: return serializeTypeNode(node.type, getGeneratedNameForNode); - case 130: return serializeTypeNode(node.type, getGeneratedNameForNode); - case 137: return serializeTypeNode(node.type, getGeneratedNameForNode); - case 138: return serializeTypeNode(getSetAccessorTypeAnnotationNode(node), getGeneratedNameForNode); + case 204: return "Function"; + case 134: return serializeTypeNode(node.type); + case 131: return serializeTypeNode(node.type); + case 138: return serializeTypeNode(node.type); + case 139: return serializeTypeNode(getSetAccessorTypeAnnotationNode(node)); } if (ts.isFunctionLike(node)) { return "Function"; } return "void 0"; } - function serializeParameterTypesOfNode(node, getGeneratedNameForNode) { + function serializeParameterTypesOfNode(node) { if (node) { var valueDeclaration; - if (node.kind === 202) { + if (node.kind === 204) { valueDeclaration = ts.getFirstConstructorWithBody(node); } else if (ts.isFunctionLike(node) && ts.nodeIsPresent(node.body)) { @@ -17880,19 +19373,19 @@ var ts; for (var i = 0; i < parameterCount; i++) { if (parameters[i].dotDotDotToken) { var parameterType = parameters[i].type; - if (parameterType.kind === 147) { + if (parameterType.kind === 149) { parameterType = parameterType.elementType; } - else if (parameterType.kind === 142 && parameterType.typeArguments && parameterType.typeArguments.length === 1) { + else if (parameterType.kind === 144 && parameterType.typeArguments && parameterType.typeArguments.length === 1) { parameterType = parameterType.typeArguments[0]; } else { parameterType = undefined; } - result[i] = serializeTypeNode(parameterType, getGeneratedNameForNode); + result[i] = serializeTypeNode(parameterType); } else { - result[i] = serializeTypeOfNode(parameters[i], getGeneratedNameForNode); + result[i] = serializeTypeOfNode(parameters[i]); } } return result; @@ -17901,9 +19394,9 @@ var ts; } return emptyArray; } - function serializeReturnTypeOfNode(node, getGeneratedNameForNode) { + function serializeReturnTypeOfNode(node) { if (node && ts.isFunctionLike(node)) { - return serializeTypeNode(node.type, getGeneratedNameForNode); + return serializeTypeNode(node.type); } return "void 0"; } @@ -17925,25 +19418,24 @@ var ts; function hasGlobalName(name) { return ts.hasProperty(globals, name); } - function resolvesToSomeValue(location, name) { - ts.Debug.assert(!ts.nodeIsSynthesized(location), "resolvesToSomeValue called with a synthesized location"); - return !!resolveName(location, name, 107455, undefined, undefined); + function getReferencedValueSymbol(reference) { + return getNodeLinks(reference).resolvedSymbol || + resolveName(reference, reference.text, 107455 | 1048576 | 8388608, undefined, undefined); } function getReferencedValueDeclaration(reference) { ts.Debug.assert(!ts.nodeIsSynthesized(reference)); - var symbol = getNodeLinks(reference).resolvedSymbol || - resolveName(reference, reference.text, 107455 | 8388608, undefined, undefined); + var symbol = getReferencedValueSymbol(reference); return symbol && getExportSymbolOfValueSymbolIfExported(symbol).valueDeclaration; } function getBlockScopedVariableId(n) { ts.Debug.assert(!ts.nodeIsSynthesized(n)); - var isVariableDeclarationOrBindingElement = n.parent.kind === 153 || (n.parent.kind === 199 && n.parent.name === n); + var isVariableDeclarationOrBindingElement = n.parent.kind === 155 || (n.parent.kind === 201 && n.parent.name === n); var symbol = (isVariableDeclarationOrBindingElement ? getSymbolOfNode(n.parent) : undefined) || getNodeLinks(n).resolvedSymbol || resolveName(n, n.text, 107455 | 8388608, undefined, undefined); var isLetOrConst = symbol && (symbol.flags & 2) && - symbol.valueDeclaration.parent.kind !== 224; + symbol.valueDeclaration.parent.kind !== 226; if (isLetOrConst) { getSymbolLinks(symbol); return symbol.id; @@ -17963,7 +19455,10 @@ var ts; } function createResolver() { return { - getExpressionNameSubstitution: getExpressionNameSubstitution, + getReferencedExportContainer: getReferencedExportContainer, + getReferencedImportDeclaration: getReferencedImportDeclaration, + getReferencedNestedRedeclaration: getReferencedNestedRedeclaration, + isNestedRedeclaration: isNestedRedeclaration, isValueAliasDeclaration: isValueAliasDeclaration, hasGlobalName: hasGlobalName, isReferencedAliasDeclaration: isReferencedAliasDeclaration, @@ -17977,7 +19472,6 @@ var ts; isSymbolAccessible: isSymbolAccessible, isEntityNameVisible: isEntityNameVisible, getConstantValue: getConstantValue, - resolvesToSomeValue: resolvesToSomeValue, collectLinkedAliases: collectLinkedAliases, getBlockScopedVariableId: getBlockScopedVariableId, getReferencedValueDeclaration: getReferencedValueDeclaration, @@ -17999,8 +19493,7 @@ var ts; getSymbolLinks(argumentsSymbol).type = getGlobalType("IArguments"); getSymbolLinks(unknownSymbol).type = unknownType; globals[undefinedSymbol.name] = undefinedSymbol; - globalArraySymbol = getGlobalTypeSymbol("Array"); - globalArrayType = getTypeOfGlobalSymbol(globalArraySymbol, 1); + globalArrayType = getGlobalType("Array", 1); globalObjectType = getGlobalType("Object"); globalFunctionType = getGlobalType("Function"); globalStringType = getGlobalType("String"); @@ -18016,113 +19509,19 @@ var ts; globalESSymbolType = getGlobalType("Symbol"); globalESSymbolConstructorSymbol = getGlobalValueSymbol("Symbol"); globalIterableType = getGlobalType("Iterable", 1); + globalIteratorType = getGlobalType("Iterator", 1); + globalIterableIteratorType = getGlobalType("IterableIterator", 1); } else { globalTemplateStringsArrayType = unknownType; globalESSymbolType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); globalESSymbolConstructorSymbol = undefined; + globalIterableType = emptyGenericType; + globalIteratorType = emptyGenericType; + globalIterableIteratorType = emptyGenericType; } anyArrayType = createArrayType(anyType); } - function isReservedWordInStrictMode(node) { - return (node.parserContextFlags & 1) && - (102 <= node.originalKeywordKind && node.originalKeywordKind <= 110); - } - function reportStrictModeGrammarErrorInClassDeclaration(identifier, message, arg0, arg1, arg2) { - if (ts.getAncestor(identifier, 202) || ts.getAncestor(identifier, 175)) { - return grammarErrorOnNode(identifier, message, arg0); - } - return false; - } - function checkGrammarImportDeclarationNameInStrictMode(node) { - if (node.importClause) { - var impotClause = node.importClause; - if (impotClause.namedBindings) { - var nameBindings = impotClause.namedBindings; - if (nameBindings.kind === 212) { - var name_11 = nameBindings.name; - if (isReservedWordInStrictMode(name_11)) { - var nameText = ts.declarationNameToString(name_11); - return grammarErrorOnNode(name_11, ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode, nameText); - } - } - else if (nameBindings.kind === 213) { - var reportError = false; - for (var _i = 0, _a = nameBindings.elements; _i < _a.length; _i++) { - var element = _a[_i]; - var name_12 = element.name; - if (isReservedWordInStrictMode(name_12)) { - var nameText = ts.declarationNameToString(name_12); - reportError = reportError || grammarErrorOnNode(name_12, ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode, nameText); - } - } - return reportError; - } - } - } - return false; - } - function checkGrammarDeclarationNameInStrictMode(node) { - var name = node.name; - if (name && name.kind === 65 && isReservedWordInStrictMode(name)) { - var nameText = ts.declarationNameToString(name); - switch (node.kind) { - case 130: - case 199: - case 201: - case 129: - case 153: - case 203: - case 204: - case 205: - return checkGrammarIdentifierInStrictMode(name); - case 202: - return grammarErrorOnNode(name, ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_strict_mode, nameText); - case 206: - return grammarErrorOnNode(name, ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode, nameText); - case 209: - return grammarErrorOnNode(name, ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode, nameText); - } - } - return false; - } - function checkGrammarTypeReferenceInStrictMode(typeName) { - if (typeName.kind === 65) { - checkGrammarTypeNameInStrictMode(typeName); - } - else if (typeName.kind === 127) { - checkGrammarTypeNameInStrictMode(typeName.right); - checkGrammarTypeReferenceInStrictMode(typeName.left); - } - } - function checkGrammarExpressionWithTypeArgumentsInStrictMode(expression) { - if (expression && expression.kind === 65) { - return checkGrammarIdentifierInStrictMode(expression); - } - else if (expression && expression.kind === 156) { - checkGrammarExpressionWithTypeArgumentsInStrictMode(expression.expression); - } - } - function checkGrammarIdentifierInStrictMode(node, nameText) { - if (node && node.kind === 65 && isReservedWordInStrictMode(node)) { - if (!nameText) { - nameText = ts.declarationNameToString(node); - } - var errorReport = reportStrictModeGrammarErrorInClassDeclaration(node, ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_strict_mode, nameText) || - grammarErrorOnNode(node, ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode, nameText); - return errorReport; - } - return false; - } - function checkGrammarTypeNameInStrictMode(node) { - if (node && node.kind === 65 && isReservedWordInStrictMode(node)) { - var nameText = ts.declarationNameToString(node); - var errorReport = reportStrictModeGrammarErrorInClassDeclaration(node, ts.Diagnostics.Type_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_strict_mode, nameText) || - grammarErrorOnNode(node, ts.Diagnostics.Type_expected_0_is_a_reserved_word_in_strict_mode, nameText); - return errorReport; - } - return false; - } function checkGrammarDecorators(node) { if (!node.decorators) { return false; @@ -18133,7 +19532,7 @@ var ts; else if (languageVersion < 1) { return grammarErrorOnFirstToken(node, ts.Diagnostics.Decorators_are_only_available_when_targeting_ECMAScript_5_and_higher); } - else if (node.kind === 137 || node.kind === 138) { + else if (node.kind === 138 || node.kind === 139) { 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); @@ -18143,26 +19542,35 @@ var ts; } function checkGrammarModifiers(node) { switch (node.kind) { - case 137: case 138: - case 136: - case 133: - case 132: - case 135: + case 139: + case 137: case 134: - case 141: - case 202: + case 133: + case 136: + case 135: + case 142: + case 208: + case 212: + case 211: + case 218: + case 217: + case 131: + break; + case 204: + case 205: + case 183: case 203: case 206: - case 205: - case 181: - case 201: - case 204: - case 210: - case 209: - case 216: - case 215: - case 130: + if (node.modifiers && node.parent.kind !== 209 && node.parent.kind !== 230) { + return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here); + } + break; + case 207: + if (node.modifiers && (node.modifiers.length > 1 || node.modifiers[0].kind !== 70) && + node.parent.kind !== 209 && node.parent.kind !== 230) { + return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here); + } break; default: return false; @@ -18196,7 +19604,7 @@ var ts; else if (flags & 128) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "static"); } - else if (node.parent.kind === 207 || node.parent.kind === 228) { + else if (node.parent.kind === 209 || node.parent.kind === 230) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_element, text); } flags |= ts.modifierToFlag(modifier.kind); @@ -18205,10 +19613,10 @@ var ts; if (flags & 128) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "static"); } - else if (node.parent.kind === 207 || node.parent.kind === 228) { + else if (node.parent.kind === 209 || node.parent.kind === 230) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_element, "static"); } - else if (node.kind === 130) { + else if (node.kind === 131) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "static"); } flags |= 128; @@ -18221,10 +19629,10 @@ var ts; else if (flags & 2) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "export", "declare"); } - else if (node.parent.kind === 202) { + else if (node.parent.kind === 204) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_class_element, "export"); } - else if (node.kind === 130) { + else if (node.kind === 131) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "export"); } flags |= 1; @@ -18233,13 +19641,13 @@ var ts; if (flags & 2) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "declare"); } - else if (node.parent.kind === 202) { + else if (node.parent.kind === 204) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_class_element, "declare"); } - else if (node.kind === 130) { + else if (node.kind === 131) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "declare"); } - else if (ts.isInAmbientContext(node.parent) && node.parent.kind === 207) { + else if (ts.isInAmbientContext(node.parent) && node.parent.kind === 209) { return grammarErrorOnNode(modifier, ts.Diagnostics.A_declare_modifier_cannot_be_used_in_an_already_ambient_context); } flags |= 2; @@ -18247,7 +19655,7 @@ var ts; break; } } - if (node.kind === 136) { + if (node.kind === 137) { if (flags & 128) { return grammarErrorOnNode(lastStatic, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "static"); } @@ -18258,13 +19666,10 @@ var ts; return grammarErrorOnNode(lastPrivate, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "private"); } } - else if ((node.kind === 210 || node.kind === 209) && flags & 2) { + else if ((node.kind === 212 || node.kind === 211) && flags & 2) { return grammarErrorOnNode(lastDeclare, ts.Diagnostics.A_declare_modifier_cannot_be_used_with_an_import_declaration, "declare"); } - else if (node.kind === 203 && flags & 2) { - return grammarErrorOnNode(lastDeclare, ts.Diagnostics.A_declare_modifier_cannot_be_used_with_an_interface_declaration, "declare"); - } - else if (node.kind === 130 && (flags & 112) && ts.isBindingPattern(node.name)) { + else if (node.kind === 131 && (flags & 112) && ts.isBindingPattern(node.name)) { return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_may_not_be_a_binding_pattern); } } @@ -18327,7 +19732,7 @@ var ts; checkGrammarParameterList(node.parameters) || checkGrammarArrowFunction(node, file); } function checkGrammarArrowFunction(node, file) { - if (node.kind === 164) { + if (node.kind === 166) { var arrowFunction = node; var startLine = ts.getLineAndCharacterOfPosition(file, arrowFunction.equalsGreaterThanToken.pos).line; var endLine = ts.getLineAndCharacterOfPosition(file, arrowFunction.equalsGreaterThanToken.end).line; @@ -18362,7 +19767,7 @@ var ts; if (!parameter.type) { return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_must_have_a_type_annotation); } - if (parameter.type.kind !== 122 && parameter.type.kind !== 120) { + if (parameter.type.kind !== 123 && parameter.type.kind !== 121) { return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_must_be_string_or_number); } if (!node.type) { @@ -18394,7 +19799,7 @@ var ts; var sourceFile = ts.getSourceFileOfNode(node); for (var _i = 0; _i < arguments.length; _i++) { var arg = arguments[_i]; - if (arg.kind === 176) { + if (arg.kind === 178) { return grammarErrorAtPos(sourceFile, arg.pos, 0, ts.Diagnostics.Argument_expression_expected); } } @@ -18465,22 +19870,30 @@ var ts; return false; } function checkGrammarComputedPropertyName(node) { - if (node.kind !== 128) { + if (node.kind !== 129) { return false; } var computedPropertyName = node; - if (computedPropertyName.expression.kind === 170 && computedPropertyName.expression.operatorToken.kind === 23) { + if (computedPropertyName.expression.kind === 172 && computedPropertyName.expression.operatorToken.kind === 23) { return grammarErrorOnNode(computedPropertyName.expression, ts.Diagnostics.A_comma_expression_is_not_allowed_in_a_computed_property_name); } } function checkGrammarForGenerator(node) { if (node.asteriskToken) { - return grammarErrorOnNode(node.asteriskToken, ts.Diagnostics.Generators_are_not_currently_supported); + ts.Debug.assert(node.kind === 203 || + node.kind === 165 || + node.kind === 136); + 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); + } + if (languageVersion < 2) { + return grammarErrorOnNode(node.asteriskToken, ts.Diagnostics.Generators_are_only_available_when_targeting_ECMAScript_6_or_higher); + } } } - function checkGrammarFunctionName(name) { - return checkGrammarEvalOrArgumentsInStrictMode(name, name); - } function checkGrammarForInvalidQuestionMark(node, questionToken, message) { if (questionToken) { return grammarErrorOnNode(questionToken, message); @@ -18492,55 +19905,52 @@ var ts; var GetAccessor = 2; var SetAccesor = 4; var GetOrSetAccessor = GetAccessor | SetAccesor; - var inStrictMode = (node.parserContextFlags & 1) !== 0; for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { var prop = _a[_i]; - var name_13 = prop.name; - if (prop.kind === 176 || - name_13.kind === 128) { - checkGrammarComputedPropertyName(name_13); + var name_15 = prop.name; + if (prop.kind === 178 || + name_15.kind === 129) { + checkGrammarComputedPropertyName(name_15); continue; } var currentKind = void 0; - if (prop.kind === 225 || prop.kind === 226) { + if (prop.kind === 227 || prop.kind === 228) { checkGrammarForInvalidQuestionMark(prop, prop.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional); - if (name_13.kind === 7) { - checkGrammarNumericLiteral(name_13); + if (name_15.kind === 7) { + checkGrammarNumericLiteral(name_15); } currentKind = Property; } - else if (prop.kind === 135) { + else if (prop.kind === 136) { currentKind = Property; } - else if (prop.kind === 137) { + else if (prop.kind === 138) { currentKind = GetAccessor; } - else if (prop.kind === 138) { + else if (prop.kind === 139) { currentKind = SetAccesor; } else { ts.Debug.fail("Unexpected syntax kind:" + prop.kind); } - if (!ts.hasProperty(seen, name_13.text)) { - seen[name_13.text] = currentKind; + if (!ts.hasProperty(seen, name_15.text)) { + seen[name_15.text] = currentKind; } else { - var existingKind = seen[name_13.text]; + var existingKind = seen[name_15.text]; if (currentKind === Property && existingKind === Property) { - if (inStrictMode) { - grammarErrorOnNode(name_13, ts.Diagnostics.An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode); - } + continue; } else if ((currentKind & GetOrSetAccessor) && (existingKind & GetOrSetAccessor)) { if (existingKind !== GetOrSetAccessor && currentKind !== existingKind) { - seen[name_13.text] = currentKind | existingKind; + seen[name_15.text] = currentKind | existingKind; } else { - return grammarErrorOnNode(name_13, ts.Diagnostics.An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name); + return grammarErrorOnNode(name_15, ts.Diagnostics.An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name); } } else { - return grammarErrorOnNode(name_13, ts.Diagnostics.An_object_literal_cannot_have_property_and_accessor_with_the_same_name); + return grammarErrorOnNode(name_15, ts.Diagnostics.An_object_literal_cannot_have_property_and_accessor_with_the_same_name); } } } @@ -18549,24 +19959,24 @@ var ts; if (checkGrammarStatementInAmbientContext(forInOrOfStatement)) { return true; } - if (forInOrOfStatement.initializer.kind === 200) { + if (forInOrOfStatement.initializer.kind === 202) { var variableList = forInOrOfStatement.initializer; if (!checkGrammarVariableDeclarationList(variableList)) { if (variableList.declarations.length > 1) { - var diagnostic = forInOrOfStatement.kind === 188 + var diagnostic = forInOrOfStatement.kind === 190 ? 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 = variableList.declarations[0]; if (firstDeclaration.initializer) { - var diagnostic = forInOrOfStatement.kind === 188 + var diagnostic = forInOrOfStatement.kind === 190 ? 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 === 188 + var diagnostic = forInOrOfStatement.kind === 190 ? 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); @@ -18589,10 +19999,10 @@ var ts; else if (accessor.typeParameters) { return grammarErrorOnNode(accessor.name, ts.Diagnostics.An_accessor_cannot_have_type_parameters); } - else if (kind === 137 && accessor.parameters.length) { + else if (kind === 138 && accessor.parameters.length) { return grammarErrorOnNode(accessor.name, ts.Diagnostics.A_get_accessor_cannot_have_parameters); } - else if (kind === 138) { + else if (kind === 139) { if (accessor.type) { return grammarErrorOnNode(accessor.name, ts.Diagnostics.A_set_accessor_cannot_have_a_return_type_annotation); } @@ -18617,7 +20027,7 @@ var ts; } } function checkGrammarForNonSymbolComputedProperty(node, message) { - if (node.kind === 128 && !ts.isWellKnownSymbolSyntactically(node.expression)) { + if (node.kind === 129 && !ts.isWellKnownSymbolSyntactically(node.expression)) { return grammarErrorOnNode(node, message); } } @@ -18627,7 +20037,7 @@ var ts; checkGrammarForGenerator(node)) { return true; } - if (node.parent.kind === 155) { + if (node.parent.kind === 157) { if (checkGrammarForInvalidQuestionMark(node, node.questionToken, ts.Diagnostics.A_class_member_cannot_be_declared_optional)) { return true; } @@ -18635,7 +20045,7 @@ var ts; return grammarErrorAtPos(getSourceFile(node), node.end - 1, ";".length, ts.Diagnostics._0_expected, "{"); } } - if (node.parent.kind === 202) { + if (node.parent.kind === 204) { if (checkGrammarForInvalidQuestionMark(node, node.questionToken, ts.Diagnostics.A_class_member_cannot_be_declared_optional)) { return true; } @@ -18646,22 +20056,22 @@ var ts; 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 === 203) { + else if (node.parent.kind === 205) { 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 === 146) { + else if (node.parent.kind === 148) { return checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_a_type_literal_must_directly_refer_to_a_built_in_symbol); } } function isIterationStatement(node, lookInLabeledStatements) { switch (node.kind) { + case 189: + case 190: + case 191: case 187: case 188: - case 189: - case 185: - case 186: return true; - case 195: + case 197: return lookInLabeledStatements && isIterationStatement(node.statement, lookInLabeledStatements); } return false; @@ -18673,9 +20083,9 @@ var ts; return grammarErrorOnNode(node, ts.Diagnostics.Jump_target_cannot_cross_function_boundary); } switch (current.kind) { - case 195: + case 197: if (node.label && current.label.text === node.label.text) { - var isMisplacedContinueLabel = node.kind === 190 + var isMisplacedContinueLabel = node.kind === 192 && !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); @@ -18683,8 +20093,8 @@ var ts; return false; } break; - case 194: - if (node.kind === 191 && !node.label) { + case 196: + if (node.kind === 193 && !node.label) { return false; } break; @@ -18697,13 +20107,13 @@ var ts; current = current.parent; } if (node.label) { - var message = node.kind === 191 + var message = node.kind === 193 ? 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 === 191 + var message = node.kind === 193 ? 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); @@ -18715,17 +20125,16 @@ var ts; if (node !== ts.lastOrUndefined(elements)) { return grammarErrorOnNode(node, ts.Diagnostics.A_rest_element_must_be_last_in_an_array_destructuring_pattern); } - if (node.name.kind === 152 || node.name.kind === 151) { + if (node.name.kind === 154 || node.name.kind === 153) { 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); } } - return checkGrammarEvalOrArgumentsInStrictMode(node, node.name); } function checkGrammarVariableDeclaration(node) { - if (node.parent.parent.kind !== 188 && node.parent.parent.kind !== 189) { + if (node.parent.parent.kind !== 190 && node.parent.parent.kind !== 191) { if (ts.isInAmbientContext(node)) { if (node.initializer) { var equalsTokenLength = "=".length; @@ -18742,8 +20151,7 @@ var ts; } } var checkLetConstNames = languageVersion >= 2 && (ts.isLet(node) || ts.isConst(node)); - return (checkLetConstNames && checkGrammarNameInLetOrConstDeclarations(node.name)) || - checkGrammarEvalOrArgumentsInStrictMode(node, node.name); + return checkLetConstNames && checkGrammarNameInLetOrConstDeclarations(node.name); } function checkGrammarNameInLetOrConstDeclarations(name) { if (name.kind === 65) { @@ -18755,7 +20163,7 @@ var ts; var elements = name.elements; for (var _i = 0; _i < elements.length; _i++) { var element = elements[_i]; - if (element.kind !== 176) { + if (element.kind !== 178) { checkGrammarNameInLetOrConstDeclarations(element.name); } } @@ -18772,15 +20180,15 @@ var ts; } function allowLetAndConstDeclarations(parent) { switch (parent.kind) { - case 184: - case 185: case 186: - case 193: case 187: case 188: - case 189: - return false; case 195: + case 189: + case 190: + case 191: + return false; + case 197: return allowLetAndConstDeclarations(parent.parent); } return true; @@ -18796,7 +20204,7 @@ var ts; } } function isIntegerLiteral(expression) { - if (expression.kind === 168) { + if (expression.kind === 170) { var unaryExpression = expression; if (unaryExpression.operator === 33 || unaryExpression.operator === 34) { expression = unaryExpression.operand; @@ -18815,7 +20223,7 @@ var ts; var inAmbientContext = ts.isInAmbientContext(enumDecl); for (var _i = 0, _a = enumDecl.members; _i < _a.length; _i++) { var node = _a[_i]; - if (node.name.kind === 128) { + if (node.name.kind === 129) { hasError = grammarErrorOnNode(node.name, ts.Diagnostics.Computed_property_names_are_not_allowed_in_enums); } else if (inAmbientContext) { @@ -18857,23 +20265,6 @@ var ts; return true; } } - function checkGrammarEvalOrArgumentsInStrictMode(contextNode, name) { - if (name && name.kind === 65) { - var identifier = name; - if (contextNode && (contextNode.parserContextFlags & 1) && isEvalOrArgumentsIdentifier(identifier)) { - var nameText = ts.declarationNameToString(identifier); - var reportErrorInClassDeclaration = reportStrictModeGrammarErrorInClassDeclaration(identifier, ts.Diagnostics.Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode, nameText); - if (!reportErrorInClassDeclaration) { - return grammarErrorOnNode(identifier, ts.Diagnostics.Invalid_use_of_0_in_strict_mode, nameText); - } - return reportErrorInClassDeclaration; - } - } - } - function isEvalOrArgumentsIdentifier(node) { - return node.kind === 65 && - (node.text === "eval" || node.text === "arguments"); - } 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); @@ -18885,18 +20276,18 @@ var ts; } } function checkGrammarProperty(node) { - if (node.parent.kind === 202) { + if (node.parent.kind === 204) { if (checkGrammarForInvalidQuestionMark(node, node.questionToken, ts.Diagnostics.A_class_member_cannot_be_declared_optional) || 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 === 203) { + else if (node.parent.kind === 205) { if (checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_an_interface_must_directly_refer_to_a_built_in_symbol)) { return true; } } - else if (node.parent.kind === 146) { + else if (node.parent.kind === 148) { if (checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_a_type_literal_must_directly_refer_to_a_built_in_symbol)) { return true; } @@ -18906,11 +20297,11 @@ var ts; } } function checkGrammarTopLevelElementForRequiredDeclareModifier(node) { - if (node.kind === 203 || - node.kind === 210 || - node.kind === 209 || - node.kind === 216 || - node.kind === 215 || + if (node.kind === 205 || + node.kind === 212 || + node.kind === 211 || + node.kind === 218 || + node.kind === 217 || (node.flags & 2) || (node.flags & (1 | 256))) { return false; @@ -18920,7 +20311,7 @@ var ts; function checkGrammarTopLevelElementsForRequiredDeclareModifier(file) { for (var _i = 0, _a = file.statements; _i < _a.length; _i++) { var decl = _a[_i]; - if (ts.isDeclaration(decl) || decl.kind === 181) { + if (ts.isDeclaration(decl) || decl.kind === 183) { if (checkGrammarTopLevelElementForRequiredDeclareModifier(decl)) { return true; } @@ -18939,7 +20330,7 @@ var ts; 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 === 180 || node.parent.kind === 207 || node.parent.kind === 228) { + if (node.parent.kind === 182 || node.parent.kind === 209 || node.parent.kind === 230) { 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); @@ -18950,13 +20341,8 @@ var ts; } } function checkGrammarNumericLiteral(node) { - if (node.flags & 16384) { - if (node.parserContextFlags & 1) { - return grammarErrorOnNode(node, ts.Diagnostics.Octal_literals_are_not_allowed_in_strict_mode); - } - else if (languageVersion >= 1) { - return grammarErrorOnNode(node, ts.Diagnostics.Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher); - } + if (node.flags & 16384 && languageVersion >= 1) { + return grammarErrorOnNode(node, ts.Diagnostics.Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher); } } function grammarErrorAfterFirstToken(node, message, arg0, arg1, arg2) { @@ -18967,8 +20353,6 @@ var ts; return true; } } - initializeTypeChecker(); - return checker; } ts.createTypeChecker = createTypeChecker; })(ts || (ts = {})); @@ -19020,7 +20404,7 @@ var ts; var oldWriter = writer; ts.forEach(moduleElementDeclarationEmitInfo, function (aliasEmitInfo) { if (aliasEmitInfo.isVisible) { - ts.Debug.assert(aliasEmitInfo.node.kind === 210); + ts.Debug.assert(aliasEmitInfo.node.kind === 212); createAndSetNewTextWriterWithSymbolWriter(); ts.Debug.assert(aliasEmitInfo.indent === 0); writeImportDeclaration(aliasEmitInfo.node); @@ -19093,10 +20477,10 @@ var ts; var oldWriter = writer; ts.forEach(nodes, function (declaration) { var nodeToCheck; - if (declaration.kind === 199) { + if (declaration.kind === 201) { nodeToCheck = declaration.parent.parent; } - else if (declaration.kind === 213 || declaration.kind === 214 || declaration.kind === 211) { + else if (declaration.kind === 215 || declaration.kind === 216 || declaration.kind === 213) { ts.Debug.fail("We should be getting ImportDeclaration instead to write"); } else { @@ -19107,7 +20491,7 @@ var ts; moduleElementEmitInfo = ts.forEach(asynchronousSubModuleDeclarationEmitInfo, function (declEmitInfo) { return declEmitInfo.node === nodeToCheck ? declEmitInfo : undefined; }); } if (moduleElementEmitInfo) { - if (moduleElementEmitInfo.node.kind === 210) { + if (moduleElementEmitInfo.node.kind === 212) { moduleElementEmitInfo.isVisible = true; } else { @@ -19115,12 +20499,12 @@ var ts; for (var declarationIndent = moduleElementEmitInfo.indent; declarationIndent; declarationIndent--) { increaseIndent(); } - if (nodeToCheck.kind === 206) { + if (nodeToCheck.kind === 208) { ts.Debug.assert(asynchronousSubModuleDeclarationEmitInfo === undefined); asynchronousSubModuleDeclarationEmitInfo = []; } writeModuleElement(nodeToCheck); - if (nodeToCheck.kind === 206) { + if (nodeToCheck.kind === 208) { moduleElementEmitInfo.subModuleElementDeclarationEmitInfo = asynchronousSubModuleDeclarationEmitInfo; asynchronousSubModuleDeclarationEmitInfo = undefined; } @@ -19208,39 +20592,39 @@ var ts; function emitType(type) { switch (type.kind) { case 112: - case 122: - case 120: - case 113: case 123: + case 121: + case 113: + case 124: case 99: case 8: return writeTextOfNode(currentSourceFile, type); - case 177: + case 179: return emitExpressionWithTypeArguments(type); - case 142: - return emitTypeReference(type); - case 145: - return emitTypeQuery(type); - case 147: - return emitArrayType(type); - case 148: - return emitTupleType(type); - case 149: - return emitUnionType(type); - case 150: - return emitParenType(type); - case 143: case 144: - return emitSignatureDeclarationWithJsDocComments(type); + return emitTypeReference(type); + case 147: + return emitTypeQuery(type); + case 149: + return emitArrayType(type); + case 150: + return emitTupleType(type); + case 151: + return emitUnionType(type); + case 152: + return emitParenType(type); + case 145: case 146: + return emitSignatureDeclarationWithJsDocComments(type); + case 148: return emitTypeLiteral(type); case 65: return emitEntityName(type); - case 127: + case 128: return emitEntityName(type); } function emitEntityName(entityName) { - var visibilityResult = resolver.isEntityNameVisible(entityName, entityName.parent.kind === 209 ? entityName.parent : enclosingDeclaration); + var visibilityResult = resolver.isEntityNameVisible(entityName, entityName.parent.kind === 211 ? entityName.parent : enclosingDeclaration); handleSymbolAccessibilityError(visibilityResult); writeEntityName(entityName); function writeEntityName(entityName) { @@ -19248,8 +20632,8 @@ var ts; writeTextOfNode(currentSourceFile, entityName); } else { - var left = entityName.kind === 127 ? entityName.left : entityName.expression; - var right = entityName.kind === 127 ? entityName.right : entityName.name; + var left = entityName.kind === 128 ? entityName.left : entityName.expression; + var right = entityName.kind === 128 ? entityName.right : entityName.name; writeEntityName(left); write("."); writeTextOfNode(currentSourceFile, right); @@ -19258,7 +20642,7 @@ var ts; } function emitExpressionWithTypeArguments(node) { if (ts.isSupportedExpressionWithTypeArguments(node)) { - ts.Debug.assert(node.expression.kind === 65 || node.expression.kind === 156); + ts.Debug.assert(node.expression.kind === 65 || node.expression.kind === 158); emitEntityName(node.expression); if (node.typeArguments) { write("<"); @@ -19319,9 +20703,9 @@ var ts; } var count = 0; while (true) { - var name_14 = baseName + "_" + (++count); - if (!ts.hasProperty(currentSourceFile.identifiers, name_14)) { - return name_14; + var name_16 = baseName + "_" + (++count); + if (!ts.hasProperty(currentSourceFile.identifiers, name_16)) { + return name_16; } } } @@ -19362,10 +20746,10 @@ var ts; if (isModuleElementVisible) { writeModuleElement(node); } - else if (node.kind === 209 || - (node.parent.kind === 228 && ts.isExternalModule(currentSourceFile))) { + else if (node.kind === 211 || + (node.parent.kind === 230 && ts.isExternalModule(currentSourceFile))) { var isVisible; - if (asynchronousSubModuleDeclarationEmitInfo && node.parent.kind !== 228) { + if (asynchronousSubModuleDeclarationEmitInfo && node.parent.kind !== 230) { asynchronousSubModuleDeclarationEmitInfo.push({ node: node, outputPos: writer.getTextPos(), @@ -19374,7 +20758,7 @@ var ts; }); } else { - if (node.kind === 210) { + if (node.kind === 212) { var importDeclaration = node; if (importDeclaration.importClause) { isVisible = (importDeclaration.importClause.name && resolver.isDeclarationVisible(importDeclaration.importClause)) || @@ -19392,23 +20776,23 @@ var ts; } function writeModuleElement(node) { switch (node.kind) { - case 201: - return writeFunctionDeclaration(node); - case 181: - return writeVariableStatement(node); case 203: - return writeInterfaceDeclaration(node); - case 202: - return writeClassDeclaration(node); - case 204: - return writeTypeAliasDeclaration(node); + return writeFunctionDeclaration(node); + case 183: + return writeVariableStatement(node); case 205: - return writeEnumDeclaration(node); + return writeInterfaceDeclaration(node); + case 204: + return writeClassDeclaration(node); case 206: + return writeTypeAliasDeclaration(node); + case 207: + return writeEnumDeclaration(node); + case 208: return writeModuleDeclaration(node); - case 209: + case 211: return writeImportEqualsDeclaration(node); - case 210: + case 212: return writeImportDeclaration(node); default: ts.Debug.fail("Unknown symbol kind"); @@ -19422,7 +20806,7 @@ var ts; if (node.flags & 256) { write("default "); } - else if (node.kind !== 203) { + else if (node.kind !== 205) { write("declare "); } } @@ -19466,7 +20850,7 @@ var ts; } function isVisibleNamedBinding(namedBindings) { if (namedBindings) { - if (namedBindings.kind === 212) { + if (namedBindings.kind === 214) { return resolver.isDeclarationVisible(namedBindings); } else { @@ -19492,7 +20876,7 @@ var ts; if (currentWriterPos !== writer.getTextPos()) { write(", "); } - if (node.importClause.namedBindings.kind === 212) { + if (node.importClause.namedBindings.kind === 214) { write("* as "); writeTextOfNode(currentSourceFile, node.importClause.namedBindings.name); } @@ -19541,9 +20925,14 @@ var ts; function writeModuleDeclaration(node) { emitJsDocComments(node); emitModuleElementDeclarationFlags(node); - write("module "); + if (node.flags & 32768) { + write("namespace "); + } + else { + write("module "); + } writeTextOfNode(currentSourceFile, node.name); - while (node.body.kind !== 207) { + while (node.body.kind !== 209) { node = node.body; write("."); writeTextOfNode(currentSourceFile, node.name); @@ -19604,7 +20993,7 @@ var ts; writeLine(); } function isPrivateMethodTypeParameter(node) { - return node.parent.kind === 135 && (node.parent.flags & 32); + return node.parent.kind === 136 && (node.parent.flags & 32); } function emitTypeParameters(typeParameters) { function emitTypeParameter(node) { @@ -19614,15 +21003,15 @@ var ts; writeTextOfNode(currentSourceFile, node.name); if (node.constraint && !isPrivateMethodTypeParameter(node)) { write(" extends "); - if (node.parent.kind === 143 || - node.parent.kind === 144 || - (node.parent.parent && node.parent.parent.kind === 146)) { - ts.Debug.assert(node.parent.kind === 135 || - node.parent.kind === 134 || - node.parent.kind === 143 || - node.parent.kind === 144 || - node.parent.kind === 139 || - node.parent.kind === 140); + if (node.parent.kind === 145 || + node.parent.kind === 146 || + (node.parent.parent && node.parent.parent.kind === 148)) { + ts.Debug.assert(node.parent.kind === 136 || + node.parent.kind === 135 || + node.parent.kind === 145 || + node.parent.kind === 146 || + node.parent.kind === 140 || + node.parent.kind === 141); emitType(node.constraint); } else { @@ -19632,31 +21021,31 @@ var ts; function getTypeParameterConstraintVisibilityError(symbolAccesibilityResult) { var diagnosticMessage; switch (node.parent.kind) { - case 202: + case 204: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_class_has_or_is_using_private_name_1; break; - case 203: + case 205: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1; break; - case 140: + case 141: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1; break; - case 139: + case 140: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1; break; + case 136: case 135: - case 134: if (node.parent.flags & 128) { diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1; } - else if (node.parent.parent.kind === 202) { + else if (node.parent.parent.kind === 204) { diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1; } else { diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1; } break; - case 201: + case 203: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_function_has_or_is_using_private_name_1; break; default: @@ -19686,7 +21075,7 @@ var ts; } function getHeritageClauseVisibilityError(symbolAccesibilityResult) { var diagnosticMessage; - if (node.parent.parent.kind === 202) { + if (node.parent.parent.kind === 204) { diagnosticMessage = isImplementsList ? ts.Diagnostics.Implements_clause_of_exported_class_0_has_or_is_using_private_name_1 : ts.Diagnostics.Extends_clause_of_exported_class_0_has_or_is_using_private_name_1; @@ -19763,16 +21152,16 @@ var ts; writeLine(); } function emitVariableDeclaration(node) { - if (node.kind !== 199 || resolver.isDeclarationVisible(node)) { + if (node.kind !== 201 || resolver.isDeclarationVisible(node)) { if (ts.isBindingPattern(node.name)) { emitBindingPattern(node.name); } else { writeTextOfNode(currentSourceFile, node.name); - if ((node.kind === 133 || node.kind === 132) && ts.hasQuestionToken(node)) { + if ((node.kind === 134 || node.kind === 133) && ts.hasQuestionToken(node)) { write("?"); } - if ((node.kind === 133 || node.kind === 132) && node.parent.kind === 146) { + if ((node.kind === 134 || node.kind === 133) && node.parent.kind === 148) { emitTypeOfVariableDeclarationFromTypeLiteral(node); } else if (!(node.flags & 32)) { @@ -19781,14 +21170,14 @@ var ts; } } function getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccesibilityResult) { - if (node.kind === 199) { + if (node.kind === 201) { return symbolAccesibilityResult.errorModuleName ? symbolAccesibilityResult.accessibility === 2 ? ts.Diagnostics.Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : ts.Diagnostics.Exported_variable_0_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Exported_variable_0_has_or_is_using_private_name_1; } - else if (node.kind === 133 || node.kind === 132) { + else if (node.kind === 134 || node.kind === 133) { if (node.flags & 128) { return symbolAccesibilityResult.errorModuleName ? symbolAccesibilityResult.accessibility === 2 ? @@ -19796,7 +21185,7 @@ var ts; ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_private_name_1; } - else if (node.parent.kind === 202) { + else if (node.parent.kind === 204) { return symbolAccesibilityResult.errorModuleName ? symbolAccesibilityResult.accessibility === 2 ? ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : @@ -19822,7 +21211,7 @@ var ts; var elements = []; for (var _i = 0, _a = bindingPattern.elements; _i < _a.length; _i++) { var element = _a[_i]; - if (element.kind !== 176) { + if (element.kind !== 178) { elements.push(element); } } @@ -19888,7 +21277,7 @@ var ts; accessorWithTypeAnnotation = node; var type = getTypeAnnotationFromAccessor(node); if (!type) { - var anotherAccessor = node.kind === 137 ? accessors.setAccessor : accessors.getAccessor; + var anotherAccessor = node.kind === 138 ? accessors.setAccessor : accessors.getAccessor; type = getTypeAnnotationFromAccessor(anotherAccessor); if (type) { accessorWithTypeAnnotation = anotherAccessor; @@ -19901,7 +21290,7 @@ var ts; } function getTypeAnnotationFromAccessor(accessor) { if (accessor) { - return accessor.kind === 137 + return accessor.kind === 138 ? accessor.type : accessor.parameters.length > 0 ? accessor.parameters[0].type @@ -19910,7 +21299,7 @@ var ts; } function getAccessorDeclarationTypeVisibilityError(symbolAccesibilityResult) { var diagnosticMessage; - if (accessorWithTypeAnnotation.kind === 138) { + if (accessorWithTypeAnnotation.kind === 139) { if (accessorWithTypeAnnotation.parent.flags & 128) { diagnosticMessage = symbolAccesibilityResult.errorModuleName ? ts.Diagnostics.Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_name_1_from_private_module_2 : @@ -19956,17 +21345,17 @@ var ts; } if (!resolver.isImplementationOfOverload(node)) { emitJsDocComments(node); - if (node.kind === 201) { + if (node.kind === 203) { emitModuleElementDeclarationFlags(node); } - else if (node.kind === 135) { + else if (node.kind === 136) { emitClassMemberDeclarationFlags(node); } - if (node.kind === 201) { + if (node.kind === 203) { write("function "); writeTextOfNode(currentSourceFile, node.name); } - else if (node.kind === 136) { + else if (node.kind === 137) { write("constructor"); } else { @@ -19983,11 +21372,11 @@ var ts; emitSignatureDeclaration(node); } function emitSignatureDeclaration(node) { - if (node.kind === 140 || node.kind === 144) { + if (node.kind === 141 || node.kind === 146) { write("new "); } emitTypeParameters(node.typeParameters); - if (node.kind === 141) { + if (node.kind === 142) { write("["); } else { @@ -19996,20 +21385,20 @@ var ts; var prevEnclosingDeclaration = enclosingDeclaration; enclosingDeclaration = node; emitCommaList(node.parameters, emitParameterDeclaration); - if (node.kind === 141) { + if (node.kind === 142) { write("]"); } else { write(")"); } - var isFunctionTypeOrConstructorType = node.kind === 143 || node.kind === 144; - if (isFunctionTypeOrConstructorType || node.parent.kind === 146) { + var isFunctionTypeOrConstructorType = node.kind === 145 || node.kind === 146; + if (isFunctionTypeOrConstructorType || node.parent.kind === 148) { if (node.type) { write(isFunctionTypeOrConstructorType ? " => " : ": "); emitType(node.type); } } - else if (node.kind !== 136 && !(node.flags & 32)) { + else if (node.kind !== 137 && !(node.flags & 32)) { writeReturnTypeAtSignature(node, getReturnTypeVisibilityError); } enclosingDeclaration = prevEnclosingDeclaration; @@ -20020,23 +21409,23 @@ var ts; function getReturnTypeVisibilityError(symbolAccesibilityResult) { var diagnosticMessage; switch (node.kind) { - case 140: + case 141: diagnosticMessage = symbolAccesibilityResult.errorModuleName ? ts.Diagnostics.Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0; break; - case 139: + case 140: diagnosticMessage = symbolAccesibilityResult.errorModuleName ? ts.Diagnostics.Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0; break; - case 141: + case 142: diagnosticMessage = symbolAccesibilityResult.errorModuleName ? ts.Diagnostics.Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0; break; + case 136: case 135: - case 134: if (node.flags & 128) { diagnosticMessage = symbolAccesibilityResult.errorModuleName ? symbolAccesibilityResult.accessibility === 2 ? @@ -20044,7 +21433,7 @@ var ts; ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0; } - else if (node.parent.kind === 202) { + else if (node.parent.kind === 204) { diagnosticMessage = symbolAccesibilityResult.errorModuleName ? symbolAccesibilityResult.accessibility === 2 ? ts.Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : @@ -20057,7 +21446,7 @@ var ts; ts.Diagnostics.Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0; } break; - case 201: + case 203: diagnosticMessage = symbolAccesibilityResult.errorModuleName ? symbolAccesibilityResult.accessibility === 2 ? ts.Diagnostics.Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : @@ -20089,9 +21478,9 @@ var ts; write("?"); } decreaseIndent(); - if (node.parent.kind === 143 || - node.parent.kind === 144 || - node.parent.parent.kind === 146) { + if (node.parent.kind === 145 || + node.parent.kind === 146 || + node.parent.parent.kind === 148) { emitTypeOfVariableDeclarationFromTypeLiteral(node); } else if (!(node.parent.flags & 32)) { @@ -20107,22 +21496,22 @@ var ts; } function getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccesibilityResult) { switch (node.parent.kind) { - case 136: + case 137: return symbolAccesibilityResult.errorModuleName ? symbolAccesibilityResult.accessibility === 2 ? ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1; - case 140: + case 141: return symbolAccesibilityResult.errorModuleName ? ts.Diagnostics.Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1; - case 139: + case 140: return symbolAccesibilityResult.errorModuleName ? ts.Diagnostics.Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1; + case 136: case 135: - case 134: if (node.parent.flags & 128) { return symbolAccesibilityResult.errorModuleName ? symbolAccesibilityResult.accessibility === 2 ? @@ -20130,7 +21519,7 @@ var ts; ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1; } - else if (node.parent.parent.kind === 202) { + else if (node.parent.parent.kind === 204) { return symbolAccesibilityResult.errorModuleName ? symbolAccesibilityResult.accessibility === 2 ? ts.Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : @@ -20142,7 +21531,7 @@ var ts; ts.Diagnostics.Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1; } - case 201: + case 203: return symbolAccesibilityResult.errorModuleName ? symbolAccesibilityResult.accessibility === 2 ? ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : @@ -20153,12 +21542,12 @@ var ts; } } function emitBindingPattern(bindingPattern) { - if (bindingPattern.kind === 151) { + if (bindingPattern.kind === 153) { write("{"); emitCommaList(bindingPattern.elements, emitBindingElement); write("}"); } - else if (bindingPattern.kind === 152) { + else if (bindingPattern.kind === 154) { write("["); var elements = bindingPattern.elements; emitCommaList(elements, emitBindingElement); @@ -20177,10 +21566,10 @@ var ts; typeName: bindingElement.name } : undefined; } - if (bindingElement.kind === 176) { + if (bindingElement.kind === 178) { write(" "); } - else if (bindingElement.kind === 153) { + else if (bindingElement.kind === 155) { if (bindingElement.propertyName) { writeTextOfNode(currentSourceFile, bindingElement.propertyName); write(": "); @@ -20203,39 +21592,39 @@ var ts; } function emitNode(node) { switch (node.kind) { - case 201: - case 206: - case 209: case 203: - case 202: - case 204: + case 208: + case 211: case 205: + case 204: + case 206: + case 207: return emitModuleElement(node, isModuleElementVisible(node)); - case 181: + case 183: return emitModuleElement(node, isVariableStatementVisible(node)); - case 210: + case 212: return emitModuleElement(node, !node.importClause); - case 216: + case 218: return emitExportDeclaration(node); + case 137: case 136: case 135: - case 134: return writeFunctionDeclaration(node); - case 140: - case 139: case 141: + case 140: + case 142: return emitSignatureDeclarationWithJsDocComments(node); - case 137: case 138: + case 139: return emitAccessorDeclaration(node); + case 134: case 133: - case 132: return emitPropertyDeclaration(node); - case 227: + case 229: return emitEnumMemberDeclaration(node); - case 215: + case 217: return emitExportAssignment(node); - case 228: + case 230: return emitSourceFile(node); } } @@ -20281,7 +21670,7 @@ var ts; } ts.isExternalModuleOrDeclarationFile = isExternalModuleOrDeclarationFile; function emitFiles(resolver, host, targetSourceFile) { - var extendsHelper = "\nvar __extends = (this && this.__extends) || function (d, b) {\n for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];\n function __() { this.constructor = d; }\n __.prototype = b.prototype;\n d.prototype = new __();\n};"; + var extendsHelper = "\nvar __extends = (this && this.__extends) || function (d, b) {\n for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n};"; var decorateHelper = "\nvar __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") return Reflect.decorate(decorators, target, key, desc);\n switch (arguments.length) {\n case 2: return decorators.reduceRight(function(o, d) { return (d && d(o)) || o; }, target);\n case 3: return decorators.reduceRight(function(o, d) { return (d && d(target, key)), void 0; }, void 0);\n case 4: return decorators.reduceRight(function(o, d) { return (d && d(target, key, o)) || o; }, desc);\n }\n};"; var metadataHelper = "\nvar __metadata = (this && this.__metadata) || function (k, v) {\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(k, v);\n};"; var paramHelper = "\nvar __param = (this && this.__param) || function (paramIndex, decorator) {\n return function (target, key) { decorator(target, key, paramIndex); }\n};"; @@ -20345,7 +21734,6 @@ var ts; var exportFunctionForFile; var generatedNameSet = {}; var nodeToGeneratedName = []; - var blockScopedVariableToGeneratedName; var computedPropertyNamesToGeneratedNames; var extendsEmitted = false; var decorateEmitted = false; @@ -20405,9 +21793,9 @@ var ts; var count = tempFlags & 268435455; tempFlags++; if (count !== 8 && count !== 13) { - var name_15 = count < 26 ? "_" + String.fromCharCode(97 + count) : "_" + (count - 26); - if (isUniqueName(name_15)) { - return name_15; + var name_17 = count < 26 ? "_" + String.fromCharCode(97 + count) : "_" + (count - 26); + if (isUniqueName(name_17)) { + return name_17; } } } @@ -20425,72 +21813,39 @@ var ts; i++; } } - function assignGeneratedName(node, name) { - nodeToGeneratedName[ts.getNodeId(node)] = ts.unescapeIdentifier(name); - } - function generateNameForFunctionOrClassDeclaration(node) { - if (!node.name) { - assignGeneratedName(node, makeUniqueName("default")); - } - } function generateNameForModuleOrEnum(node) { - if (node.name.kind === 65) { - var name_16 = node.name.text; - assignGeneratedName(node, isUniqueLocalName(name_16, node) ? name_16 : makeUniqueName(name_16)); - } + var name = node.name.text; + return isUniqueLocalName(name, node) ? name : makeUniqueName(name); } function generateNameForImportOrExportDeclaration(node) { var expr = ts.getExternalModuleName(node); var baseName = expr.kind === 8 ? ts.escapeIdentifier(ts.makeIdentifierFromModuleName(expr.text)) : "module"; - assignGeneratedName(node, makeUniqueName(baseName)); + return makeUniqueName(baseName); } - function generateNameForImportDeclaration(node) { - if (node.importClause) { - generateNameForImportOrExportDeclaration(node); - } - } - function generateNameForExportDeclaration(node) { - if (node.moduleSpecifier) { - generateNameForImportOrExportDeclaration(node); - } - } - function generateNameForExportAssignment(node) { - if (node.expression && node.expression.kind !== 65) { - assignGeneratedName(node, makeUniqueName("default")); - } + function generateNameForExportDefault() { + return makeUniqueName("default"); } function generateNameForNode(node) { switch (node.kind) { - case 201: - case 202: - case 175: - generateNameForFunctionOrClassDeclaration(node); - break; - case 206: - generateNameForModuleOrEnum(node); - generateNameForNode(node.body); - break; - case 205: - generateNameForModuleOrEnum(node); - break; - case 210: - generateNameForImportDeclaration(node); - break; - case 216: - generateNameForExportDeclaration(node); - break; - case 215: - generateNameForExportAssignment(node); - break; + case 65: + return makeUniqueName(node.text); + case 208: + case 207: + return generateNameForModuleOrEnum(node); + case 212: + case 218: + return generateNameForImportOrExportDeclaration(node); + case 203: + case 204: + case 177: + case 217: + return generateNameForExportDefault(); } } function getGeneratedNameForNode(node) { - var nodeId = ts.getNodeId(node); - if (!nodeToGeneratedName[nodeId]) { - generateNameForNode(node); - } - return nodeToGeneratedName[nodeId]; + var id = ts.getNodeId(node); + return nodeToGeneratedName[id] || (nodeToGeneratedName[id] = ts.unescapeIdentifier(generateNameForNode(node))); } function initializeEmitterWithSourceMaps() { var sourceMapDir; @@ -20514,7 +21869,7 @@ var ts; return; } var prevEncodedEmittedColumn = lastEncodedSourceMapSpan.emittedColumn; - if (lastEncodedSourceMapSpan.emittedLine == lastRecordedSourceMapSpan.emittedLine) { + if (lastEncodedSourceMapSpan.emittedLine === lastRecordedSourceMapSpan.emittedLine) { if (sourceMapData.sourceMapMappings) { sourceMapData.sourceMapMappings += ","; } @@ -20567,8 +21922,8 @@ var ts; var emittedLine = writer.getLine(); var emittedColumn = writer.getColumn(); if (!lastRecordedSourceMapSpan || - lastRecordedSourceMapSpan.emittedLine != emittedLine || - lastRecordedSourceMapSpan.emittedColumn != emittedColumn || + lastRecordedSourceMapSpan.emittedLine !== emittedLine || + lastRecordedSourceMapSpan.emittedColumn !== emittedColumn || (lastRecordedSourceMapSpan.sourceIndex === sourceMapSourceIndex && (lastRecordedSourceMapSpan.sourceLine > sourceLinePos.line || (lastRecordedSourceMapSpan.sourceLine === sourceLinePos.line && lastRecordedSourceMapSpan.sourceColumn > sourceLinePos.character)))) { @@ -20622,8 +21977,8 @@ var ts; if (scopeName) { var parentIndex = getSourceMapNameIndex(); if (parentIndex !== -1) { - var name_17 = node.name; - if (!name_17 || name_17.kind !== 128) { + var name_18 = node.name; + if (!name_18 || name_18.kind !== 129) { scopeName = "." + scopeName; } scopeName = sourceMapData.sourceMapNames[parentIndex] + scopeName; @@ -20640,19 +21995,19 @@ var ts; if (scopeName) { recordScopeNameStart(scopeName); } - else if (node.kind === 201 || - node.kind === 163 || + else if (node.kind === 203 || + node.kind === 165 || + node.kind === 136 || node.kind === 135 || - node.kind === 134 || - node.kind === 137 || node.kind === 138 || - node.kind === 206 || - node.kind === 202 || - node.kind === 205) { + node.kind === 139 || + node.kind === 208 || + node.kind === 204 || + node.kind === 207) { if (node.name) { - var name_18 = node.name; - scopeName = name_18.kind === 128 - ? ts.getTextOfNode(name_18) + var name_19 = node.name; + scopeName = name_19.kind === 129 + ? ts.getTextOfNode(name_19) : node.name.text; } recordScopeNameStart(scopeName); @@ -20745,19 +22100,19 @@ var ts; else { sourceMapDir = ts.getDirectoryPath(ts.normalizePath(jsFilePath)); } - function emitNodeWithSourceMap(node, allowGeneratedIdentifiers) { + function emitNodeWithSourceMap(node) { if (node) { if (ts.nodeIsSynthesized(node)) { - return emitNodeWithoutSourceMap(node, false); + return emitNodeWithoutSourceMap(node); } - if (node.kind != 228) { + if (node.kind !== 230) { recordEmitNodeStartSpan(node); - emitNodeWithoutSourceMap(node, allowGeneratedIdentifiers); + emitNodeWithoutSourceMap(node); recordEmitNodeEndSpan(node); } else { recordNewSourceFileStart(node); - emitNodeWithoutSourceMap(node, false); + emitNodeWithoutSourceMap(node); } } } @@ -20995,10 +22350,10 @@ var ts; emitParenthesizedIf(node.tag, needsParenthesisForPropertyAccessOrInvocation(node.tag)); write("("); emit(tempVariable); - if (node.template.kind === 172) { + if (node.template.kind === 174) { ts.forEach(node.template.templateSpans, function (templateSpan) { write(", "); - var needsParens = templateSpan.expression.kind === 170 + var needsParens = templateSpan.expression.kind === 172 && templateSpan.expression.operatorToken.kind === 23; emitParenthesizedIf(templateSpan.expression, needsParens); }); @@ -21022,7 +22377,7 @@ var ts; } for (var i = 0, n = node.templateSpans.length; i < n; i++) { var templateSpan = node.templateSpans[i]; - var needsParens = templateSpan.expression.kind !== 162 + var needsParens = templateSpan.expression.kind !== 164 && comparePrecedenceToBinaryPlus(templateSpan.expression) !== 1; if (i > 0 || headEmitted) { write(" + "); @@ -21055,11 +22410,11 @@ var ts; } function templateNeedsParens(template, parent) { switch (parent.kind) { - case 158: - case 159: - return parent.expression === template; case 160: + case 161: + return parent.expression === template; case 162: + case 164: return false; default: return comparePrecedenceToBinaryPlus(parent) !== -1; @@ -21067,7 +22422,7 @@ var ts; } function comparePrecedenceToBinaryPlus(expression) { switch (expression.kind) { - case 170: + case 172: switch (expression.operatorToken.kind) { case 35: case 36: @@ -21079,8 +22434,8 @@ var ts; default: return -1; } + case 175: case 173: - case 171: return -1; default: return 1; @@ -21092,11 +22447,11 @@ var ts; emit(span.literal); } function emitExpressionForPropertyName(node) { - ts.Debug.assert(node.kind !== 153); + ts.Debug.assert(node.kind !== 155); if (node.kind === 8) { emitLiteral(node); } - else if (node.kind === 128) { + else if (node.kind === 129) { if (ts.nodeIsDecorated(node.parent)) { if (!computedPropertyNamesToGeneratedNames) { computedPropertyNamesToGeneratedNames = []; @@ -21124,75 +22479,122 @@ var ts; write("\""); } } - function isNotExpressionIdentifier(node) { + function isExpressionIdentifier(node) { var parent = node.parent; switch (parent.kind) { - case 130: - case 199: - case 153: - case 133: + case 156: + case 172: + case 160: + case 223: + case 129: + case 173: case 132: - case 225: - case 226: + case 167: + case 187: + case 159: + case 217: + case 185: + case 179: + case 189: + case 190: + case 191: + case 186: + case 161: + case 164: + case 171: + case 170: + case 194: + case 228: + case 176: + case 196: + case 162: + case 180: + case 198: + case 163: + case 168: + case 169: + case 188: + case 195: + case 175: + return true; + case 155: + case 229: + case 131: case 227: - case 135: case 134: case 201: - case 137: - case 138: - case 163: - case 202: - case 203: - case 205: - case 206: - case 209: + return parent.initializer === node; + case 158: + return parent.expression === node; + case 166: + case 165: + return parent.body === node; case 211: - case 212: - return parent.name === node; - case 214: - case 218: - return parent.name === node || parent.propertyName === node; - case 191: - case 190: - case 215: - return false; - case 195: - return node.parent.label === node; + return parent.moduleReference === node; + case 128: + return parent.left === node; } + return false; } function emitExpressionIdentifier(node) { - var substitution = resolver.getExpressionNameSubstitution(node, getGeneratedNameForNode); - if (substitution) { - write(substitution); + var container = resolver.getReferencedExportContainer(node); + if (container) { + if (container.kind === 230) { + if (languageVersion < 2 && compilerOptions.module !== 4) { + write("exports."); + } + } + else { + write(getGeneratedNameForNode(container)); + write("."); + } } - else { - writeTextOfNode(currentSourceFile, node); - } - } - function getGeneratedNameForIdentifier(node) { - if (ts.nodeIsSynthesized(node) || !blockScopedVariableToGeneratedName) { - return undefined; - } - var variableId = resolver.getBlockScopedVariableId(node); - if (variableId === undefined) { - return undefined; - } - return blockScopedVariableToGeneratedName[variableId]; - } - function emitIdentifier(node, allowGeneratedIdentifiers) { - if (allowGeneratedIdentifiers) { - var generatedName = getGeneratedNameForIdentifier(node); - if (generatedName) { - write(generatedName); + else if (languageVersion < 2) { + var declaration = resolver.getReferencedImportDeclaration(node); + if (declaration) { + if (declaration.kind === 213) { + write(getGeneratedNameForNode(declaration.parent)); + write(languageVersion === 0 ? '["default"]' : ".default"); + return; + } + else if (declaration.kind === 216) { + write(getGeneratedNameForNode(declaration.parent.parent.parent)); + write("."); + writeTextOfNode(currentSourceFile, declaration.propertyName || declaration.name); + return; + } + } + declaration = resolver.getReferencedNestedRedeclaration(node); + if (declaration) { + write(getGeneratedNameForNode(declaration.name)); return; } } + writeTextOfNode(currentSourceFile, node); + } + function isNameOfNestedRedeclaration(node) { + if (languageVersion < 2) { + var parent_7 = node.parent; + switch (parent_7.kind) { + case 155: + case 204: + case 207: + case 201: + return parent_7.name === node && resolver.isNestedRedeclaration(parent_7); + } + } + return false; + } + function emitIdentifier(node) { if (!node.parent) { write(node.text); } - else if (!isNotExpressionIdentifier(node)) { + else if (isExpressionIdentifier(node)) { emitExpressionIdentifier(node); } + else if (isNameOfNestedRedeclaration(node)) { + write(getGeneratedNameForNode(node)); + } else { writeTextOfNode(currentSourceFile, node); } @@ -21233,7 +22635,7 @@ var ts; } function emitBindingElement(node) { if (node.propertyName) { - emit(node.propertyName, false); + emit(node.propertyName); write(": "); } if (node.dotDotDotToken) { @@ -21264,38 +22666,38 @@ var ts; function needsParenthesisForPropertyAccessOrInvocation(node) { switch (node.kind) { case 65: - case 154: case 156: - case 157: case 158: - case 162: + case 159: + case 160: + case 164: return false; } return true; } - function emitListWithSpread(elements, alwaysCopy, multiLine, trailingComma) { + function emitListWithSpread(elements, needsUniqueCopy, multiLine, trailingComma, useConcat) { var pos = 0; var group = 0; var length = elements.length; while (pos < length) { - if (group === 1) { + if (group === 1 && useConcat) { write(".concat("); } - else if (group > 1) { + else if (group > 0) { write(", "); } var e = elements[pos]; - if (e.kind === 174) { + if (e.kind === 176) { e = e.expression; emitParenthesizedIf(e, group === 0 && needsParenthesisForPropertyAccessOrInvocation(e)); pos++; - if (pos === length && group === 0 && alwaysCopy && e.kind !== 154) { + if (pos === length && group === 0 && needsUniqueCopy && e.kind !== 156) { write(".slice()"); } } else { var i = pos; - while (i < length && elements[i].kind !== 174) { + while (i < length && elements[i].kind !== 176) { i++; } write("["); @@ -21312,11 +22714,13 @@ var ts; group++; } if (group > 1) { - write(")"); + if (useConcat) { + write(")"); + } } } function isSpreadElementExpression(node) { - return node.kind === 174; + return node.kind === 176; } function emitArrayLiteral(node) { var elements = node.elements; @@ -21329,7 +22733,7 @@ var ts; write("]"); } else { - emitListWithSpread(elements, true, (node.flags & 512) !== 0, elements.hasTrailingComma); + emitListWithSpread(elements, true, (node.flags & 512) !== 0, elements.hasTrailingComma, true); } } function emitObjectLiteralBody(node, numElements) { @@ -21377,7 +22781,7 @@ var ts; writeComma(); var property = properties[i]; emitStart(property); - if (property.kind === 137 || property.kind === 138) { + if (property.kind === 138 || property.kind === 139) { var accessors = ts.getAllAccessorDeclarations(node.properties, property); if (property !== accessors.firstAccessor) { continue; @@ -21428,13 +22832,13 @@ var ts; emitMemberAccessForPropertyName(property.name); emitEnd(property.name); write(" = "); - if (property.kind === 225) { + if (property.kind === 227) { emit(property.initializer); } - else if (property.kind === 226) { + else if (property.kind === 228) { emitExpressionIdentifier(property.name); } - else if (property.kind === 135) { + else if (property.kind === 136) { emitFunctionDeclaration(property); } else { @@ -21466,7 +22870,7 @@ var ts; var numProperties = properties.length; var numInitialNonComputedProperties = numProperties; for (var i = 0, n = properties.length; i < n; i++) { - if (properties[i].name.kind === 128) { + if (properties[i].name.kind === 129) { numInitialNonComputedProperties = i; break; } @@ -21480,30 +22884,35 @@ var ts; emitObjectLiteralBody(node, properties.length); } function createBinaryExpression(left, operator, right, startsOnNewLine) { - var result = ts.createSynthesizedNode(170, startsOnNewLine); + var result = ts.createSynthesizedNode(172, startsOnNewLine); result.operatorToken = ts.createSynthesizedNode(operator); result.left = left; result.right = right; return result; } function createPropertyAccessExpression(expression, name) { - var result = ts.createSynthesizedNode(156); + var result = ts.createSynthesizedNode(158); result.expression = parenthesizeForAccess(expression); result.dotToken = ts.createSynthesizedNode(20); result.name = name; return result; } function createElementAccessExpression(expression, argumentExpression) { - var result = ts.createSynthesizedNode(157); + var result = ts.createSynthesizedNode(159); result.expression = parenthesizeForAccess(expression); result.argumentExpression = argumentExpression; return result; } function parenthesizeForAccess(expr) { - if (ts.isLeftHandSideExpression(expr) && expr.kind !== 159 && expr.kind !== 7) { + while (expr.kind === 163) { + expr = expr.expression; + } + if (ts.isLeftHandSideExpression(expr) && + expr.kind !== 161 && + expr.kind !== 7) { return expr; } - var node = ts.createSynthesizedNode(162); + var node = ts.createSynthesizedNode(164); node.expression = expr; return node; } @@ -21516,43 +22925,37 @@ var ts; if (languageVersion >= 2 && node.asteriskToken) { write("*"); } - emit(node.name, false); + emit(node.name); if (languageVersion < 2) { write(": function "); } emitSignatureAndBody(node); } function emitPropertyAssignment(node) { - emit(node.name, false); + emit(node.name); write(": "); emit(node.initializer); } + function isNamespaceExportReference(node) { + var container = resolver.getReferencedExportContainer(node); + return container && container.kind !== 230; + } function emitShorthandPropertyAssignment(node) { - emit(node.name, false); - if (languageVersion < 2) { + writeTextOfNode(currentSourceFile, node.name); + if (languageVersion < 2 || isNamespaceExportReference(node.name)) { write(": "); - var generatedName = getGeneratedNameForIdentifier(node.name); - if (generatedName) { - write(generatedName); - } - else { - emitExpressionIdentifier(node.name); - } - } - else if (resolver.getExpressionNameSubstitution(node.name, getGeneratedNameForNode)) { - write(": "); - emitExpressionIdentifier(node.name); + emit(node.name); } } function tryEmitConstantValue(node) { - if (compilerOptions.separateCompilation) { + if (compilerOptions.isolatedModules) { return false; } var constantValue = resolver.getConstantValue(node); if (constantValue !== undefined) { write(constantValue.toString()); if (!compilerOptions.removeComments) { - var propertyName = node.kind === 156 ? ts.declarationNameToString(node.name) : ts.getTextOfNode(node.argumentExpression); + var propertyName = node.kind === 158 ? ts.declarationNameToString(node.name) : ts.getTextOfNode(node.argumentExpression); write(" /* " + propertyName + " */"); } return true; @@ -21582,7 +22985,7 @@ var ts; var indentedBeforeDot = indentIfOnDifferentLines(node, node.expression, node.dotToken); write("."); var indentedAfterDot = indentIfOnDifferentLines(node, node.dotToken, node.name); - emit(node.name, false); + emit(node.name); decreaseIndentIf(indentedBeforeDot, indentedAfterDot); } function emitQualifiedName(node) { @@ -21600,10 +23003,10 @@ var ts; write("]"); } function hasSpreadElement(elements) { - return ts.forEach(elements, function (e) { return e.kind === 174; }); + return ts.forEach(elements, function (e) { return e.kind === 176; }); } function skipParentheses(node) { - while (node.kind === 162 || node.kind === 161) { + while (node.kind === 164 || node.kind === 163) { node = node.expression; } return node; @@ -21624,12 +23027,12 @@ var ts; function emitCallWithSpread(node) { var target; var expr = skipParentheses(node.expression); - if (expr.kind === 156) { + if (expr.kind === 158) { target = emitCallTarget(expr.expression); write("."); emit(expr.name); } - else if (expr.kind === 157) { + else if (expr.kind === 159) { target = emitCallTarget(expr.expression); write("["); emit(expr.argumentExpression); @@ -21655,7 +23058,7 @@ var ts; write("void 0"); } write(", "); - emitListWithSpread(node.arguments, false, false, false); + emitListWithSpread(node.arguments, false, false, false, true); write(")"); } function emitCallExpression(node) { @@ -21670,7 +23073,7 @@ var ts; } else { emit(node.expression); - superCall = node.expression.kind === 156 && node.expression.expression.kind === 91; + superCall = node.expression.kind === 158 && node.expression.expression.kind === 91; } if (superCall && languageVersion < 2) { write(".call("); @@ -21689,11 +23092,25 @@ var ts; } function emitNewExpression(node) { write("new "); - emit(node.expression); - if (node.arguments) { + if (languageVersion === 1 && + node.arguments && + hasSpreadElement(node.arguments)) { write("("); - emitCommaList(node.arguments); - write(")"); + var target = emitCallTarget(node.expression); + write(".bind.apply("); + emit(target); + write(", [void 0].concat("); + emitListWithSpread(node.arguments, false, false, false, false); + write(")))"); + write("()"); + } + else { + emit(node.expression); + if (node.arguments) { + write("("); + emitCommaList(node.arguments); + write(")"); + } } } function emitTaggedTemplateExpression(node) { @@ -21707,20 +23124,20 @@ var ts; } } function emitParenExpression(node) { - if (!node.parent || node.parent.kind !== 164) { - if (node.expression.kind === 161) { + if (!ts.nodeIsSynthesized(node) && node.parent.kind !== 166) { + if (node.expression.kind === 163) { var operand = node.expression.expression; - while (operand.kind == 161) { + while (operand.kind === 163) { operand = operand.expression; } - if (operand.kind !== 168 && - operand.kind !== 167 && - operand.kind !== 166 && - operand.kind !== 165 && + if (operand.kind !== 170 && operand.kind !== 169 && - operand.kind !== 159 && - !(operand.kind === 158 && node.parent.kind === 159) && - !(operand.kind === 163 && node.parent.kind === 158)) { + operand.kind !== 168 && + operand.kind !== 167 && + operand.kind !== 171 && + operand.kind !== 161 && + !(operand.kind === 160 && node.parent.kind === 161) && + !(operand.kind === 165 && node.parent.kind === 160)) { emit(operand); return; } @@ -21749,7 +23166,7 @@ var ts; if (!isCurrentFileSystemExternalModule() || node.kind !== 65 || ts.nodeIsSynthesized(node)) { return false; } - var isVariableDeclarationOrBindingElement = node.parent && (node.parent.kind === 199 || node.parent.kind === 153); + var isVariableDeclarationOrBindingElement = node.parent && (node.parent.kind === 201 || node.parent.kind === 155); var targetDeclaration = isVariableDeclarationOrBindingElement ? node.parent : resolver.getReferencedValueDeclaration(node); @@ -21763,7 +23180,7 @@ var ts; write("\", "); } write(ts.tokenToString(node.operator)); - if (node.operand.kind === 168) { + if (node.operand.kind === 170) { var operand = node.operand; if (node.operator === 33 && (operand.operator === 33 || operand.operator === 38)) { write(" "); @@ -21806,10 +23223,10 @@ var ts; } var current = node; while (current) { - if (current.kind === 228) { + if (current.kind === 230) { return !isExported || ((ts.getCombinedNodeFlags(node) & 1) !== 0); } - else if (ts.isFunctionLike(current) || current.kind === 207) { + else if (ts.isFunctionLike(current) || current.kind === 209) { return false; } else { @@ -21819,8 +23236,8 @@ var ts; } function emitBinaryExpression(node) { if (languageVersion < 2 && node.operatorToken.kind === 53 && - (node.left.kind === 155 || node.left.kind === 154)) { - emitDestructuring(node, node.parent.kind === 183); + (node.left.kind === 157 || node.left.kind === 156)) { + emitDestructuring(node, node.parent.kind === 185); } else { var exportChanged = node.operatorToken.kind >= 53 && @@ -21867,7 +23284,7 @@ var ts; } } function isSingleLineEmptyBlock(node) { - if (node && node.kind === 180) { + if (node && node.kind === 182) { var block = node; return block.statements.length === 0 && nodeEndIsOnSameLineAsNodeStart(block, block); } @@ -21882,12 +23299,12 @@ var ts; emitToken(14, node.pos); increaseIndent(); scopeEmitStart(node.parent); - if (node.kind === 207) { - ts.Debug.assert(node.parent.kind === 206); + if (node.kind === 209) { + ts.Debug.assert(node.parent.kind === 208); emitCaptureThisForNodeIfNecessary(node.parent); } emitLines(node.statements); - if (node.kind === 207) { + if (node.kind === 209) { emitTempDeclarations(true); } decreaseIndent(); @@ -21896,7 +23313,7 @@ var ts; scopeEmitEnd(); } function emitEmbeddedStatement(node) { - if (node.kind === 180) { + if (node.kind === 182) { write(" "); emit(node); } @@ -21908,7 +23325,7 @@ var ts; } } function emitExpressionStatement(node) { - emitParenthesizedIf(node.expression, node.expression.kind === 164); + emitParenthesizedIf(node.expression, node.expression.kind === 166); write(";"); } function emitIfStatement(node) { @@ -21921,7 +23338,7 @@ var ts; if (node.elseStatement) { writeLine(); emitToken(76, node.thenStatement.end); - if (node.elseStatement.kind === 184) { + if (node.elseStatement.kind === 186) { write(" "); emit(node.elseStatement); } @@ -21933,7 +23350,7 @@ var ts; function emitDoStatement(node) { write("do"); emitEmbeddedStatement(node.statement); - if (node.statement.kind === 180) { + if (node.statement.kind === 182) { write(" "); } else { @@ -22002,7 +23419,7 @@ var ts; var endPos = emitToken(82, node.pos); write(" "); endPos = emitToken(16, endPos); - if (node.initializer && node.initializer.kind === 200) { + if (node.initializer && node.initializer.kind === 202) { var variableDeclarationList = node.initializer; var startIsEmitted = tryEmitStartOfVariableDeclarationList(variableDeclarationList, endPos); if (startIsEmitted) { @@ -22023,13 +23440,13 @@ var ts; emitEmbeddedStatement(node.statement); } function emitForInOrForOfStatement(node) { - if (languageVersion < 2 && node.kind === 189) { + if (languageVersion < 2 && node.kind === 191) { return emitDownLevelForOfStatement(node); } var endPos = emitToken(82, node.pos); write(" "); endPos = emitToken(16, endPos); - if (node.initializer.kind === 200) { + if (node.initializer.kind === 202) { var variableDeclarationList = node.initializer; if (variableDeclarationList.declarations.length >= 1) { tryEmitStartOfVariableDeclarationList(variableDeclarationList, endPos); @@ -22039,7 +23456,7 @@ var ts; else { emit(node.initializer); } - if (node.kind === 188) { + if (node.kind === 190) { write(" in "); } else { @@ -22107,7 +23524,7 @@ var ts; increaseIndent(); var rhsIterationValue = createElementAccessExpression(rhsReference, counter); emitStart(node.initializer); - if (node.initializer.kind === 200) { + if (node.initializer.kind === 202) { write("var "); var variableDeclarationList = node.initializer; if (variableDeclarationList.declarations.length > 0) { @@ -22129,7 +23546,7 @@ var ts; } else { var assignmentExpression = createBinaryExpression(node.initializer, 53, rhsIterationValue, false); - if (node.initializer.kind === 154 || node.initializer.kind === 155) { + if (node.initializer.kind === 156 || node.initializer.kind === 157) { emitDestructuring(assignmentExpression, true, undefined); } else { @@ -22138,7 +23555,7 @@ var ts; } emitEnd(node.initializer); write(";"); - if (node.statement.kind === 180) { + if (node.statement.kind === 182) { emitLines(node.statement.statements); } else { @@ -22150,7 +23567,7 @@ var ts; write("}"); } function emitBreakOrContinueStatement(node) { - emitToken(node.kind === 191 ? 66 : 71, node.pos); + emitToken(node.kind === 193 ? 66 : 71, node.pos); emitOptional(" ", node.label); write(";"); } @@ -22195,7 +23612,7 @@ var ts; ts.getLineOfLocalPosition(currentSourceFile, ts.skipTrivia(currentSourceFile.text, node2.pos)); } function emitCaseOrDefaultClause(node) { - if (node.kind === 221) { + if (node.kind === 223) { write("case "); emit(node.expression); write(":"); @@ -22250,7 +23667,7 @@ var ts; function getContainingModule(node) { do { node = node.parent; - } while (node && node.kind !== 206); + } while (node && node.kind !== 208); return node; } function emitContainingModuleName(node) { @@ -22275,7 +23692,7 @@ var ts; function createVoidZero() { var zero = ts.createSynthesizedNode(7); zero.text = "0"; - var result = ts.createSynthesizedNode(167); + var result = ts.createSynthesizedNode(169); result.expression = zero; return result; } @@ -22344,15 +23761,15 @@ var ts; function emitDestructuring(root, isAssignmentExpressionStatement, value) { var emitCount = 0; var canDefineTempVariablesInPlace = false; - if (root.kind === 199) { + if (root.kind === 201) { var isExported = ts.getCombinedNodeFlags(root) & 1; var isSourceLevelForSystemModuleKind = shouldHoistDeclarationInSystemJsModule(root); canDefineTempVariablesInPlace = !isExported && !isSourceLevelForSystemModuleKind; } - else if (root.kind === 130) { + else if (root.kind === 131) { canDefineTempVariablesInPlace = true; } - if (root.kind === 170) { + if (root.kind === 172) { emitAssignmentExpression(root); } else { @@ -22363,8 +23780,7 @@ var ts; if (emitCount++) { write(", "); } - renameNonTopLevelLetAndConst(name); - var isVariableDeclarationOrBindingElement = name.parent && (name.parent.kind === 199 || name.parent.kind === 153); + var isVariableDeclarationOrBindingElement = name.parent && (name.parent.kind === 201 || name.parent.kind === 155); var exportChanged = isNameOfExportedSourceLevelDeclarationInSystemExternalModule(name); if (exportChanged) { write(exportFunctionForFile + "(\""); @@ -22396,14 +23812,14 @@ var ts; } function createDefaultValueCheck(value, defaultValue) { value = ensureIdentifier(value); - var equals = ts.createSynthesizedNode(170); + var equals = ts.createSynthesizedNode(172); equals.left = value; equals.operatorToken = ts.createSynthesizedNode(30); equals.right = createVoidZero(); return createConditionalExpression(equals, defaultValue, value); } function createConditionalExpression(condition, whenTrue, whenFalse) { - var cond = ts.createSynthesizedNode(171); + var cond = ts.createSynthesizedNode(173); cond.condition = condition; cond.questionToken = ts.createSynthesizedNode(50); cond.whenTrue = whenTrue; @@ -22417,13 +23833,15 @@ var ts; return node; } function createPropertyAccessForDestructuringProperty(object, propName) { - if (propName.kind !== 65) { - return createElementAccessExpression(object, propName); + var syntheticName = ts.createSynthesizedNode(propName.kind); + syntheticName.text = propName.text; + if (syntheticName.kind !== 65) { + return createElementAccessExpression(object, syntheticName); } - return createPropertyAccessExpression(object, propName); + return createPropertyAccessExpression(object, syntheticName); } function createSliceCall(value, sliceIndex) { - var call = ts.createSynthesizedNode(158); + var call = ts.createSynthesizedNode(160); var sliceIdentifier = ts.createSynthesizedNode(65); sliceIdentifier.text = "slice"; call.expression = createPropertyAccessExpression(value, sliceIdentifier); @@ -22438,8 +23856,8 @@ var ts; } for (var _a = 0; _a < properties.length; _a++) { var p = properties[_a]; - if (p.kind === 225 || p.kind === 226) { - var propName = (p.name); + if (p.kind === 227 || p.kind === 228) { + var propName = p.name; emitDestructuringAssignment(p.initializer || propName, createPropertyAccessForDestructuringProperty(value, propName)); } } @@ -22451,8 +23869,8 @@ var ts; } for (var i = 0; i < elements.length; i++) { var e = elements[i]; - if (e.kind !== 176) { - if (e.kind !== 174) { + if (e.kind !== 178) { + if (e.kind !== 176) { emitDestructuringAssignment(e, createElementAccessExpression(value, createNumericLiteral(i))); } else if (i === elements.length - 1) { @@ -22462,14 +23880,14 @@ var ts; } } function emitDestructuringAssignment(target, value) { - if (target.kind === 170 && target.operatorToken.kind === 53) { + if (target.kind === 172 && target.operatorToken.kind === 53) { value = createDefaultValueCheck(value, target.right); target = target.left; } - if (target.kind === 155) { + if (target.kind === 157) { emitObjectLiteralAssignment(target, value); } - else if (target.kind === 154) { + else if (target.kind === 156) { emitArrayLiteralAssignment(target, value); } else { @@ -22483,14 +23901,14 @@ var ts; emitDestructuringAssignment(target, value); } else { - if (root.parent.kind !== 162) { + if (root.parent.kind !== 164) { write("("); } value = ensureIdentifier(value); emitDestructuringAssignment(target, value); write(", "); emit(value); - if (root.parent.kind !== 162) { + if (root.parent.kind !== 164) { write(")"); } } @@ -22510,11 +23928,11 @@ var ts; } for (var i = 0; i < elements.length; i++) { var element = elements[i]; - if (pattern.kind === 151) { + if (pattern.kind === 153) { var propName = element.propertyName || element.name; emitBindingElement(element, createPropertyAccessForDestructuringProperty(value, propName)); } - else if (element.kind !== 176) { + else if (element.kind !== 178) { if (!element.dotDotDotToken) { emitBindingElement(element, createElementAccessExpression(value, createNumericLiteral(i))); } @@ -22540,14 +23958,13 @@ var ts; } } else { - renameNonTopLevelLetAndConst(node.name); var initializer = node.initializer; if (!initializer && languageVersion < 2) { var isUninitializedLet = (resolver.getNodeCheckFlags(node) & 256) && (getCombinedFlagsForIdentifier(node.name) & 4096); if (isUninitializedLet && - node.parent.parent.kind !== 188 && - node.parent.parent.kind !== 189) { + node.parent.parent.kind !== 190 && + node.parent.parent.kind !== 191) { initializer = createVoidZero(); } } @@ -22565,7 +23982,7 @@ var ts; } } function emitExportVariableAssignments(node) { - if (node.kind === 176) { + if (node.kind === 178) { return; } var name = node.name; @@ -22577,48 +23994,15 @@ var ts; } } function getCombinedFlagsForIdentifier(node) { - if (!node.parent || (node.parent.kind !== 199 && node.parent.kind !== 153)) { + if (!node.parent || (node.parent.kind !== 201 && node.parent.kind !== 155)) { return 0; } return ts.getCombinedNodeFlags(node.parent); } - function renameNonTopLevelLetAndConst(node) { - if (languageVersion >= 2 || - ts.nodeIsSynthesized(node) || - node.kind !== 65 || - (node.parent.kind !== 199 && node.parent.kind !== 153)) { - return; - } - var combinedFlags = getCombinedFlagsForIdentifier(node); - if (((combinedFlags & 12288) === 0) || combinedFlags & 1) { - return; - } - var list = ts.getAncestor(node, 200); - if (list.parent.kind === 181) { - var isSourceFileLevelBinding = list.parent.parent.kind === 228; - var isModuleLevelBinding = list.parent.parent.kind === 207; - var isFunctionLevelBinding = list.parent.parent.kind === 180 && ts.isFunctionLike(list.parent.parent.parent); - if (isSourceFileLevelBinding || isModuleLevelBinding || isFunctionLevelBinding) { - return; - } - } - var blockScopeContainer = ts.getEnclosingBlockScopeContainer(node); - var parent = blockScopeContainer.kind === 228 - ? blockScopeContainer - : blockScopeContainer.parent; - if (resolver.resolvesToSomeValue(parent, node.text)) { - var variableId = resolver.getBlockScopedVariableId(node); - if (!blockScopedVariableToGeneratedName) { - blockScopedVariableToGeneratedName = []; - } - var generatedName = makeUniqueName(node.text); - blockScopedVariableToGeneratedName[variableId] = generatedName; - } - } function isES6ExportedDeclaration(node) { return !!(node.flags & 1) && languageVersion >= 2 && - node.parent.kind === 228; + node.parent.kind === 230; } function emitVariableStatement(node) { var startIsEmitted = false; @@ -22645,15 +24029,30 @@ var ts; ts.forEach(node.declarationList.declarations, emitExportVariableAssignments); } } + function shouldEmitLeadingAndTrailingCommentsForVariableStatement(node) { + if (!(node.flags & 1)) { + return true; + } + if (isES6ExportedDeclaration(node)) { + return true; + } + for (var _a = 0, _b = node.declarationList.declarations; _a < _b.length; _a++) { + var declaration = _b[_a]; + if (declaration.initializer) { + return true; + } + } + return false; + } function emitParameter(node) { if (languageVersion < 2) { if (ts.isBindingPattern(node.name)) { - var name_19 = createTempVariable(0); + var name_20 = createTempVariable(0); if (!tempParameters) { tempParameters = []; } - tempParameters.push(name_19); - emit(name_19); + tempParameters.push(name_20); + emit(name_20); } else { emit(node.name); @@ -22700,7 +24099,7 @@ var ts; } } function emitRestParameter(node) { - if (languageVersion < 2 && ts.hasRestParameters(node)) { + if (languageVersion < 2 && ts.hasRestParameter(node)) { var restIndex = node.parameters.length - 1; var restParam = node.parameters[restIndex]; if (ts.isBindingPattern(restParam.name)) { @@ -22741,12 +24140,12 @@ var ts; } } function emitAccessor(node) { - write(node.kind === 137 ? "get " : "set "); - emit(node.name, false); + write(node.kind === 138 ? "get " : "set "); + emit(node.name); emitSignatureAndBody(node); } function shouldEmitAsArrowFunction(node) { - return node.kind === 164 && languageVersion >= 2; + return node.kind === 166 && languageVersion >= 2; } function emitDeclarationName(node) { if (node.name) { @@ -22757,10 +24156,10 @@ var ts; } } function shouldEmitFunctionName(node) { - if (node.kind === 163) { + if (node.kind === 165) { return !!node.name; } - if (node.kind === 201) { + if (node.kind === 203) { return !!node.name || languageVersion < 2; } } @@ -22768,7 +24167,7 @@ var ts; if (ts.nodeIsMissing(node.body)) { return emitOnlyPinnedOrTripleSlashComments(node); } - if (node.kind !== 135 && node.kind !== 134) { + if (node.kind !== 136 && node.kind !== 135) { emitLeadingComments(node); } if (!shouldEmitAsArrowFunction(node)) { @@ -22788,10 +24187,10 @@ var ts; emitDeclarationName(node); } emitSignatureAndBody(node); - if (languageVersion < 2 && node.kind === 201 && node.parent === currentSourceFile && node.name) { + if (languageVersion < 2 && node.kind === 203 && node.parent === currentSourceFile && node.name) { emitExportMemberAssignments(node.name); } - if (node.kind !== 135 && node.kind !== 134) { + if (node.kind !== 136 && node.kind !== 135) { emitTrailingComments(node); } } @@ -22808,7 +24207,7 @@ var ts; write("("); if (node) { var parameters = node.parameters; - var omitCount = languageVersion < 2 && ts.hasRestParameters(node) ? 1 : 0; + var omitCount = languageVersion < 2 && ts.hasRestParameter(node) ? 1 : 0; emitList(parameters, 0, parameters.length - omitCount, false, false); } write(")"); @@ -22838,7 +24237,7 @@ var ts; if (!node.body) { write(" { }"); } - else if (node.body.kind === 180) { + else if (node.body.kind === 182) { emitBlockFunctionBody(node, node.body); } else { @@ -22863,10 +24262,10 @@ var ts; } write(" "); var current = body; - while (current.kind === 161) { + while (current.kind === 163) { current = current.expression; } - emitParenthesizedIf(body, current.kind === 155); + emitParenthesizedIf(body, current.kind === 157); } function emitDownLevelExpressionFunctionBody(node, body) { write(" {"); @@ -22938,9 +24337,9 @@ var ts; function findInitialSuperCall(ctor) { if (ctor.body) { var statement = ctor.body.statements[0]; - if (statement && statement.kind === 183) { + if (statement && statement.kind === 185) { var expr = statement.expression; - if (expr && expr.kind === 158) { + if (expr && expr.kind === 160) { var func = expr.expression; if (func && func.kind === 91) { return statement; @@ -22971,7 +24370,7 @@ var ts; emitNodeWithoutSourceMap(memberName); write("]"); } - else if (memberName.kind === 128) { + else if (memberName.kind === 129) { emitComputedPropertyName(memberName); } else { @@ -22983,7 +24382,7 @@ var ts; var properties = []; for (var _a = 0, _b = node.members; _a < _b.length; _a++) { var member = _b[_a]; - if (member.kind === 133 && isStatic === ((member.flags & 128) !== 0) && member.initializer) { + if (member.kind === 134 && isStatic === ((member.flags & 128) !== 0) && member.initializer) { properties.push(member); } } @@ -23023,11 +24422,11 @@ var ts; } function emitMemberFunctionsForES5AndLower(node) { ts.forEach(node.members, function (member) { - if (member.kind === 179) { + if (member.kind === 181) { writeLine(); write(";"); } - else if (member.kind === 135 || node.kind === 134) { + else if (member.kind === 136 || node.kind === 135) { if (!member.body) { return emitOnlyPinnedOrTripleSlashComments(member); } @@ -23046,7 +24445,7 @@ var ts; write(";"); emitTrailingComments(member); } - else if (member.kind === 137 || member.kind === 138) { + else if (member.kind === 138 || member.kind === 139) { var accessors = ts.getAllAccessorDeclarations(node.members, member); if (member === accessors.firstAccessor) { writeLine(); @@ -23096,22 +24495,22 @@ var ts; function emitMemberFunctionsForES6AndHigher(node) { for (var _a = 0, _b = node.members; _a < _b.length; _a++) { var member = _b[_a]; - if ((member.kind === 135 || node.kind === 134) && !member.body) { + if ((member.kind === 136 || node.kind === 135) && !member.body) { emitOnlyPinnedOrTripleSlashComments(member); } - else if (member.kind === 135 || - member.kind === 137 || - member.kind === 138) { + else if (member.kind === 136 || + member.kind === 138 || + member.kind === 139) { writeLine(); emitLeadingComments(member); emitStart(member); if (member.flags & 128) { write("static "); } - if (member.kind === 137) { + if (member.kind === 138) { write("get "); } - else if (member.kind === 138) { + else if (member.kind === 139) { write("set "); } if (member.asteriskToken) { @@ -23122,7 +24521,7 @@ var ts; emitEnd(member); emitTrailingComments(member); } - else if (member.kind === 179) { + else if (member.kind === 181) { writeLine(); write(";"); } @@ -23143,10 +24542,10 @@ var ts; function emitConstructorWorker(node, baseTypeElement) { var hasInstancePropertyWithInitializer = false; ts.forEach(node.members, function (member) { - if (member.kind === 136 && !member.body) { + if (member.kind === 137 && !member.body) { emitOnlyPinnedOrTripleSlashComments(member); } - if (member.kind === 133 && member.initializer && (member.flags & 128) === 0) { + if (member.kind === 134 && member.initializer && (member.flags & 128) === 0) { hasInstancePropertyWithInitializer = true; } }); @@ -23246,7 +24645,7 @@ var ts; } function emitClassLikeDeclarationForES6AndHigher(node) { var thisNodeIsDecorated = ts.nodeIsDecorated(node); - if (node.kind === 202) { + if (node.kind === 204) { if (thisNodeIsDecorated) { if (isES6ExportedDeclaration(node) && !(node.flags & 256)) { write("export "); @@ -23263,7 +24662,7 @@ var ts; } } var staticProperties = getInitializedProperties(node, true); - var isClassExpressionWithStaticProperties = staticProperties.length > 0 && node.kind === 175; + var isClassExpressionWithStaticProperties = staticProperties.length > 0 && node.kind === 177; var tempVariable; if (isClassExpressionWithStaticProperties) { tempVariable = createAndRecordTempVariable(0); @@ -23330,7 +24729,7 @@ var ts; } } function emitClassLikeDeclarationBelowES6(node) { - if (node.kind === 202) { + if (node.kind === 204) { if (!shouldHoistDeclarationInSystemJsModule(node)) { write("var "); } @@ -23388,11 +24787,11 @@ var ts; emit(baseTypeNode.expression); } write(")"); - if (node.kind === 202) { + if (node.kind === 204) { write(";"); } emitEnd(node); - if (node.kind === 202) { + if (node.kind === 204) { emitExportMemberAssignment(node); } if (languageVersion < 2 && node.parent === currentSourceFile && node.name) { @@ -23466,13 +24865,13 @@ var ts; } else { decorators = member.decorators; - if (member.kind === 135) { + if (member.kind === 136) { functionLikeMember = member; } } writeLine(); emitStart(member); - if (member.kind !== 133) { + if (member.kind !== 134) { write("Object.defineProperty("); emitStart(member.name); emitClassMemberPrefix(node, member); @@ -23502,7 +24901,7 @@ var ts; write(", "); emitExpressionForPropertyName(member.name); emitEnd(member.name); - if (member.kind !== 133) { + if (member.kind !== 134) { write(", Object.getOwnPropertyDescriptor("); emitStart(member.name); emitClassMemberPrefix(node, member); @@ -23541,26 +24940,26 @@ var ts; } function shouldEmitTypeMetadata(node) { switch (node.kind) { - case 135: - case 137: + case 136: case 138: - case 133: + case 139: + case 134: return true; } return false; } function shouldEmitReturnTypeMetadata(node) { switch (node.kind) { - case 135: + case 136: return true; } return false; } function shouldEmitParamTypesMetadata(node) { switch (node.kind) { - case 202: - case 135: - case 138: + case 204: + case 136: + case 139: return true; } return false; @@ -23569,7 +24968,7 @@ var ts; var argumentsWritten = 0; if (compilerOptions.emitDecoratorMetadata) { if (shouldEmitTypeMetadata(node)) { - var serializedType = resolver.serializeTypeOfNode(node, getGeneratedNameForNode); + var serializedType = resolver.serializeTypeOfNode(node); if (serializedType) { if (writeComma) { write(", "); @@ -23582,7 +24981,7 @@ var ts; } } if (shouldEmitParamTypesMetadata(node)) { - var serializedTypes = resolver.serializeParameterTypesOfNode(node, getGeneratedNameForNode); + var serializedTypes = resolver.serializeParameterTypesOfNode(node); if (serializedTypes) { if (writeComma || argumentsWritten) { write(", "); @@ -23600,7 +24999,7 @@ var ts; } } if (shouldEmitReturnTypeMetadata(node)) { - var serializedType = resolver.serializeReturnTypeOfNode(node, getGeneratedNameForNode); + var serializedType = resolver.serializeReturnTypeOfNode(node); if (serializedType) { if (writeComma || argumentsWritten) { write(", "); @@ -23641,7 +25040,7 @@ var ts; } function shouldEmitEnumDeclaration(node) { var isConstEnum = ts.isConst(node); - return !isConstEnum || compilerOptions.preserveConstEnums || compilerOptions.separateCompilation; + return !isConstEnum || compilerOptions.preserveConstEnums || compilerOptions.isolatedModules; } function emitEnumDeclaration(node) { if (!shouldEmitEnumDeclaration(node)) { @@ -23696,7 +25095,7 @@ var ts; emitDeclarationName(node); write("\", "); emitDeclarationName(node); - write(")"); + write(");"); } emitExportMemberAssignments(node.name); } @@ -23730,13 +25129,13 @@ var ts; } } function getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration) { - if (moduleDeclaration.body.kind === 206) { + if (moduleDeclaration.body.kind === 208) { var recursiveInnerModule = getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration.body); return recursiveInnerModule || moduleDeclaration.body; } } function shouldEmitModuleDeclaration(node) { - return ts.isInstantiatedModule(node, compilerOptions.preserveConstEnums || compilerOptions.separateCompilation); + return ts.isInstantiatedModule(node, compilerOptions.preserveConstEnums || compilerOptions.isolatedModules); } function isModuleMergedWithES6Class(node) { return languageVersion === 2 && !!(resolver.getNodeCheckFlags(node) & 2048); @@ -23765,7 +25164,7 @@ var ts; write(getGeneratedNameForNode(node)); emitEnd(node.name); write(") "); - if (node.body.kind === 207) { + if (node.body.kind === 209) { var saveTempFlags = tempFlags; var saveTempVariables = tempVariables; tempFlags = 0; @@ -23804,7 +25203,7 @@ var ts; emitDeclarationName(node); write("\", "); emitDeclarationName(node); - write(")"); + write(");"); } emitExportMemberAssignments(node.name); } @@ -23822,16 +25221,16 @@ var ts; } } function getNamespaceDeclarationNode(node) { - if (node.kind === 209) { + if (node.kind === 211) { return node; } var importClause = node.importClause; - if (importClause && importClause.namedBindings && importClause.namedBindings.kind === 212) { + if (importClause && importClause.namedBindings && importClause.namedBindings.kind === 214) { return importClause.namedBindings; } } function isDefaultImport(node) { - return node.kind === 210 && node.importClause && !!node.importClause.name; + return node.kind === 212 && node.importClause && !!node.importClause.name; } function emitExportImportAssignments(node) { if (ts.isAliasSymbolDeclaration(node) && resolver.isValueAliasDeclaration(node)) { @@ -23858,7 +25257,7 @@ var ts; if (shouldEmitNamedBindings) { emitLeadingComments(node.importClause.namedBindings); emitStart(node.importClause.namedBindings); - if (node.importClause.namedBindings.kind === 212) { + if (node.importClause.namedBindings.kind === 214) { write("* as "); emit(node.importClause.namedBindings.name); } @@ -23884,7 +25283,7 @@ var ts; } function emitExternalImportDeclaration(node) { if (ts.contains(externalImports, node)) { - var isExportedImport = node.kind === 209 && (node.flags & 1) !== 0; + var isExportedImport = node.kind === 211 && (node.flags & 1) !== 0; var namespaceDeclaration = getNamespaceDeclarationNode(node); if (compilerOptions.module !== 2) { emitLeadingComments(node); @@ -23896,7 +25295,7 @@ var ts; write(" = "); } else { - var isNakedImport = 210 && !node.importClause; + var isNakedImport = 212 && !node.importClause; if (!isNakedImport) { write("var "); write(getGeneratedNameForNode(node)); @@ -24052,8 +25451,8 @@ var ts; write("export default "); var expression = node.expression; emit(expression); - if (expression.kind !== 201 && - expression.kind !== 202) { + if (expression.kind !== 203 && + expression.kind !== 204) { write(";"); } emitEnd(node); @@ -24089,18 +25488,18 @@ var ts; for (var _a = 0, _b = sourceFile.statements; _a < _b.length; _a++) { var node = _b[_a]; switch (node.kind) { - case 210: + case 212: if (!node.importClause || resolver.isReferencedAliasDeclaration(node.importClause, true)) { externalImports.push(node); } break; - case 209: - if (node.moduleReference.kind === 220 && resolver.isReferencedAliasDeclaration(node)) { + case 211: + if (node.moduleReference.kind === 222 && resolver.isReferencedAliasDeclaration(node)) { externalImports.push(node); } break; - case 216: + case 218: if (node.moduleSpecifier) { if (!node.exportClause) { externalImports.push(node); @@ -24113,12 +25512,12 @@ var ts; else { for (var _c = 0, _d = node.exportClause.elements; _c < _d.length; _c++) { var specifier = _d[_c]; - var name_20 = (specifier.propertyName || specifier.name).text; - (exportSpecifiers[name_20] || (exportSpecifiers[name_20] = [])).push(specifier); + var name_21 = (specifier.propertyName || specifier.name).text; + (exportSpecifiers[name_21] || (exportSpecifiers[name_21] = [])).push(specifier); } } break; - case 215: + case 217: if (node.isExportEquals && !exportEquals) { exportEquals = node; } @@ -24138,13 +25537,16 @@ var ts; write("}"); } } - function getLocalNameForExternalImport(importNode) { - var namespaceDeclaration = getNamespaceDeclarationNode(importNode); - if (namespaceDeclaration && !isDefaultImport(importNode)) { + function getLocalNameForExternalImport(node) { + var namespaceDeclaration = getNamespaceDeclarationNode(node); + if (namespaceDeclaration && !isDefaultImport(node)) { return ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, namespaceDeclaration.name); } - else { - return getGeneratedNameForNode(importNode); + if (node.kind === 212 && node.importClause) { + return getGeneratedNameForNode(node); + } + if (node.kind === 218 && node.moduleSpecifier) { + return getGeneratedNameForNode(node); } } function getExternalModuleNameText(importNode) { @@ -24162,8 +25564,8 @@ var ts; var started = false; for (var _a = 0; _a < externalImports.length; _a++) { var importNode = externalImports[_a]; - var skipNode = importNode.kind === 216 || - (importNode.kind === 210 && !importNode.importClause); + var skipNode = importNode.kind === 218 || + (importNode.kind === 212 && !importNode.importClause); if (skipNode) { continue; } @@ -24188,7 +25590,7 @@ var ts; var hasExportDeclarationWithExportClause = false; for (var _a = 0; _a < externalImports.length; _a++) { var externalImport = externalImports[_a]; - if (externalImport.kind === 216 && externalImport.exportClause) { + if (externalImport.kind === 218 && externalImport.exportClause) { hasExportDeclarationWithExportClause = true; break; } @@ -24217,7 +25619,7 @@ var ts; } for (var _d = 0; _d < externalImports.length; _d++) { var externalImport = externalImports[_d]; - if (externalImport.kind !== 216) { + if (externalImport.kind !== 218) { continue; } var exportDecl = externalImport; @@ -24287,11 +25689,11 @@ var ts; var seen = {}; for (var i = 0; i < hoistedVars.length; ++i) { var local = hoistedVars[i]; - var name_21 = local.kind === 65 + var name_22 = local.kind === 65 ? local : local.name; - if (name_21) { - var text = ts.unescapeIdentifier(name_21.text); + if (name_22) { + var text = ts.unescapeIdentifier(name_22.text); if (ts.hasProperty(seen, text)) { continue; } @@ -24302,7 +25704,7 @@ var ts; if (i !== 0) { write(", "); } - if (local.kind === 202 || local.kind === 206 || local.kind === 205) { + if (local.kind === 204 || local.kind === 208 || local.kind === 207) { emitDeclarationName(local); } else { @@ -24336,21 +25738,21 @@ var ts; if (node.flags & 2) { return; } - if (node.kind === 201) { + if (node.kind === 203) { if (!hoistedFunctionDeclarations) { hoistedFunctionDeclarations = []; } hoistedFunctionDeclarations.push(node); return; } - if (node.kind === 202) { + if (node.kind === 204) { if (!hoistedVars) { hoistedVars = []; } hoistedVars.push(node); return; } - if (node.kind === 205) { + if (node.kind === 207) { if (shouldEmitEnumDeclaration(node)) { if (!hoistedVars) { hoistedVars = []; @@ -24359,7 +25761,7 @@ var ts; } return; } - if (node.kind === 206) { + if (node.kind === 208) { if (shouldEmitModuleDeclaration(node)) { if (!hoistedVars) { hoistedVars = []; @@ -24368,17 +25770,17 @@ var ts; } return; } - if (node.kind === 199 || node.kind === 153) { + if (node.kind === 201 || node.kind === 155) { if (shouldHoistVariable(node, false)) { - var name_22 = node.name; - if (name_22.kind === 65) { + var name_23 = node.name; + if (name_23.kind === 65) { if (!hoistedVars) { hoistedVars = []; } - hoistedVars.push(name_22); + hoistedVars.push(name_23); } else { - ts.forEachChild(name_22, visit); + ts.forEachChild(name_23, visit); } } return; @@ -24397,7 +25799,7 @@ var ts; return false; } return (ts.getCombinedNodeFlags(node) & 12288) === 0 || - ts.getEnclosingBlockScopeContainer(node).kind === 228; + ts.getEnclosingBlockScopeContainer(node).kind === 230; } function isCurrentFileSystemExternalModule() { return compilerOptions.module === 4 && ts.isExternalModule(currentSourceFile); @@ -24414,10 +25816,10 @@ var ts; emitSetters(exportStarFunction); writeLine(); emitExecute(node, startIndex); - emitTempDeclarations(true); decreaseIndent(); writeLine(); write("}"); + emitTempDeclarations(true); } function emitSetters(exportStarFunction) { write("setters:["); @@ -24432,27 +25834,27 @@ var ts; var parameterName = "_" + importVariableName; write("function (" + parameterName + ") {"); switch (importNode.kind) { - case 210: + case 212: if (!importNode.importClause) { break; } - case 209: + case 211: ts.Debug.assert(importVariableName !== ""); increaseIndent(); writeLine(); write(importVariableName + " = " + parameterName + ";"); writeLine(); - var defaultName = importNode.kind === 210 + var defaultName = importNode.kind === 212 ? importNode.importClause.name : importNode.name; if (defaultName) { emitExportMemberAssignments(defaultName); writeLine(); } - if (importNode.kind === 210 && + if (importNode.kind === 212 && importNode.importClause.namedBindings) { var namedBindings = importNode.importClause.namedBindings; - if (namedBindings.kind === 212) { + if (namedBindings.kind === 214) { emitExportMemberAssignments(namedBindings.name); writeLine(); } @@ -24466,7 +25868,7 @@ var ts; } decreaseIndent(); break; - case 216: + case 218: ts.Debug.assert(importVariableName !== ""); increaseIndent(); if (importNode.exportClause) { @@ -24500,10 +25902,10 @@ var ts; for (var i = startIndex; i < node.statements.length; ++i) { var statement = node.statements[i]; switch (statement.kind) { - case 216: - case 210: - case 209: - case 201: + case 218: + case 212: + case 211: + case 203: continue; } writeLine(); @@ -24517,7 +25919,11 @@ var ts; collectExternalModuleInfo(node); ts.Debug.assert(!exportFunctionForFile); exportFunctionForFile = makeUniqueName("exports"); - write("System.register(["); + write("System.register("); + if (node.moduleName) { + write("\"" + node.moduleName + "\", "); + } + write("["); for (var i = 0; i < externalImports.length; ++i) { var text = getExternalModuleNameText(externalImports[i]); if (i !== 0) { @@ -24590,8 +25996,8 @@ var ts; collectExternalModuleInfo(node); writeLine(); write("define("); - if (node.amdModuleName) { - write("\"" + node.amdModuleName + "\", "); + if (node.moduleName) { + write("\"" + node.moduleName + "\", "); } emitAMDDependencies(node, true); write(") {"); @@ -24692,7 +26098,7 @@ var ts; paramEmitted = true; } } - if (ts.isExternalModule(node) || compilerOptions.separateCompilation) { + if (ts.isExternalModule(node) || compilerOptions.isolatedModules) { if (languageVersion >= 2) { emitES6Module(node, startIndex); } @@ -24720,7 +26126,7 @@ var ts; } emitLeadingComments(node.endOfFileToken); } - function emitNodeWithoutSourceMap(node, allowGeneratedIdentifiers) { + function emitNodeWithoutSourceMap(node) { if (!node) { return; } @@ -24731,46 +26137,47 @@ var ts; if (emitComments) { emitLeadingComments(node); } - emitJavaScriptWorker(node, allowGeneratedIdentifiers); + emitJavaScriptWorker(node); if (emitComments) { emitTrailingComments(node); } } function shouldEmitLeadingAndTrailingComments(node) { switch (node.kind) { - case 203: - case 201: - case 210: - case 209: - case 204: - case 215: - return false; - case 206: - return shouldEmitModuleDeclaration(node); case 205: + case 203: + case 212: + case 211: + case 206: + case 217: + return false; + case 183: + return shouldEmitLeadingAndTrailingCommentsForVariableStatement(node); + case 208: + return shouldEmitModuleDeclaration(node); + case 207: return shouldEmitEnumDeclaration(node); } - if (node.kind !== 180 && + if (node.kind !== 182 && node.parent && - node.parent.kind === 164 && + node.parent.kind === 166 && node.parent.body === node && compilerOptions.target <= 1) { return false; } return true; } - function emitJavaScriptWorker(node, allowGeneratedIdentifiers) { - if (allowGeneratedIdentifiers === void 0) { allowGeneratedIdentifiers = true; } + function emitJavaScriptWorker(node) { switch (node.kind) { case 65: - return emitIdentifier(node, allowGeneratedIdentifiers); - case 130: + return emitIdentifier(node); + case 131: return emitParameter(node); + case 136: case 135: - case 134: return emitMethod(node); - case 137: case 138: + case 139: return emitAccessor(node); case 93: return emitThis(node); @@ -24790,131 +26197,131 @@ var ts; case 12: case 13: return emitLiteral(node); - case 172: - return emitTemplateExpression(node); - case 178: - return emitTemplateSpan(node); - case 127: - return emitQualifiedName(node); - case 151: - return emitObjectBindingPattern(node); - case 152: - return emitArrayBindingPattern(node); - case 153: - return emitBindingElement(node); - case 154: - return emitArrayLiteral(node); - case 155: - return emitObjectLiteral(node); - case 225: - return emitPropertyAssignment(node); - case 226: - return emitShorthandPropertyAssignment(node); - case 128: - return emitComputedPropertyName(node); - case 156: - return emitPropertyAccess(node); - case 157: - return emitIndexedAccess(node); - case 158: - return emitCallExpression(node); - case 159: - return emitNewExpression(node); - case 160: - return emitTaggedTemplateExpression(node); - case 161: - return emit(node.expression); - case 162: - return emitParenExpression(node); - case 201: - case 163: - case 164: - return emitFunctionDeclaration(node); - case 165: - return emitDeleteExpression(node); - case 166: - return emitTypeOfExpression(node); - case 167: - return emitVoidExpression(node); - case 168: - return emitPrefixUnaryExpression(node); - case 169: - return emitPostfixUnaryExpression(node); - case 170: - return emitBinaryExpression(node); - case 171: - return emitConditionalExpression(node); case 174: - return emitSpreadElementExpression(node); - case 173: - return emitYieldExpression(node); - case 176: - return; + return emitTemplateExpression(node); case 180: - case 207: - return emitBlock(node); - case 181: - return emitVariableStatement(node); - case 182: - return write(";"); - case 183: - return emitExpressionStatement(node); - case 184: - return emitIfStatement(node); - case 185: - return emitDoStatement(node); - case 186: - return emitWhileStatement(node); - case 187: - return emitForStatement(node); - case 189: - case 188: - return emitForInOrForOfStatement(node); - case 190: - case 191: - return emitBreakOrContinueStatement(node); - case 192: - return emitReturnStatement(node); - case 193: - return emitWithStatement(node); - case 194: - return emitSwitchStatement(node); - case 221: - case 222: - return emitCaseOrDefaultClause(node); - case 195: - return emitLabelledStatement(node); - case 196: - return emitThrowStatement(node); - case 197: - return emitTryStatement(node); - case 224: - return emitCatchClause(node); - case 198: - return emitDebuggerStatement(node); - case 199: - return emitVariableDeclaration(node); - case 175: - return emitClassExpression(node); - case 202: - return emitClassDeclaration(node); - case 203: - return emitInterfaceDeclaration(node); - case 205: - return emitEnumDeclaration(node); + return emitTemplateSpan(node); + case 128: + return emitQualifiedName(node); + case 153: + return emitObjectBindingPattern(node); + case 154: + return emitArrayBindingPattern(node); + case 155: + return emitBindingElement(node); + case 156: + return emitArrayLiteral(node); + case 157: + return emitObjectLiteral(node); case 227: - return emitEnumMember(node); - case 206: - return emitModuleDeclaration(node); - case 210: - return emitImportDeclaration(node); - case 209: - return emitImportEqualsDeclaration(node); - case 216: - return emitExportDeclaration(node); - case 215: - return emitExportAssignment(node); + return emitPropertyAssignment(node); case 228: + return emitShorthandPropertyAssignment(node); + case 129: + return emitComputedPropertyName(node); + case 158: + return emitPropertyAccess(node); + case 159: + return emitIndexedAccess(node); + case 160: + return emitCallExpression(node); + case 161: + return emitNewExpression(node); + case 162: + return emitTaggedTemplateExpression(node); + case 163: + return emit(node.expression); + case 164: + return emitParenExpression(node); + case 203: + case 165: + case 166: + return emitFunctionDeclaration(node); + case 167: + return emitDeleteExpression(node); + case 168: + return emitTypeOfExpression(node); + case 169: + return emitVoidExpression(node); + case 170: + return emitPrefixUnaryExpression(node); + case 171: + return emitPostfixUnaryExpression(node); + case 172: + return emitBinaryExpression(node); + case 173: + return emitConditionalExpression(node); + case 176: + return emitSpreadElementExpression(node); + case 175: + return emitYieldExpression(node); + case 178: + return; + case 182: + case 209: + return emitBlock(node); + case 183: + return emitVariableStatement(node); + case 184: + return write(";"); + case 185: + return emitExpressionStatement(node); + case 186: + return emitIfStatement(node); + case 187: + return emitDoStatement(node); + case 188: + return emitWhileStatement(node); + case 189: + return emitForStatement(node); + case 191: + case 190: + return emitForInOrForOfStatement(node); + case 192: + case 193: + return emitBreakOrContinueStatement(node); + case 194: + return emitReturnStatement(node); + case 195: + return emitWithStatement(node); + case 196: + return emitSwitchStatement(node); + case 223: + case 224: + return emitCaseOrDefaultClause(node); + case 197: + return emitLabelledStatement(node); + case 198: + return emitThrowStatement(node); + case 199: + return emitTryStatement(node); + case 226: + return emitCatchClause(node); + case 200: + return emitDebuggerStatement(node); + case 201: + return emitVariableDeclaration(node); + case 177: + return emitClassExpression(node); + case 204: + return emitClassDeclaration(node); + case 205: + return emitInterfaceDeclaration(node); + case 207: + return emitEnumDeclaration(node); + case 229: + return emitEnumMember(node); + case 208: + return emitModuleDeclaration(node); + case 212: + return emitImportDeclaration(node); + case 211: + return emitImportEqualsDeclaration(node); + case 218: + return emitExportDeclaration(node); + case 217: + return emitExportAssignment(node); + case 230: return emitSourceFileNode(node); } } @@ -24942,7 +26349,7 @@ var ts; } function getLeadingCommentsToEmit(node) { if (node.parent) { - if (node.parent.kind === 228 || node.pos !== node.parent.pos) { + if (node.parent.kind === 230 || node.pos !== node.parent.pos) { if (hasDetachedComments(node.pos)) { return getLeadingCommentsWithoutDetachedComments(); } @@ -24954,7 +26361,7 @@ var ts; } function getTrailingCommentsToEmit(node) { if (node.parent) { - if (node.parent.kind === 228 || node.end !== node.parent.end) { + if (node.parent.kind === 230 || node.end !== node.parent.end) { return ts.getTrailingCommentRanges(currentSourceFile.text, node.end); } } @@ -25048,9 +26455,7 @@ var ts; ts.emitTime = 0; ts.ioReadTime = 0; ts.ioWriteTime = 0; - ts.version = "1.5.2"; - var carriageReturnLineFeed = "\r\n"; - var lineFeed = "\n"; + ts.version = "1.5.3"; function findConfigFile(searchPath) { var fileName = "tsconfig.json"; while (true) { @@ -25121,9 +26526,7 @@ var ts; } } } - var newLine = options.newLine === 0 ? carriageReturnLineFeed : - options.newLine === 1 ? lineFeed : - ts.sys.newLine; + var newLine = ts.getNewLineCharacter(options); return { getSourceFile: getSourceFile, getDefaultLibFileName: function (options) { return ts.combinePaths(ts.getDirectoryPath(ts.normalizePath(ts.sys.getExecutingFilePath())), ts.getDefaultLibFileName(options)); }, @@ -25136,7 +26539,7 @@ var ts; } ts.createCompilerHost = createCompilerHost; function getPreEmitDiagnostics(program, sourceFile) { - var diagnostics = program.getSyntacticDiagnostics(sourceFile).concat(program.getGlobalDiagnostics()).concat(program.getSemanticDiagnostics(sourceFile)); + var diagnostics = program.getOptionsDiagnostics().concat(program.getSyntacticDiagnostics(sourceFile), program.getGlobalDiagnostics(), program.getSemanticDiagnostics(sourceFile)); if (program.getCompilerOptions().declaration) { diagnostics.concat(program.getDeclarationDiagnostics(sourceFile)); } @@ -25169,16 +26572,17 @@ var ts; function createProgram(rootNames, options, host) { var program; var files = []; - var filesByName = {}; var diagnostics = ts.createDiagnosticCollection(); - var seenNoDefaultLib = options.noLib; var commonSourceDirectory; var diagnosticsProducingTypeChecker; var noDiagnosticsTypeChecker; + var classifiableNames; + var skipDefaultLib = options.noLib; var start = new Date().getTime(); host = host || createCompilerHost(options); + var filesByName = ts.createFileMap(function (fileName) { return host.getCanonicalFileName(fileName); }); ts.forEach(rootNames, function (name) { return processRootFile(name, false); }); - if (!seenNoDefaultLib) { + if (!skipDefaultLib) { processRootFile(host.getDefaultLibFileName(options), true); } verifyCompilerOptions(); @@ -25188,10 +26592,12 @@ var ts; getSourceFiles: function () { return files; }, getCompilerOptions: function () { return options; }, getSyntacticDiagnostics: getSyntacticDiagnostics, + getOptionsDiagnostics: getOptionsDiagnostics, getGlobalDiagnostics: getGlobalDiagnostics, getSemanticDiagnostics: getSemanticDiagnostics, getDeclarationDiagnostics: getDeclarationDiagnostics, getTypeChecker: getTypeChecker, + getClassifiableNames: getClassifiableNames, getDiagnosticsProducingTypeChecker: getDiagnosticsProducingTypeChecker, getCommonSourceDirectory: function () { return commonSourceDirectory; }, emit: emit, @@ -25202,6 +26608,17 @@ var ts; getTypeCount: function () { return getDiagnosticsProducingTypeChecker().getTypeCount(); } }; return program; + function getClassifiableNames() { + if (!classifiableNames) { + getTypeChecker(); + classifiableNames = {}; + for (var _i = 0; _i < files.length; _i++) { + var sourceFile = files[_i]; + ts.copyMap(sourceFile.classifiableNames, classifiableNames); + } + } + return classifiableNames; + } function getEmitHost(writeFileCallback) { return { getCanonicalFileName: function (fileName) { return host.getCanonicalFileName(fileName); }, @@ -25231,8 +26648,7 @@ var ts; return emitResult; } function getSourceFile(fileName) { - fileName = host.getCanonicalFileName(ts.normalizeSlashes(fileName)); - return ts.hasProperty(filesByName, fileName) ? filesByName[fileName] : undefined; + return filesByName.get(fileName); } function getDiagnosticsHelper(sourceFile, getDiagnostics) { if (sourceFile) { @@ -25271,13 +26687,16 @@ var ts; return ts.getDeclarationDiagnostics(getEmitHost(writeFile), resolver, sourceFile); } } - function getGlobalDiagnostics() { - var typeChecker = getDiagnosticsProducingTypeChecker(); + function getOptionsDiagnostics() { var allDiagnostics = []; - ts.addRange(allDiagnostics, typeChecker.getGlobalDiagnostics()); ts.addRange(allDiagnostics, diagnostics.getGlobalDiagnostics()); return ts.sortAndDeduplicateDiagnostics(allDiagnostics); } + function getGlobalDiagnostics() { + var allDiagnostics = []; + ts.addRange(allDiagnostics, getDiagnosticsProducingTypeChecker().getGlobalDiagnostics()); + return ts.sortAndDeduplicateDiagnostics(allDiagnostics); + } function hasExtension(fileName) { return ts.getBaseFileName(fileName).indexOf(".") >= 0; } @@ -25309,14 +26728,17 @@ var ts; } } else { - if (options.allowNonTsExtensions && !findSourceFile(fileName, isDefaultLib, refFile, refPos, refEnd)) { - diagnostic = ts.Diagnostics.File_0_not_found; - diagnosticArgument = [fileName]; - } - else if (!ts.forEach(ts.supportedExtensions, function (extension) { return findSourceFile(fileName + extension, isDefaultLib, refFile, refPos, refEnd); })) { - diagnostic = ts.Diagnostics.File_0_not_found; - fileName += ".ts"; - diagnosticArgument = [fileName]; + var nonTsFile = options.allowNonTsExtensions && findSourceFile(fileName, isDefaultLib, refFile, refPos, refEnd); + if (!nonTsFile) { + if (options.allowNonTsExtensions) { + diagnostic = ts.Diagnostics.File_0_not_found; + diagnosticArgument = [fileName]; + } + else if (!ts.forEach(ts.supportedExtensions, function (extension) { return findSourceFile(fileName + extension, isDefaultLib, refFile, refPos, refEnd); })) { + diagnostic = ts.Diagnostics.File_0_not_found; + fileName += ".ts"; + diagnosticArgument = [fileName]; + } } } if (diagnostic) { @@ -25330,16 +26752,16 @@ var ts; } function findSourceFile(fileName, isDefaultLib, refFile, refStart, refLength) { var canonicalName = host.getCanonicalFileName(ts.normalizeSlashes(fileName)); - if (ts.hasProperty(filesByName, canonicalName)) { + if (filesByName.contains(canonicalName)) { return getSourceFileFromCache(fileName, canonicalName, false); } else { var normalizedAbsolutePath = ts.getNormalizedAbsolutePath(fileName, host.getCurrentDirectory()); var canonicalAbsolutePath = host.getCanonicalFileName(normalizedAbsolutePath); - if (ts.hasProperty(filesByName, canonicalAbsolutePath)) { + if (filesByName.contains(canonicalAbsolutePath)) { return getSourceFileFromCache(normalizedAbsolutePath, canonicalAbsolutePath, true); } - var file = filesByName[canonicalName] = host.getSourceFile(fileName, options.target, function (hostErrorMessage) { + var file = host.getSourceFile(fileName, options.target, function (hostErrorMessage) { if (refFile) { diagnostics.add(ts.createFileDiagnostic(refFile, refStart, refLength, ts.Diagnostics.Cannot_read_file_0_Colon_1, fileName, hostErrorMessage)); } @@ -25347,15 +26769,17 @@ var ts; diagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0_Colon_1, fileName, hostErrorMessage)); } }); + filesByName.set(canonicalName, file); if (file) { - seenNoDefaultLib = seenNoDefaultLib || file.hasNoDefaultLib; - filesByName[canonicalAbsolutePath] = file; + skipDefaultLib = skipDefaultLib || file.hasNoDefaultLib; + filesByName.set(canonicalAbsolutePath, file); if (!options.noResolve) { var basePath = ts.getDirectoryPath(fileName); processReferencedFiles(file, basePath); processImportedModules(file, basePath); } if (isDefaultLib) { + file.isDefaultLib = true; files.unshift(file); } else { @@ -25365,7 +26789,7 @@ var ts; return file; } function getSourceFileFromCache(fileName, canonicalName, useAbsolutePath) { - var file = filesByName[canonicalName]; + var file = filesByName.get(canonicalName); if (file && host.useCaseSensitiveFileNames()) { var sourceFileName = useAbsolutePath ? ts.getNormalizedAbsolutePath(file.fileName, host.getCurrentDirectory()) : file.fileName; if (canonicalName !== sourceFileName) { @@ -25383,7 +26807,7 @@ var ts; } function processImportedModules(file, basePath) { ts.forEach(file.statements, function (node) { - if (node.kind === 210 || node.kind === 209 || node.kind === 216) { + if (node.kind === 212 || node.kind === 211 || node.kind === 218) { var moduleNameExpr = ts.getExternalModuleName(node); if (moduleNameExpr && moduleNameExpr.kind === 8) { var moduleNameText = moduleNameExpr.text; @@ -25404,7 +26828,7 @@ var ts; } } } - else if (node.kind === 206 && node.name.kind === 8 && (node.flags & 2 || ts.isDeclarationFile(file))) { + else if (node.kind === 208 && node.name.kind === 8 && (node.flags & 2 || ts.isDeclarationFile(file))) { ts.forEachChild(node.body, function (node) { if (ts.isExternalModuleImportEqualsDeclaration(node) && ts.getExternalModuleImportEqualsDeclarationExpression(node).kind === 8) { @@ -25470,18 +26894,18 @@ var ts; return allFilesBelongToPath; } function verifyCompilerOptions() { - if (options.separateCompilation) { + if (options.isolatedModules) { if (options.sourceMap) { - diagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_sourceMap_cannot_be_specified_with_option_separateCompilation)); + diagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_sourceMap_cannot_be_specified_with_option_isolatedModules)); } if (options.declaration) { - diagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_declaration_cannot_be_specified_with_option_separateCompilation)); + diagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_declaration_cannot_be_specified_with_option_isolatedModules)); } if (options.noEmitOnError) { - diagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_noEmitOnError_cannot_be_specified_with_option_separateCompilation)); + diagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_noEmitOnError_cannot_be_specified_with_option_isolatedModules)); } if (options.out) { - diagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_out_cannot_be_specified_with_option_separateCompilation)); + diagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_out_cannot_be_specified_with_option_isolatedModules)); } } if (options.inlineSourceMap) { @@ -25511,14 +26935,14 @@ var ts; } var languageVersion = options.target || 0; var firstExternalModuleSourceFile = ts.forEach(files, function (f) { return ts.isExternalModule(f) ? f : undefined; }); - if (options.separateCompilation) { + if (options.isolatedModules) { if (!options.module && languageVersion < 2) { - diagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_separateCompilation_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES6_or_higher)); + diagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES6_or_higher)); } var firstNonExternalModuleSourceFile = ts.forEach(files, function (f) { return !ts.isExternalModule(f) && !ts.isDeclarationFile(f) ? f : undefined; }); if (firstNonExternalModuleSourceFile) { var span = ts.getErrorSpanForNode(firstNonExternalModuleSourceFile, firstNonExternalModuleSourceFile); - diagnostics.add(ts.createFileDiagnostic(firstNonExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_compile_namespaces_when_the_separateCompilation_flag_is_provided)); + diagnostics.add(ts.createFileDiagnostic(firstNonExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided)); } } else if (firstExternalModuleSourceFile && languageVersion < 2 && !options.module) { @@ -25550,6 +26974,10 @@ var ts; diagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_noEmit_cannot_be_specified_with_option_declaration)); } } + if (options.emitDecoratorMetadata && + !options.experimentalDecorators) { + diagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_experimentalDecorators_must_also_be_specified_when_option_emitDecoratorMetadata_is_specified)); + } } } ts.createProgram = createProgram; @@ -25658,9 +27086,14 @@ var ts; name: "noResolve", type: "boolean" }, + { + name: "skipDefaultLibCheck", + type: "boolean" + }, { name: "out", type: "string", + isFilePath: true, description: ts.Diagnostics.Concatenate_and_emit_output_to_single_file, paramType: ts.Diagnostics.FILE }, @@ -25697,7 +27130,7 @@ var ts; paramType: ts.Diagnostics.LOCATION }, { - name: "separateCompilation", + name: "isolatedModules", type: "boolean" }, { @@ -25743,10 +27176,16 @@ var ts; type: "boolean", description: ts.Diagnostics.Watch_input_files }, + { + name: "experimentalDecorators", + type: "boolean", + description: ts.Diagnostics.Enables_experimental_support_for_ES7_decorators + }, { name: "emitDecoratorMetadata", type: "boolean", - experimental: true + experimental: true, + description: ts.Diagnostics.Enables_experimental_support_for_emitting_type_metadata_for_decorators } ]; function parseCommandLine(commandLine) { @@ -25873,7 +27312,7 @@ var ts; var errors = []; return { options: getCompilerOptions(), - fileNames: getFiles(), + fileNames: getFileNames(), errors: errors }; function getCompilerOptions() { @@ -25917,23 +27356,24 @@ var ts; } return options; } - function getFiles() { - var files = []; + function getFileNames() { + var fileNames = []; if (ts.hasProperty(json, "files")) { if (json["files"] instanceof Array) { - var files = ts.map(json["files"], function (s) { return ts.combinePaths(basePath, s); }); + fileNames = ts.map(json["files"], function (s) { return ts.combinePaths(basePath, s); }); } } else { - var sysFiles = host.readDirectory(basePath, ".ts"); + var exclude = json["exclude"] instanceof Array ? ts.map(json["exclude"], ts.normalizeSlashes) : undefined; + var sysFiles = host.readDirectory(basePath, ".ts", exclude); for (var i = 0; i < sysFiles.length; i++) { var name = sysFiles[i]; if (!ts.fileExtensionIs(name, ".d.ts") || !ts.contains(sysFiles, name.substr(0, name.length - 5) + ".ts")) { - files.push(name); + fileNames.push(name); } } } - return files; + return fileNames; } } ts.parseConfigFile = parseConfigFile; diff --git a/bin/tsserver.js b/bin/tsserver.js index f617ae545f3..2d937e57fad 100644 --- a/bin/tsserver.js +++ b/bin/tsserver.js @@ -31,6 +31,36 @@ var ts; /// var ts; (function (ts) { + function createFileMap(getCanonicalFileName) { + var files = {}; + return { + get: get, + set: set, + contains: contains, + remove: remove, + forEachValue: forEachValueInMap + }; + function set(fileName, value) { + files[normalizeKey(fileName)] = value; + } + function get(fileName) { + return files[normalizeKey(fileName)]; + } + function contains(fileName) { + return hasProperty(files, normalizeKey(fileName)); + } + function remove(fileName) { + var key = normalizeKey(fileName); + delete files[key]; + } + function forEachValueInMap(f) { + forEachValue(files, f); + } + function normalizeKey(key) { + return getCanonicalFileName(normalizeSlashes(key)); + } + } + ts.createFileMap = createFileMap; function forEach(array, callback) { if (array) { for (var i = 0, len = array.length; i < len; i++) { @@ -145,6 +175,16 @@ var ts; } } ts.addRange = addRange; + function rangeEquals(array1, array2, pos, end) { + while (pos < end) { + if (array1[pos] !== array2[pos]) { + return false; + } + pos++; + } + return true; + } + ts.rangeEquals = rangeEquals; function lastOrUndefined(array) { if (array.length === 0) { return undefined; @@ -301,8 +341,10 @@ var ts; var end = start + length; Debug.assert(start >= 0, "start must be non-negative, is " + start); Debug.assert(length >= 0, "length must be non-negative, is " + length); - Debug.assert(start <= file.text.length, "start must be within the bounds of the file. " + start + " > " + file.text.length); - Debug.assert(end <= file.text.length, "end must be the bounds of the file. " + end + " > " + file.text.length); + if (file) { + Debug.assert(start <= file.text.length, "start must be within the bounds of the file. " + start + " > " + file.text.length); + Debug.assert(end <= file.text.length, "end must be the bounds of the file. " + end + " > " + file.text.length); + } var text = getLocaleSpecificMessage(message.key); if (arguments.length > 4) { text = formatStringFromArgs(text, arguments, 4); @@ -486,7 +528,7 @@ var ts; function getNormalizedPathComponents(path, currentDirectory) { path = normalizeSlashes(path); var rootLength = getRootLength(path); - if (rootLength == 0) { + if (rootLength === 0) { path = combinePaths(normalizeSlashes(currentDirectory), path); rootLength = getRootLength(path); } @@ -726,6 +768,9 @@ var ts; fileStream.Close(); } } + function getCanonicalPath(path) { + return path.toLowerCase(); + } function getNames(collection) { var result = []; for (var e = new Enumerator(collection); !e.atEnd(); e.moveNext()) { @@ -733,23 +778,28 @@ var ts; } return result.sort(); } - function readDirectory(path, extension) { + function readDirectory(path, extension, exclude) { var result = []; + exclude = ts.map(exclude, function (s) { return getCanonicalPath(ts.combinePaths(path, s)); }); visitDirectory(path); return result; function visitDirectory(path) { var folder = fso.GetFolder(path || "."); var files = getNames(folder.files); for (var _i = 0; _i < files.length; _i++) { - var name_1 = files[_i]; - if (!extension || ts.fileExtensionIs(name_1, extension)) { - result.push(ts.combinePaths(path, name_1)); + var current = files[_i]; + var name_1 = ts.combinePaths(path, current); + if ((!extension || ts.fileExtensionIs(name_1, extension)) && !ts.contains(exclude, getCanonicalPath(name_1))) { + result.push(name_1); } } var subfolders = getNames(folder.subfolders); for (var _a = 0; _a < subfolders.length; _a++) { var current = subfolders[_a]; - visitDirectory(ts.combinePaths(path, current)); + var name_2 = ts.combinePaths(path, current); + if (!ts.contains(exclude, getCanonicalPath(name_2))) { + visitDirectory(name_2); + } } } } @@ -827,8 +877,12 @@ var ts; } _fs.writeFileSync(fileName, data, "utf8"); } - function readDirectory(path, extension) { + function getCanonicalPath(path) { + return useCaseSensitiveFileNames ? path.toLowerCase() : path; + } + function readDirectory(path, extension, exclude) { var result = []; + exclude = ts.map(exclude, function (s) { return getCanonicalPath(ts.combinePaths(path, s)); }); visitDirectory(path); return result; function visitDirectory(path) { @@ -837,14 +891,16 @@ var ts; for (var _i = 0; _i < files.length; _i++) { var current = files[_i]; var name = ts.combinePaths(path, current); - var stat = _fs.lstatSync(name); - if (stat.isFile()) { - if (!extension || ts.fileExtensionIs(name, extension)) { - result.push(name); + if (!ts.contains(exclude, getCanonicalPath(name))) { + var stat = _fs.statSync(name); + if (stat.isFile()) { + if (!extension || ts.fileExtensionIs(name, extension)) { + result.push(name); + } + } + else if (stat.isDirectory()) { + directories.push(name); } - } - else if (stat.isDirectory()) { - directories.push(name); } } for (var _a = 0; _a < directories.length; _a++) { @@ -1039,7 +1095,7 @@ var ts; Unterminated_template_literal: { code: 1160, category: ts.DiagnosticCategory.Error, key: "Unterminated template literal." }, Unterminated_regular_expression_literal: { code: 1161, category: ts.DiagnosticCategory.Error, key: "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." }, - yield_expression_must_be_contained_within_a_generator_declaration: { code: 1163, category: ts.DiagnosticCategory.Error, key: "'yield' expression must be contained_within a generator declaration." }, + 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." }, Computed_property_names_are_not_allowed_in_enums: { code: 1164, category: ts.DiagnosticCategory.Error, key: "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." }, 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." }, @@ -1084,15 +1140,32 @@ var ts; Decorators_are_only_available_when_targeting_ECMAScript_5_and_higher: { code: 1205, category: ts.DiagnosticCategory.Error, key: "Decorators are only available when targeting ECMAScript 5 and higher." }, Decorators_are_not_valid_here: { code: 1206, category: ts.DiagnosticCategory.Error, key: "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/set accessors of the same name." }, - Cannot_compile_namespaces_when_the_separateCompilation_flag_is_provided: { code: 1208, category: ts.DiagnosticCategory.Error, key: "Cannot compile namespaces when the '--separateCompilation' flag is provided." }, - Ambient_const_enums_are_not_allowed_when_the_separateCompilation_flag_is_provided: { code: 1209, category: ts.DiagnosticCategory.Error, key: "Ambient const enums are not allowed when the '--separateCompilation' flag is provided." }, + 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." }, + 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." }, 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." }, 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" }, 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" }, 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 strict mode." }, - Type_expected_0_is_a_reserved_word_in_strict_mode: { code: 1215, category: ts.DiagnosticCategory.Error, key: "Type expected. '{0}' is a reserved word in strict mode" }, - Type_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_strict_mode: { code: 1216, category: ts.DiagnosticCategory.Error, key: "Type 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." }, + 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." }, 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'." }, + Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Specify_experimentalDecorators_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. Specify '--experimentalDecorators' to remove this warning." }, + Generators_are_only_available_when_targeting_ECMAScript_6_or_higher: { code: 1220, category: ts.DiagnosticCategory.Error, key: "Generators are only available when targeting ECMAScript 6 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." }, + 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." }, + _0_tag_already_specified: { code: 1223, category: ts.DiagnosticCategory.Error, key: "'{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." }, + Cannot_find_parameter_0: { code: 1225, category: ts.DiagnosticCategory.Error, key: "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}'." }, + 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}'." }, + 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." }, + A_type_predicate_cannot_reference_a_rest_parameter: { code: 1229, category: ts.DiagnosticCategory.Error, key: "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." }, + 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." }, + 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." }, + 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." }, + 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." }, + 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." }, Duplicate_identifier_0: { code: 2300, category: ts.DiagnosticCategory.Error, key: "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." }, Static_members_cannot_reference_class_type_parameters: { code: 2302, category: ts.DiagnosticCategory.Error, key: "Static members cannot reference class type parameters." }, @@ -1253,7 +1326,7 @@ var ts; 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'." }, 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." }, 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'." }, - Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_6_and_higher: { code: 2472, category: ts.DiagnosticCategory.Error, key: "Spread operator in 'new' expressions is only available when targeting ECMAScript 6 and higher." }, + 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." }, 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." }, 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." }, 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 import declaration or export assignment." }, @@ -1284,6 +1357,13 @@ var ts; A_rest_element_cannot_contain_a_binding_pattern: { code: 2501, category: ts.DiagnosticCategory.Error, key: "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." }, Cannot_find_namespace_0: { code: 2503, category: ts.DiagnosticCategory.Error, key: "Cannot find namespace '{0}'." }, + No_best_common_type_exists_among_yield_expressions: { code: 2504, category: ts.DiagnosticCategory.Error, key: "No best common type exists among yield expressions." }, + A_generator_cannot_have_a_void_type_annotation: { code: 2505, category: ts.DiagnosticCategory.Error, key: "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." }, + Type_0_is_not_a_constructor_function_type: { code: 2507, category: ts.DiagnosticCategory.Error, key: "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." }, + 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." }, + 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." }, Import_declaration_0_is_using_private_name_1: { code: 4000, category: ts.DiagnosticCategory.Error, key: "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}'." }, 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}'." }, @@ -1368,11 +1448,11 @@ var ts; Option_noEmit_cannot_be_specified_with_option_out_or_outDir: { code: 5040, category: ts.DiagnosticCategory.Error, key: "Option 'noEmit' cannot be specified with option 'out' or 'outDir'." }, Option_noEmit_cannot_be_specified_with_option_declaration: { code: 5041, category: ts.DiagnosticCategory.Error, key: "Option 'noEmit' cannot be specified with option 'declaration'." }, 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." }, - Option_sourceMap_cannot_be_specified_with_option_separateCompilation: { code: 5043, category: ts.DiagnosticCategory.Error, key: "Option 'sourceMap' cannot be specified with option 'separateCompilation'." }, - Option_declaration_cannot_be_specified_with_option_separateCompilation: { code: 5044, category: ts.DiagnosticCategory.Error, key: "Option 'declaration' cannot be specified with option 'separateCompilation'." }, - Option_noEmitOnError_cannot_be_specified_with_option_separateCompilation: { code: 5045, category: ts.DiagnosticCategory.Error, key: "Option 'noEmitOnError' cannot be specified with option 'separateCompilation'." }, - Option_out_cannot_be_specified_with_option_separateCompilation: { code: 5046, category: ts.DiagnosticCategory.Error, key: "Option 'out' cannot be specified with option 'separateCompilation'." }, - Option_separateCompilation_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES6_or_higher: { code: 5047, category: ts.DiagnosticCategory.Error, key: "Option 'separateCompilation' can only be used when either option'--module' is provided or option 'target' is 'ES6' or higher." }, + Option_sourceMap_cannot_be_specified_with_option_isolatedModules: { code: 5043, category: ts.DiagnosticCategory.Error, key: "Option 'sourceMap' cannot be specified with option 'isolatedModules'." }, + Option_declaration_cannot_be_specified_with_option_isolatedModules: { code: 5044, category: ts.DiagnosticCategory.Error, key: "Option 'declaration' cannot be specified with option 'isolatedModules'." }, + Option_noEmitOnError_cannot_be_specified_with_option_isolatedModules: { code: 5045, category: ts.DiagnosticCategory.Error, key: "Option 'noEmitOnError' cannot be specified with option 'isolatedModules'." }, + Option_out_cannot_be_specified_with_option_isolatedModules: { code: 5046, category: ts.DiagnosticCategory.Error, key: "Option 'out' cannot be specified with option 'isolatedModules'." }, + Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES6_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 'ES6' or higher." }, Option_sourceMap_cannot_be_specified_with_option_inlineSourceMap: { code: 5048, category: ts.DiagnosticCategory.Error, key: "Option 'sourceMap' cannot be specified with option 'inlineSourceMap'." }, Option_sourceRoot_cannot_be_specified_with_option_inlineSourceMap: { code: 5049, category: ts.DiagnosticCategory.Error, key: "Option 'sourceRoot' cannot be specified with option 'inlineSourceMap'." }, Option_mapRoot_cannot_be_specified_with_option_inlineSourceMap: { code: 5050, category: ts.DiagnosticCategory.Error, key: "Option 'mapRoot' cannot be specified with option 'inlineSourceMap'." }, @@ -1426,6 +1506,9 @@ var ts; Specifies_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix: { code: 6060, category: ts.DiagnosticCategory.Message, key: "Specifies 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" }, Argument_for_newLine_option_must_be_CRLF_or_LF: { code: 6062, category: ts.DiagnosticCategory.Error, key: "Argument for '--newLine' option must be 'CRLF' or 'LF'." }, + Option_experimentalDecorators_must_also_be_specified_when_option_emitDecoratorMetadata_is_specified: { code: 6064, category: ts.DiagnosticCategory.Error, key: "Option 'experimentalDecorators' must also be specified when option 'emitDecoratorMetadata' is specified." }, + Enables_experimental_support_for_ES7_decorators: { code: 6065, category: ts.DiagnosticCategory.Message, key: "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." }, Variable_0_implicitly_has_an_1_type: { code: 7005, category: ts.DiagnosticCategory.Error, key: "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." }, Member_0_implicitly_has_an_1_type: { code: 7008, category: ts.DiagnosticCategory.Error, key: "Member '{0}' implicitly has an '{1}' type." }, @@ -1438,9 +1521,10 @@ var ts; 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." }, Rest_parameter_0_implicitly_has_an_any_type: { code: 7019, category: ts.DiagnosticCategory.Error, key: "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." }, - _0_implicitly_has_type_any_because_it_is_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 is does not have a type annotation and is referenced directly or indirectly in its own initializer." }, + _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 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 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 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 type." }, You_cannot_rename_this_element: { code: 8000, category: ts.DiagnosticCategory.Error, key: "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." }, 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." }, @@ -1454,16 +1538,12 @@ var ts; 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." }, 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." }, 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." }, - can_only_be_used_in_a_ts_file: { code: 8013, category: ts.DiagnosticCategory.Error, key: "'?' can only be used in a .ts file." }, property_declarations_can_only_be_used_in_a_ts_file: { code: 8014, category: ts.DiagnosticCategory.Error, key: "'property declarations' 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." }, 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." }, decorators_can_only_be_used_in_a_ts_file: { code: 8017, category: ts.DiagnosticCategory.Error, key: "'decorators' can only be used in a .ts file." }, - yield_expressions_are_not_currently_supported: { code: 9000, category: ts.DiagnosticCategory.Error, key: "'yield' expressions are not currently supported." }, - Generators_are_not_currently_supported: { code: 9001, category: ts.DiagnosticCategory.Error, key: "Generators are not currently supported." }, Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_class_extends_clauses: { code: 9002, category: ts.DiagnosticCategory.Error, key: "Only identifiers/qualified-names with optional type arguments are currently supported in a class 'extends' clauses." }, - class_expressions_are_not_currently_supported: { code: 9003, category: ts.DiagnosticCategory.Error, key: "'class' expressions are not currently supported." }, - class_declarations_are_only_supported_directly_inside_a_module_or_as_a_top_level_declaration: { code: 9004, category: ts.DiagnosticCategory.Error, key: "'class' declarations are only supported directly inside a module or as a top level declaration." } + class_expressions_are_not_currently_supported: { code: 9003, category: ts.DiagnosticCategory.Error, key: "'class' expressions are not currently supported." } }; })(ts || (ts = {})); /// @@ -1493,7 +1573,7 @@ var ts; "false": 80, "finally": 81, "for": 82, - "from": 125, + "from": 126, "function": 83, "get": 116, "if": 84, @@ -1502,36 +1582,37 @@ var ts; "in": 86, "instanceof": 87, "interface": 103, + "is": 117, "let": 104, - "module": 117, - "namespace": 118, + "module": 118, + "namespace": 119, "new": 88, "null": 89, - "number": 120, + "number": 121, "package": 105, "private": 106, "protected": 107, "public": 108, - "require": 119, + "require": 120, "return": 90, - "set": 121, + "set": 122, "static": 109, - "string": 122, + "string": 123, "super": 91, "switch": 92, - "symbol": 123, + "symbol": 124, "this": 93, "throw": 94, "true": 95, "try": 96, - "type": 124, + "type": 125, "typeof": 97, "var": 98, "void": 99, "while": 100, "with": 101, "yield": 110, - "of": 126, + "of": 127, "{": 14, "}": 15, "(": 16, @@ -1623,9 +1704,9 @@ var ts; } function makeReverseMap(source) { var result = []; - for (var name_2 in source) { - if (source.hasOwnProperty(name_2)) { - result[source[name_2]] = name_2; + for (var name_3 in source) { + if (source.hasOwnProperty(name_3)) { + result[source[name_3]] = name_3; } } return result; @@ -1734,6 +1815,25 @@ var ts; return ch >= 48 && ch <= 55; } ts.isOctalDigit = isOctalDigit; + function couldStartTrivia(text, pos) { + var ch = text.charCodeAt(pos); + switch (ch) { + case 13: + case 10: + case 9: + case 11: + case 12: + case 32: + case 47: + case 60: + case 61: + case 62: + return true; + default: + return ch > 127; + } + } + ts.couldStartTrivia = couldStartTrivia; function skipTrivia(text, pos, stopAfterLineBreak) { while (true) { var ch = text.charCodeAt(pos); @@ -2196,7 +2296,7 @@ var ts; error(ts.Diagnostics.Unexpected_end_of_text); isInvalidExtendedEscape = true; } - else if (text.charCodeAt(pos) == 125) { + else if (text.charCodeAt(pos) === 125) { pos++; } else { @@ -2816,9 +2916,14 @@ var ts; name: "noResolve", type: "boolean" }, + { + name: "skipDefaultLibCheck", + type: "boolean" + }, { name: "out", type: "string", + isFilePath: true, description: ts.Diagnostics.Concatenate_and_emit_output_to_single_file, paramType: ts.Diagnostics.FILE }, @@ -2855,7 +2960,7 @@ var ts; paramType: ts.Diagnostics.LOCATION }, { - name: "separateCompilation", + name: "isolatedModules", type: "boolean" }, { @@ -2901,10 +3006,16 @@ var ts; type: "boolean", description: ts.Diagnostics.Watch_input_files }, + { + name: "experimentalDecorators", + type: "boolean", + description: ts.Diagnostics.Enables_experimental_support_for_ES7_decorators + }, { name: "emitDecoratorMetadata", type: "boolean", - experimental: true + experimental: true, + description: ts.Diagnostics.Enables_experimental_support_for_emitting_type_metadata_for_decorators } ]; function parseCommandLine(commandLine) { @@ -3031,7 +3142,7 @@ var ts; var errors = []; return { options: getCompilerOptions(), - fileNames: getFiles(), + fileNames: getFileNames(), errors: errors }; function getCompilerOptions() { @@ -3075,23 +3186,24 @@ var ts; } return options; } - function getFiles() { - var files = []; + function getFileNames() { + var fileNames = []; if (ts.hasProperty(json, "files")) { if (json["files"] instanceof Array) { - var files = ts.map(json["files"], function (s) { return ts.combinePaths(basePath, s); }); + fileNames = ts.map(json["files"], function (s) { return ts.combinePaths(basePath, s); }); } } else { - var sysFiles = host.readDirectory(basePath, ".ts"); + var exclude = json["exclude"] instanceof Array ? ts.map(json["exclude"], ts.normalizeSlashes) : undefined; + var sysFiles = host.readDirectory(basePath, ".ts", exclude); for (var i = 0; i < sysFiles.length; i++) { var name = sysFiles[i]; if (!ts.fileExtensionIs(name, ".d.ts") || !ts.contains(sysFiles, name.substr(0, name.length - 5) + ".ts")) { - files.push(name); + fileNames.push(name); } } } - return files; + return fileNames; } } ts.parseConfigFile = parseConfigFile; @@ -3112,7 +3224,7 @@ var ts; ts.getDeclarationOfKind = getDeclarationOfKind; var stringWriters = []; function getSingleLineStringWriter() { - if (stringWriters.length == 0) { + if (stringWriters.length === 0) { var str = ""; var writeText = function (text) { return str += text; }; return { @@ -3145,21 +3257,21 @@ var ts; ts.getFullWidth = getFullWidth; function containsParseError(node) { aggregateChildData(node); - return (node.parserContextFlags & 64) !== 0; + return (node.parserContextFlags & 128) !== 0; } ts.containsParseError = containsParseError; function aggregateChildData(node) { - if (!(node.parserContextFlags & 128)) { + if (!(node.parserContextFlags & 256)) { var thisNodeOrAnySubNodesHasError = ((node.parserContextFlags & 32) !== 0) || ts.forEachChild(node, containsParseError); if (thisNodeOrAnySubNodesHasError) { - node.parserContextFlags |= 64; + node.parserContextFlags |= 128; } - node.parserContextFlags |= 128; + node.parserContextFlags |= 256; } } function getSourceFileOfNode(node) { - while (node && node.kind !== 228) { + while (node && node.kind !== 230) { node = node.parent; } return node; @@ -3248,15 +3360,15 @@ var ts; return current; } switch (current.kind) { - case 228: + case 230: + case 210: + case 226: case 208: - case 224: - case 206: - case 187: - case 188: case 189: + case 190: + case 191: return current; - case 180: + case 182: if (!isFunctionLike(current.parent)) { return current; } @@ -3267,9 +3379,9 @@ var ts; ts.getEnclosingBlockScopeContainer = getEnclosingBlockScopeContainer; function isCatchClauseVariableDeclaration(declaration) { return declaration && - declaration.kind === 199 && + declaration.kind === 201 && declaration.parent && - declaration.parent.kind === 224; + declaration.parent.kind === 226; } ts.isCatchClauseVariableDeclaration = isCatchClauseVariableDeclaration; function declarationNameToString(name) { @@ -3305,22 +3417,22 @@ var ts; function getErrorSpanForNode(sourceFile, node) { var errorNode = node; switch (node.kind) { - case 228: + case 230: 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 199: - case 153: - case 202: - case 175: - case 203: - case 206: - case 205: - case 227: case 201: - case 163: + case 155: + case 204: + case 177: + case 205: + case 208: + case 207: + case 229: + case 203: + case 165: errorNode = node.name; break; } @@ -3342,11 +3454,11 @@ var ts; } ts.isDeclarationFile = isDeclarationFile; function isConstEnumDeclaration(node) { - return node.kind === 205 && isConst(node); + return node.kind === 207 && isConst(node); } ts.isConstEnumDeclaration = isConstEnumDeclaration; function walkUpBindingElementsAndPatterns(node) { - while (node && (node.kind === 153 || isBindingPattern(node))) { + while (node && (node.kind === 155 || isBindingPattern(node))) { node = node.parent; } return node; @@ -3354,14 +3466,14 @@ var ts; function getCombinedNodeFlags(node) { node = walkUpBindingElementsAndPatterns(node); var flags = node.flags; - if (node.kind === 199) { + if (node.kind === 201) { node = node.parent; } - if (node && node.kind === 200) { + if (node && node.kind === 202) { flags |= node.flags; node = node.parent; } - if (node && node.kind === 181) { + if (node && node.kind === 183) { flags |= node.flags; } return flags; @@ -3376,11 +3488,11 @@ var ts; } ts.isLet = isLet; function isPrologueDirective(node) { - return node.kind === 183 && node.expression.kind === 8; + return node.kind === 185 && node.expression.kind === 8; } ts.isPrologueDirective = isPrologueDirective; function getLeadingCommentRangesOfNode(node, sourceFileOfNode) { - if (node.kind === 130 || node.kind === 129) { + if (node.kind === 131 || node.kind === 130) { return ts.concatenate(ts.getTrailingCommentRanges(sourceFileOfNode.text, node.pos), ts.getLeadingCommentRanges(sourceFileOfNode.text, node.pos)); } else { @@ -3398,43 +3510,143 @@ var ts; } ts.getJsDocComments = getJsDocComments; ts.fullTripleSlashReferencePathRegEx = /^(\/\/\/\s*/; + function isTypeNode(node) { + if (144 <= node.kind && node.kind <= 152) { + return true; + } + switch (node.kind) { + case 112: + case 121: + case 123: + case 113: + case 124: + return true; + case 99: + return node.parent.kind !== 169; + case 8: + return node.parent.kind === 131; + case 179: + return !isExpressionWithTypeArgumentsInClassExtendsClause(node); + case 65: + if (node.parent.kind === 128 && node.parent.right === node) { + node = node.parent; + } + else if (node.parent.kind === 158 && node.parent.name === node) { + node = node.parent; + } + case 128: + case 158: + ts.Debug.assert(node.kind === 65 || node.kind === 128 || node.kind === 158, "'node' was expected to be a qualified name, identifier or property access in 'isTypeNode'."); + var parent_1 = node.parent; + if (parent_1.kind === 147) { + return false; + } + if (144 <= parent_1.kind && parent_1.kind <= 152) { + return true; + } + switch (parent_1.kind) { + case 179: + return !isExpressionWithTypeArgumentsInClassExtendsClause(parent_1); + case 130: + return node === parent_1.constraint; + case 134: + case 133: + case 131: + case 201: + return node === parent_1.type; + case 203: + case 165: + case 166: + case 137: + case 136: + case 135: + case 138: + case 139: + return node === parent_1.type; + case 140: + case 141: + case 142: + return node === parent_1.type; + case 163: + return node === parent_1.type; + case 160: + case 161: + return parent_1.typeArguments && ts.indexOf(parent_1.typeArguments, node) >= 0; + case 162: + return false; + } + } + return false; + } + ts.isTypeNode = isTypeNode; function forEachReturnStatement(body, visitor) { return traverse(body); function traverse(node) { switch (node.kind) { - case 192: + case 194: return visitor(node); - case 208: - case 180: - case 184: - case 185: + case 210: + case 182: case 186: case 187: case 188: case 189: - case 193: - case 194: - case 221: - case 222: + case 190: + case 191: case 195: - case 197: + case 196: + case 223: case 224: + case 197: + case 199: + case 226: return ts.forEachChild(node, traverse); } } } ts.forEachReturnStatement = forEachReturnStatement; + function forEachYieldExpression(body, visitor) { + return traverse(body); + function traverse(node) { + switch (node.kind) { + case 175: + visitor(node); + var operand = node.expression; + if (operand) { + traverse(operand); + } + case 207: + case 205: + case 208: + case 206: + case 204: + return; + default: + if (isFunctionLike(node)) { + var name_4 = node.name; + if (name_4 && name_4.kind === 129) { + traverse(name_4.expression); + return; + } + } + else if (!isTypeNode(node)) { + ts.forEachChild(node, traverse); + } + } + } + } + ts.forEachYieldExpression = forEachYieldExpression; function isVariableLike(node) { if (node) { switch (node.kind) { - case 153: + case 155: + case 229: + case 131: case 227: - case 130: - case 225: + case 134: case 133: - case 132: - case 226: - case 199: + case 228: + case 201: return true; } } @@ -3444,30 +3656,36 @@ var ts; function isAccessor(node) { if (node) { switch (node.kind) { - case 137: case 138: + case 139: return true; } } return false; } ts.isAccessor = isAccessor; + function isClassLike(node) { + if (node) { + return node.kind === 204 || node.kind === 177; + } + } + ts.isClassLike = isClassLike; function isFunctionLike(node) { if (node) { switch (node.kind) { - case 136: - case 163: - case 201: - case 164: - case 135: - case 134: case 137: + case 165: + case 203: + case 166: + case 136: + case 135: case 138: case 139: case 140: case 141: - case 143: - case 144: + case 142: + case 145: + case 146: return true; } } @@ -3475,11 +3693,11 @@ var ts; } ts.isFunctionLike = isFunctionLike; function isFunctionBlock(node) { - return node && node.kind === 180 && isFunctionLike(node.parent); + return node && node.kind === 182 && isFunctionLike(node.parent); } ts.isFunctionBlock = isFunctionBlock; function isObjectLiteralMethod(node) { - return node && node.kind === 135 && node.parent.kind === 155; + return node && node.kind === 136 && node.parent.kind === 157; } ts.isObjectLiteralMethod = isObjectLiteralMethod; function getContainingFunction(node) { @@ -3498,36 +3716,36 @@ var ts; return undefined; } switch (node.kind) { - case 128: - if (node.parent.parent.kind === 202) { + case 129: + if (node.parent.parent.kind === 204) { return node; } node = node.parent; break; - case 131: - if (node.parent.kind === 130 && isClassElement(node.parent.parent)) { + case 132: + if (node.parent.kind === 131 && isClassElement(node.parent.parent)) { node = node.parent.parent; } else if (isClassElement(node.parent)) { node = node.parent; } break; - case 164: + case 166: if (!includeArrowFunctions) { continue; } - case 201: - case 163: - case 206: - case 133: - case 132: - case 135: + case 203: + case 165: + case 208: case 134: + case 133: case 136: + case 135: case 137: case 138: - case 205: - case 228: + case 139: + case 207: + case 230: return node; } } @@ -3539,40 +3757,40 @@ var ts; if (!node) return node; switch (node.kind) { - case 128: - if (node.parent.parent.kind === 202) { + case 129: + if (node.parent.parent.kind === 204) { return node; } node = node.parent; break; - case 131: - if (node.parent.kind === 130 && isClassElement(node.parent.parent)) { + case 132: + if (node.parent.kind === 131 && isClassElement(node.parent.parent)) { node = node.parent.parent; } else if (isClassElement(node.parent)) { node = node.parent; } break; - case 201: - case 163: - case 164: + case 203: + case 165: + case 166: if (!includeFunctions) { continue; } - case 133: - case 132: - case 135: case 134: + case 133: case 136: + case 135: case 137: case 138: + case 139: return node; } } } ts.getSuperContainer = getSuperContainer; function getInvokedExpression(node) { - if (node.kind === 160) { + if (node.kind === 162) { return node.tag; } return node.expression; @@ -3580,40 +3798,40 @@ var ts; ts.getInvokedExpression = getInvokedExpression; function nodeCanBeDecorated(node) { switch (node.kind) { - case 202: + case 204: return true; - case 133: - return node.parent.kind === 202; - case 130: - return node.parent.body && node.parent.parent.kind === 202; - case 137: + case 134: + return node.parent.kind === 204; + case 131: + return node.parent.body && node.parent.parent.kind === 204; case 138: - case 135: - return node.body && node.parent.kind === 202; + case 139: + case 136: + return node.body && node.parent.kind === 204; } return false; } ts.nodeCanBeDecorated = nodeCanBeDecorated; function nodeIsDecorated(node) { switch (node.kind) { - case 202: + case 204: if (node.decorators) { return true; } return false; - case 133: - case 130: + case 134: + case 131: if (node.decorators) { return true; } return false; - case 137: + case 138: if (node.body && node.decorators) { return true; } return false; - case 135: - case 138: + case 136: + case 139: if (node.body && node.decorators) { return true; } @@ -3624,10 +3842,10 @@ var ts; ts.nodeIsDecorated = nodeIsDecorated; function childIsDecorated(node) { switch (node.kind) { - case 202: + case 204: return ts.forEach(node.members, nodeOrChildIsDecorated); - case 135: - case 138: + case 136: + case 139: return ts.forEach(node.parameters, nodeIsDecorated); } return false; @@ -3645,8 +3863,6 @@ var ts; case 95: case 80: case 9: - case 154: - case 155: case 156: case 157: case 158: @@ -3655,72 +3871,77 @@ var ts; case 161: case 162: case 163: - case 175: case 164: - case 167: case 165: + case 177: case 166: - case 168: case 169: + case 167: + case 168: case 170: case 171: - case 174: case 172: - case 10: + case 173: case 176: + case 174: + case 10: + case 178: + case 175: return true; - case 127: - while (node.parent.kind === 127) { + case 128: + while (node.parent.kind === 128) { node = node.parent; } - return node.parent.kind === 145; + return node.parent.kind === 147; case 65: - if (node.parent.kind === 145) { + if (node.parent.kind === 147) { return true; } case 7: case 8: - var parent_1 = node.parent; - switch (parent_1.kind) { - case 199: - case 130: + var parent_2 = node.parent; + switch (parent_2.kind) { + case 201: + case 131: + case 134: case 133: - case 132: + case 229: case 227: - case 225: - case 153: - return parent_1.initializer === node; - case 183: - case 184: + case 155: + return parent_2.initializer === node; case 185: case 186: - case 192: - case 193: - case 194: - case 221: - case 196: - case 194: - return parent_1.expression === node; case 187: - var forStatement = parent_1; - return (forStatement.initializer === node && forStatement.initializer.kind !== 200) || + case 188: + case 194: + case 195: + case 196: + case 223: + case 198: + case 196: + return parent_2.expression === node; + case 189: + var forStatement = parent_2; + return (forStatement.initializer === node && forStatement.initializer.kind !== 202) || forStatement.condition === node || forStatement.incrementor === node; - case 188: - case 189: - var forInStatement = parent_1; - return (forInStatement.initializer === node && forInStatement.initializer.kind !== 200) || + case 190: + case 191: + var forInStatement = parent_2; + return (forInStatement.initializer === node && forInStatement.initializer.kind !== 202) || forInStatement.expression === node; - case 161: - return node === parent_1.expression; - case 178: - return node === parent_1.expression; - case 128: - return node === parent_1.expression; - case 131: + case 163: + return node === parent_2.expression; + case 180: + return node === parent_2.expression; + case 129: + return node === parent_2.expression; + case 132: return true; + case 179: + return parent_2.expression === node && isExpressionWithTypeArgumentsInClassExtendsClause(parent_2); default: - if (isExpression(parent_1)) { + if (isExpression(parent_2)) { return true; } } @@ -3735,7 +3956,7 @@ var ts; } ts.isInstantiatedModule = isInstantiatedModule; function isExternalModuleImportEqualsDeclaration(node) { - return node.kind === 209 && node.moduleReference.kind === 220; + return node.kind === 211 && node.moduleReference.kind === 222; } ts.isExternalModuleImportEqualsDeclaration = isExternalModuleImportEqualsDeclaration; function getExternalModuleImportEqualsDeclarationExpression(node) { @@ -3744,50 +3965,108 @@ var ts; } ts.getExternalModuleImportEqualsDeclarationExpression = getExternalModuleImportEqualsDeclarationExpression; function isInternalModuleImportEqualsDeclaration(node) { - return node.kind === 209 && node.moduleReference.kind !== 220; + return node.kind === 211 && node.moduleReference.kind !== 222; } ts.isInternalModuleImportEqualsDeclaration = isInternalModuleImportEqualsDeclaration; function getExternalModuleName(node) { - if (node.kind === 210) { + if (node.kind === 212) { return node.moduleSpecifier; } - if (node.kind === 209) { + if (node.kind === 211) { var reference = node.moduleReference; - if (reference.kind === 220) { + if (reference.kind === 222) { return reference.expression; } } - if (node.kind === 216) { + if (node.kind === 218) { return node.moduleSpecifier; } } ts.getExternalModuleName = getExternalModuleName; - function hasDotDotDotToken(node) { - return node && node.kind === 130 && node.dotDotDotToken !== undefined; - } - ts.hasDotDotDotToken = hasDotDotDotToken; function hasQuestionToken(node) { if (node) { switch (node.kind) { - case 130: + case 131: return node.questionToken !== undefined; + case 136: case 135: - case 134: return node.questionToken !== undefined; - case 226: - case 225: + case 228: + case 227: + case 134: case 133: - case 132: return node.questionToken !== undefined; } } return false; } ts.hasQuestionToken = hasQuestionToken; - function hasRestParameters(s) { - return s.parameters.length > 0 && ts.lastOrUndefined(s.parameters).dotDotDotToken !== undefined; + function isJSDocConstructSignature(node) { + return node.kind === 243 && + node.parameters.length > 0 && + node.parameters[0].type.kind === 245; } - ts.hasRestParameters = hasRestParameters; + ts.isJSDocConstructSignature = isJSDocConstructSignature; + function getJSDocTag(node, kind) { + if (node && node.jsDocComment) { + for (var _i = 0, _a = node.jsDocComment.tags; _i < _a.length; _i++) { + var tag = _a[_i]; + if (tag.kind === kind) { + return tag; + } + } + } + } + function getJSDocTypeTag(node) { + return getJSDocTag(node, 251); + } + ts.getJSDocTypeTag = getJSDocTypeTag; + function getJSDocReturnTag(node) { + return getJSDocTag(node, 250); + } + ts.getJSDocReturnTag = getJSDocReturnTag; + function getJSDocTemplateTag(node) { + return getJSDocTag(node, 252); + } + ts.getJSDocTemplateTag = getJSDocTemplateTag; + function getCorrespondingJSDocParameterTag(parameter) { + if (parameter.name && parameter.name.kind === 65) { + var parameterName = parameter.name.text; + var docComment = parameter.parent.jsDocComment; + if (docComment) { + return ts.forEach(docComment.tags, function (t) { + if (t.kind === 249) { + var parameterTag = t; + var name_5 = parameterTag.preParameterName || parameterTag.postParameterName; + if (name_5.text === parameterName) { + return t; + } + } + }); + } + } + } + ts.getCorrespondingJSDocParameterTag = getCorrespondingJSDocParameterTag; + function hasRestParameter(s) { + return isRestParameter(ts.lastOrUndefined(s.parameters)); + } + ts.hasRestParameter = hasRestParameter; + function isRestParameter(node) { + if (node) { + if (node.parserContextFlags & 64) { + if (node.type && node.type.kind === 244) { + return true; + } + var paramTag = getCorrespondingJSDocParameterTag(node); + if (paramTag && paramTag.typeExpression) { + return paramTag.typeExpression.type.kind === 244; + } + } + return node.dotDotDotToken !== undefined; + } + return false; + } + ts.isRestParameter = isRestParameter; function isLiteralKind(kind) { return 7 <= kind && kind <= 10; } @@ -3801,7 +4080,7 @@ var ts; } ts.isTemplateLiteralKind = isTemplateLiteralKind; function isBindingPattern(node) { - return !!node && (node.kind === 152 || node.kind === 151); + return !!node && (node.kind === 154 || node.kind === 153); } ts.isBindingPattern = isBindingPattern; function isInAmbientContext(node) { @@ -3816,33 +4095,33 @@ var ts; ts.isInAmbientContext = isInAmbientContext; function isDeclaration(node) { switch (node.kind) { - case 164: - case 153: - case 202: - case 136: - case 205: - case 227: - case 218: - case 201: - case 163: - case 137: - case 211: - case 209: - case 214: - case 203: - case 135: - case 134: - case 206: - case 212: - case 130: - case 225: - case 133: - case 132: - case 138: - case 226: + case 166: + case 155: case 204: - case 129: - case 199: + case 137: + case 207: + case 229: + case 220: + case 203: + case 165: + case 138: + case 213: + case 211: + case 216: + case 205: + case 136: + case 135: + case 208: + case 214: + case 131: + case 227: + case 134: + case 133: + case 139: + case 228: + case 206: + case 130: + case 201: return true; } return false; @@ -3850,25 +4129,25 @@ var ts; ts.isDeclaration = isDeclaration; function isStatement(n) { switch (n.kind) { - case 191: - case 190: - case 198: - case 185: - case 183: - case 182: - case 188: - case 189: - case 187: - case 184: - case 195: - case 192: - case 194: - case 94: - case 197: - case 181: - case 186: case 193: - case 215: + case 192: + case 200: + case 187: + case 185: + case 184: + case 190: + case 191: + case 189: + case 186: + case 197: + case 194: + case 196: + case 94: + case 199: + case 183: + case 188: + case 195: + case 217: return true; default: return false; @@ -3877,13 +4156,13 @@ var ts; ts.isStatement = isStatement; function isClassElement(n) { switch (n.kind) { - case 136: - case 133: - case 135: case 137: - case 138: case 134: - case 141: + case 136: + case 138: + case 139: + case 135: + case 142: return true; default: return false; @@ -3895,7 +4174,7 @@ var ts; return false; } var parent = name.parent; - if (parent.kind === 214 || parent.kind === 218) { + if (parent.kind === 216 || parent.kind === 220) { if (parent.propertyName) { return true; } @@ -3906,13 +4185,43 @@ var ts; return false; } ts.isDeclarationName = isDeclarationName; + function isIdentifierName(node) { + var parent = node.parent; + switch (parent.kind) { + case 134: + case 133: + case 136: + case 135: + case 138: + case 139: + case 229: + case 227: + case 158: + return parent.name === node; + case 128: + if (parent.right === node) { + while (parent.kind === 128) { + parent = parent.parent; + } + return parent.kind === 147; + } + return false; + case 155: + case 216: + return parent.propertyName === node; + case 220: + return true; + } + return false; + } + ts.isIdentifierName = isIdentifierName; function isAliasSymbolDeclaration(node) { - return node.kind === 209 || - node.kind === 211 && !!node.name || - node.kind === 212 || + return node.kind === 211 || + node.kind === 213 && !!node.name || node.kind === 214 || - node.kind === 218 || - node.kind === 215 && node.expression.kind === 65; + node.kind === 216 || + node.kind === 220 || + node.kind === 217 && node.expression.kind === 65; } ts.isAliasSymbolDeclaration = isAliasSymbolDeclaration; function getClassExtendsHeritageClauseElement(node) { @@ -3995,7 +4304,7 @@ var ts; } ts.getFileReferenceFromReferencePath = getFileReferenceFromReferencePath; function isKeyword(token) { - return 66 <= token && token <= 126; + return 66 <= token && token <= 127; } ts.isKeyword = isKeyword; function isTrivia(token) { @@ -4004,19 +4313,19 @@ var ts; ts.isTrivia = isTrivia; function hasDynamicName(declaration) { return declaration.name && - declaration.name.kind === 128 && + declaration.name.kind === 129 && !isWellKnownSymbolSyntactically(declaration.name.expression); } ts.hasDynamicName = hasDynamicName; function isWellKnownSymbolSyntactically(node) { - return node.kind === 156 && isESSymbolIdentifier(node.expression); + return node.kind === 158 && isESSymbolIdentifier(node.expression); } ts.isWellKnownSymbolSyntactically = isWellKnownSymbolSyntactically; function getPropertyNameForPropertyNameNode(name) { if (name.kind === 65 || name.kind === 8 || name.kind === 7) { return name.text; } - if (name.kind === 128) { + if (name.kind === 129) { var nameExpression = name.expression; if (isWellKnownSymbolSyntactically(nameExpression)) { var rightHandSideName = nameExpression.name.text; @@ -4051,18 +4360,18 @@ var ts; ts.isModifier = isModifier; function isParameterDeclaration(node) { var root = getRootDeclaration(node); - return root.kind === 130; + return root.kind === 131; } ts.isParameterDeclaration = isParameterDeclaration; function getRootDeclaration(node) { - while (node.kind === 153) { + while (node.kind === 155) { node = node.parent.parent; } return node; } ts.getRootDeclaration = getRootDeclaration; function nodeStartsNewLexicalEnvironment(n) { - return isFunctionLike(n) || n.kind === 206 || n.kind === 228; + return isFunctionLike(n) || n.kind === 208 || n.kind === 230; } ts.nodeStartsNewLexicalEnvironment = nodeStartsNewLexicalEnvironment; function nodeIsSynthesized(node) { @@ -4286,7 +4595,7 @@ var ts; ts.getLineOfLocalPosition = getLineOfLocalPosition; function getFirstConstructorWithBody(node) { return ts.forEach(node.members, function (member) { - if (member.kind === 136 && nodeIsPresent(member.body)) { + if (member.kind === 137 && nodeIsPresent(member.body)) { return member; } }); @@ -4295,7 +4604,7 @@ var ts; function shouldEmitToOwnFile(sourceFile, compilerOptions) { if (!isDeclarationFile(sourceFile)) { if ((isExternalModule(sourceFile) || !compilerOptions.out)) { - return compilerOptions.separateCompilation || !ts.fileExtensionIs(sourceFile.fileName, ".js"); + return compilerOptions.isolatedModules || !ts.fileExtensionIs(sourceFile.fileName, ".js"); } return false; } @@ -4309,10 +4618,10 @@ var ts; var setAccessor; if (hasDynamicName(accessor)) { firstAccessor = accessor; - if (accessor.kind === 137) { + if (accessor.kind === 138) { getAccessor = accessor; } - else if (accessor.kind === 138) { + else if (accessor.kind === 139) { setAccessor = accessor; } else { @@ -4321,7 +4630,7 @@ var ts; } else { ts.forEach(declarations, function (member) { - if ((member.kind === 137 || member.kind === 138) + if ((member.kind === 138 || member.kind === 139) && (member.flags & 128) === (accessor.flags & 128)) { var memberName = getPropertyNameForPropertyNameNode(member.name); var accessorName = getPropertyNameForPropertyNameNode(accessor.name); @@ -4332,10 +4641,10 @@ var ts; else if (!secondAccessor) { secondAccessor = member; } - if (member.kind === 137 && !getAccessor) { + if (member.kind === 138 && !getAccessor) { getAccessor = member; } - if (member.kind === 138 && !setAccessor) { + if (member.kind === 139 && !setAccessor) { setAccessor = member; } } @@ -4456,22 +4765,22 @@ var ts; function isLeftHandSideExpression(expr) { if (expr) { switch (expr.kind) { - case 156: - case 157: - case 159: case 158: + case 159: + case 161: case 160: - case 154: case 162: - case 155: - case 175: - case 163: + case 156: + case 164: + case 157: + case 177: + case 165: case 65: case 9: case 7: case 8: case 10: - case 172: + case 174: case 80: case 89: case 93: @@ -4487,6 +4796,12 @@ var ts; return token >= 53 && token <= 64; } ts.isAssignmentOperator = isAssignmentOperator; + function isExpressionWithTypeArgumentsInClassExtendsClause(node) { + return node.kind === 179 && + node.parent.token === 79 && + node.parent.parent.kind === 204; + } + ts.isExpressionWithTypeArgumentsInClassExtendsClause = isExpressionWithTypeArgumentsInClassExtendsClause; function isSupportedExpressionWithTypeArguments(node) { return isSupportedExpressionWithTypeArgumentsRest(node.expression); } @@ -4495,7 +4810,7 @@ var ts; if (node.kind === 65) { return true; } - else if (node.kind === 156) { + else if (node.kind === 158) { return isSupportedExpressionWithTypeArgumentsRest(node.expression); } else { @@ -4503,14 +4818,18 @@ var ts; } } function isRightSideOfQualifiedNameOrPropertyAccess(node) { - return (node.parent.kind === 127 && node.parent.right === node) || - (node.parent.kind === 156 && node.parent.name === node); + return (node.parent.kind === 128 && node.parent.right === node) || + (node.parent.kind === 158 && node.parent.name === node); } ts.isRightSideOfQualifiedNameOrPropertyAccess = isRightSideOfQualifiedNameOrPropertyAccess; function getLocalSymbolForExportDefault(symbol) { return symbol && symbol.valueDeclaration && (symbol.valueDeclaration.flags & 256) ? symbol.valueDeclaration.localSymbol : undefined; } ts.getLocalSymbolForExportDefault = getLocalSymbolForExportDefault; + function isJavaScript(fileName) { + return ts.fileExtensionIs(fileName, ".js"); + } + ts.isJavaScript = isJavaScript; function getExpandedCharCodes(input) { var output = []; var length = input.length; @@ -4565,6 +4884,21 @@ var ts; return result; } ts.convertToBase64 = convertToBase64; + var carriageReturnLineFeed = "\r\n"; + var lineFeed = "\n"; + function getNewLineCharacter(options) { + if (options.newLine === 0) { + return carriageReturnLineFeed; + } + else if (options.newLine === 1) { + return lineFeed; + } + else if (ts.sys) { + return ts.sys.newLine; + } + return carriageReturnLineFeed; + } + ts.getNewLineCharacter = getNewLineCharacter; })(ts || (ts = {})); var ts; (function (ts) { @@ -4612,6 +4946,12 @@ var ts; 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; } @@ -4681,12 +5021,22 @@ var ts; return createTextChangeRange(createTextSpanFromBounds(oldStartN, oldEndN), newEndN - oldStartN); } ts.collapseTextChangeRangesAcrossMultipleVersions = collapseTextChangeRangesAcrossMultipleVersions; + function getTypeParameterOwner(d) { + if (d && d.kind === 130) { + for (var current = d; current; current = current.parent) { + if (ts.isFunctionLike(current) || ts.isClassLike(current) || current.kind === 205) { + return current; + } + } + } + } + ts.getTypeParameterOwner = getTypeParameterOwner; })(ts || (ts = {})); /// /// var ts; (function (ts) { - var nodeConstructors = new Array(230); + var nodeConstructors = new Array(254); ts.parseTime = 0; function getNodeConstructor(kind) { return nodeConstructors[kind] || (nodeConstructors[kind] = ts.objectAllocator.getNodeConstructor(kind)); @@ -4724,20 +5074,20 @@ var ts; var visitNodes = cbNodeArray ? visitNodeArray : visitEachNode; var cbNodes = cbNodeArray || cbNode; switch (node.kind) { - case 127: + case 128: return visitNode(cbNode, node.left) || visitNode(cbNode, node.right); - case 129: + case 130: return visitNode(cbNode, node.name) || visitNode(cbNode, node.constraint) || visitNode(cbNode, node.expression); - case 130: + case 131: + case 134: case 133: - case 132: - case 225: - case 226: - case 199: - case 153: + case 227: + case 228: + case 201: + case 155: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.propertyName) || @@ -4746,24 +5096,24 @@ var ts; visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.type) || visitNode(cbNode, node.initializer); - case 143: - case 144: - case 139: + case 145: + case 146: case 140: case 141: + case 142: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNodes(cbNodes, node.typeParameters) || visitNodes(cbNodes, node.parameters) || visitNode(cbNode, node.type); - case 135: - case 134: case 136: + case 135: case 137: case 138: - case 163: - case 201: - case 164: + case 139: + case 165: + case 203: + case 166: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.asteriskToken) || @@ -4774,221 +5124,268 @@ var ts; visitNode(cbNode, node.type) || visitNode(cbNode, node.equalsGreaterThanToken) || visitNode(cbNode, node.body); - case 142: + case 144: return visitNode(cbNode, node.typeName) || visitNodes(cbNodes, node.typeArguments); - case 145: - return visitNode(cbNode, node.exprName); - case 146: - return visitNodes(cbNodes, node.members); + case 143: + return visitNode(cbNode, node.parameterName) || + visitNode(cbNode, node.type); case 147: - return visitNode(cbNode, node.elementType); + return visitNode(cbNode, node.exprName); case 148: - return visitNodes(cbNodes, node.elementTypes); + return visitNodes(cbNodes, node.members); case 149: - return visitNodes(cbNodes, node.types); + return visitNode(cbNode, node.elementType); case 150: - return visitNode(cbNode, node.type); + return visitNodes(cbNodes, node.elementTypes); case 151: + return visitNodes(cbNodes, node.types); case 152: - return visitNodes(cbNodes, node.elements); + return visitNode(cbNode, node.type); + case 153: case 154: return visitNodes(cbNodes, node.elements); - case 155: - return visitNodes(cbNodes, node.properties); case 156: + return visitNodes(cbNodes, node.elements); + case 157: + return visitNodes(cbNodes, node.properties); + case 158: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.dotToken) || visitNode(cbNode, node.name); - case 157: + case 159: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.argumentExpression); - case 158: - case 159: + case 160: + case 161: return visitNode(cbNode, node.expression) || visitNodes(cbNodes, node.typeArguments) || visitNodes(cbNodes, node.arguments); - case 160: + case 162: return visitNode(cbNode, node.tag) || visitNode(cbNode, node.template); - case 161: + case 163: return visitNode(cbNode, node.type) || visitNode(cbNode, node.expression); - case 162: - return visitNode(cbNode, node.expression); - case 165: - return visitNode(cbNode, node.expression); - case 166: + case 164: return visitNode(cbNode, node.expression); case 167: return visitNode(cbNode, node.expression); case 168: + return visitNode(cbNode, node.expression); + case 169: + return visitNode(cbNode, node.expression); + case 170: return visitNode(cbNode, node.operand); - case 173: + case 175: return visitNode(cbNode, node.asteriskToken) || visitNode(cbNode, node.expression); - case 169: + case 171: return visitNode(cbNode, node.operand); - case 170: + case 172: return visitNode(cbNode, node.left) || visitNode(cbNode, node.operatorToken) || visitNode(cbNode, node.right); - case 171: + case 173: return visitNode(cbNode, node.condition) || visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.whenTrue) || visitNode(cbNode, node.colonToken) || visitNode(cbNode, node.whenFalse); - case 174: + case 176: return visitNode(cbNode, node.expression); - case 180: - case 207: + case 182: + case 209: return visitNodes(cbNodes, node.statements); - case 228: + case 230: return visitNodes(cbNodes, node.statements) || visitNode(cbNode, node.endOfFileToken); - case 181: + case 183: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.declarationList); - case 200: + case 202: return visitNodes(cbNodes, node.declarations); - case 183: + case 185: return visitNode(cbNode, node.expression); - case 184: + case 186: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.thenStatement) || visitNode(cbNode, node.elseStatement); - case 185: + case 187: return visitNode(cbNode, node.statement) || visitNode(cbNode, node.expression); - case 186: + case 188: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.statement); - case 187: + case 189: return visitNode(cbNode, node.initializer) || visitNode(cbNode, node.condition) || visitNode(cbNode, node.incrementor) || visitNode(cbNode, node.statement); - case 188: - return visitNode(cbNode, node.initializer) || - visitNode(cbNode, node.expression) || - visitNode(cbNode, node.statement); - case 189: - return visitNode(cbNode, node.initializer) || - visitNode(cbNode, node.expression) || - visitNode(cbNode, node.statement); case 190: - case 191: - return visitNode(cbNode, node.label); - case 192: - return visitNode(cbNode, node.expression); - case 193: - return visitNode(cbNode, node.expression) || + return visitNode(cbNode, node.initializer) || + visitNode(cbNode, node.expression) || visitNode(cbNode, node.statement); + case 191: + return visitNode(cbNode, node.initializer) || + visitNode(cbNode, node.expression) || + visitNode(cbNode, node.statement); + case 192: + case 193: + return visitNode(cbNode, node.label); case 194: - return visitNode(cbNode, node.expression) || - visitNode(cbNode, node.caseBlock); - case 208: - return visitNodes(cbNodes, node.clauses); - case 221: - return visitNode(cbNode, node.expression) || - visitNodes(cbNodes, node.statements); - case 222: - return visitNodes(cbNodes, node.statements); + return visitNode(cbNode, node.expression); case 195: - return visitNode(cbNode, node.label) || + return visitNode(cbNode, node.expression) || visitNode(cbNode, node.statement); case 196: - return visitNode(cbNode, node.expression); + return visitNode(cbNode, node.expression) || + visitNode(cbNode, node.caseBlock); + case 210: + return visitNodes(cbNodes, node.clauses); + case 223: + return visitNode(cbNode, node.expression) || + visitNodes(cbNodes, node.statements); + case 224: + return visitNodes(cbNodes, node.statements); case 197: + return visitNode(cbNode, node.label) || + visitNode(cbNode, node.statement); + case 198: + return visitNode(cbNode, node.expression); + case 199: return visitNode(cbNode, node.tryBlock) || visitNode(cbNode, node.catchClause) || visitNode(cbNode, node.finallyBlock); - case 224: + case 226: return visitNode(cbNode, node.variableDeclaration) || visitNode(cbNode, node.block); - case 131: + case 132: return visitNode(cbNode, node.expression); - case 202: - case 175: - 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 203: - 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 204: + case 177: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.name) || - visitNode(cbNode, node.type); + visitNodes(cbNodes, node.typeParameters) || + visitNodes(cbNodes, node.heritageClauses) || + visitNodes(cbNodes, node.members); case 205: 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 227: - return visitNode(cbNode, node.name) || - visitNode(cbNode, node.initializer); case 206: + return visitNodes(cbNodes, node.decorators) || + visitNodes(cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNodes(cbNodes, node.typeParameters) || + visitNode(cbNode, node.type); + case 207: + return visitNodes(cbNodes, node.decorators) || + visitNodes(cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNodes(cbNodes, node.members); + case 229: + return visitNode(cbNode, node.name) || + visitNode(cbNode, node.initializer); + case 208: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.body); - case 209: + case 211: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.moduleReference); - case 210: + case 212: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.importClause) || visitNode(cbNode, node.moduleSpecifier); - case 211: + case 213: return visitNode(cbNode, node.name) || visitNode(cbNode, node.namedBindings); - case 212: + case 214: return visitNode(cbNode, node.name); - case 213: - case 217: + case 215: + case 219: return visitNodes(cbNodes, node.elements); - case 216: + case 218: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.exportClause) || visitNode(cbNode, node.moduleSpecifier); - case 214: - case 218: + case 216: + case 220: return visitNode(cbNode, node.propertyName) || visitNode(cbNode, node.name); - case 215: + case 217: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.expression); - case 172: + case 174: return visitNode(cbNode, node.head) || visitNodes(cbNodes, node.templateSpans); - case 178: + case 180: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.literal); - case 128: + case 129: return visitNode(cbNode, node.expression); - case 223: + case 225: return visitNodes(cbNodes, node.types); - case 177: + case 179: return visitNode(cbNode, node.expression) || visitNodes(cbNodes, node.typeArguments); - case 220: + case 222: return visitNode(cbNode, node.expression); - case 219: + case 221: return visitNodes(cbNodes, node.decorators); + case 231: + return visitNode(cbNode, node.type); + case 235: + return visitNodes(cbNodes, node.types); + case 236: + return visitNodes(cbNodes, node.types); + case 234: + return visitNode(cbNode, node.elementType); + case 238: + return visitNode(cbNode, node.type); + case 237: + return visitNode(cbNode, node.type); + case 239: + return visitNodes(cbNodes, node.members); + case 241: + return visitNode(cbNode, node.name) || + visitNodes(cbNodes, node.typeArguments); + case 242: + return visitNode(cbNode, node.type); + case 243: + return visitNodes(cbNodes, node.parameters) || + visitNode(cbNode, node.type); + case 244: + return visitNode(cbNode, node.type); + case 245: + return visitNode(cbNode, node.type); + case 246: + return visitNode(cbNode, node.type); + case 240: + return visitNode(cbNode, node.name) || + visitNode(cbNode, node.type); + case 247: + return visitNodes(cbNodes, node.tags); + case 249: + return visitNode(cbNode, node.preParameterName) || + visitNode(cbNode, node.typeExpression) || + visitNode(cbNode, node.postParameterName); + case 250: + return visitNode(cbNode, node.typeExpression); + case 251: + return visitNode(cbNode, node.typeExpression); + case 252: + return visitNodes(cbNodes, node.typeParameters); } } ts.forEachChild = forEachChild; @@ -5004,11 +5401,20 @@ var ts; return IncrementalParser.updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks); } ts.updateSourceFile = updateSourceFile; + function parseIsolatedJSDocComment(content, start, length) { + return Parser.JSDocParser.parseIsolatedJSDocComment(content, start, length); + } + 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(2, true); var disallowInAndDecoratorContext = 2 | 16; var sourceFile; + var parseDiagnostics; var syntaxCursor; var token; var sourceText; @@ -5016,44 +5422,83 @@ var ts; var identifiers; var identifierCount; var parsingContext; - var contextFlags = 0; + var contextFlags; var parseErrorBeforeNextFinishedNode = false; function parseSourceFile(fileName, _sourceText, languageVersion, _syntaxCursor, setParentNodes) { + initializeState(fileName, _sourceText, languageVersion, _syntaxCursor); + var result = parseSourceFileWorker(fileName, languageVersion, setParentNodes); + clearState(); + return result; + } + Parser.parseSourceFile = parseSourceFile; + function initializeState(fileName, _sourceText, languageVersion, _syntaxCursor) { sourceText = _sourceText; syntaxCursor = _syntaxCursor; + parseDiagnostics = []; parsingContext = 0; identifiers = {}; identifierCount = 0; nodeCount = 0; - contextFlags = 0; + contextFlags = ts.isJavaScript(fileName) ? 64 : 0; parseErrorBeforeNextFinishedNode = false; - createSourceFile(fileName, languageVersion); scanner.setText(sourceText); scanner.setOnError(scanError); scanner.setScriptTarget(languageVersion); + } + function clearState() { + scanner.setText(""); + scanner.setOnError(undefined); + parseDiagnostics = undefined; + sourceFile = undefined; + identifiers = undefined; + syntaxCursor = undefined; + sourceText = undefined; + } + function parseSourceFileWorker(fileName, languageVersion, setParentNodes) { + sourceFile = createSourceFile(fileName, languageVersion); token = nextToken(); processReferenceComments(sourceFile); - sourceFile.statements = parseList(0, true, parseSourceElement); + 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); } - syntaxCursor = undefined; - scanner.setText(""); - scanner.setOnError(undefined); - var result = sourceFile; - sourceFile = undefined; - identifiers = undefined; - syntaxCursor = undefined; - sourceText = undefined; - return result; + if (ts.isJavaScript(fileName)) { + addJSDocComments(); + } + return sourceFile; + } + function addJSDocComments() { + forEachChild(sourceFile, visit); + return; + function visit(node) { + switch (node.kind) { + case 183: + case 203: + case 131: + addJSDocComment(node); + } + forEachChild(node, visit); + } + } + function addJSDocComment(node) { + var comments = ts.getLeadingCommentRangesOfNode(node, sourceFile); + if (comments) { + for (var _i = 0; _i < comments.length; _i++) { + var comment = comments[_i]; + var jsDocComment = JSDocParser.parseJSDocComment(node, comment.pos, comment.end - comment.pos); + if (jsDocComment) { + node.jsDocComment = jsDocComment; + } + } + } } - Parser.parseSourceFile = parseSourceFile; function fixupParentReferences(sourceFile) { // 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 @@ -5072,16 +5517,17 @@ var ts; } } } + Parser.fixupParentReferences = fixupParentReferences; function createSourceFile(fileName, languageVersion) { - sourceFile = createNode(228, 0); + var sourceFile = createNode(230, 0); sourceFile.pos = 0; sourceFile.end = sourceText.length; sourceFile.text = sourceText; - sourceFile.parseDiagnostics = []; sourceFile.bindDiagnostics = []; sourceFile.languageVersion = languageVersion; sourceFile.fileName = ts.normalizePath(fileName); sourceFile.flags = ts.fileExtensionIs(sourceFile.fileName, ".d.ts") ? 2048 : 0; + return sourceFile; } function setContextFlag(val, flag) { if (val) { @@ -5091,9 +5537,6 @@ var ts; contextFlags &= ~flag; } } - function setStrictModeContext(val) { - setContextFlag(val, 1); - } function setDisallowInContext(val) { setContextFlag(val, 2); } @@ -5164,9 +5607,6 @@ var ts; function inYieldContext() { return (contextFlags & 4) !== 0; } - function inStrictModeContext() { - return (contextFlags & 1) !== 0; - } function inGeneratorParameterContext() { return (contextFlags & 8) !== 0; } @@ -5182,9 +5622,9 @@ var ts; parseErrorAtPosition(start, length, message, arg0); } function parseErrorAtPosition(start, length, message, arg0) { - var lastError = ts.lastOrUndefined(sourceFile.parseDiagnostics); + var lastError = ts.lastOrUndefined(parseDiagnostics); if (!lastError || start !== lastError.start) { - sourceFile.parseDiagnostics.push(ts.createFileDiagnostic(sourceFile, start, length, message, arg0)); + parseDiagnostics.push(ts.createFileDiagnostic(sourceFile, start, length, message, arg0)); } parseErrorBeforeNextFinishedNode = true; } @@ -5215,7 +5655,7 @@ var ts; } function speculationHelper(callback, isLookAhead) { var saveToken = token; - var saveParseDiagnosticsLength = sourceFile.parseDiagnostics.length; + var saveParseDiagnosticsLength = parseDiagnostics.length; var saveParseErrorBeforeNextFinishedNode = parseErrorBeforeNextFinishedNode; var saveContextFlags = contextFlags; var result = isLookAhead @@ -5224,7 +5664,7 @@ var ts; ts.Debug.assert(saveContextFlags === contextFlags); if (!result || isLookAhead) { token = saveToken; - sourceFile.parseDiagnostics.length = saveParseDiagnosticsLength; + parseDiagnostics.length = saveParseDiagnosticsLength; parseErrorBeforeNextFinishedNode = saveParseErrorBeforeNextFinishedNode; } return result; @@ -5306,8 +5746,8 @@ var ts; node.end = pos; return node; } - function finishNode(node) { - node.end = scanner.getStartPos(); + function finishNode(node, end) { + node.end = end === undefined ? scanner.getStartPos() : end; if (contextFlags) { node.parserContextFlags = contextFlags; } @@ -5356,17 +5796,26 @@ var ts; token === 8 || token === 7; } - function parsePropertyName() { + function parsePropertyNameWorker(allowComputedPropertyNames) { if (token === 8 || token === 7) { return parseLiteralNode(true); } - if (token === 18) { + if (allowComputedPropertyNames && token === 18) { return parseComputedPropertyName(); } return parseIdentifierName(); } + function parsePropertyName() { + return parsePropertyNameWorker(true); + } + function parseSimplePropertyName() { + return parsePropertyNameWorker(false); + } + function isSimplePropertyName() { + return token === 8 || token === 7 || isIdentifierOrKeyword(); + } function parseComputedPropertyName() { - var node = createNode(128); + var node = createNode(129); parseExpected(18); var yieldContext = inYieldContext(); if (inGeneratorParameterContext()) { @@ -5420,23 +5869,21 @@ var ts; switch (parsingContext) { case 0: case 1: - return isSourceElement(inErrorRecovery); - case 2: - case 4: - return isStartOfStatement(inErrorRecovery); case 3: + return !(token === 22 && inErrorRecovery) && isStartOfStatement(); + case 2: return token === 67 || token === 73; - case 5: + case 4: return isStartOfTypeMember(); - case 6: + case 5: return lookAhead(isClassMemberStart) || (token === 22 && !inErrorRecovery); - case 7: + case 6: return token === 18 || isLiteralPropertyName(); - case 13: + case 12: return token === 18 || token === 35 || isLiteralPropertyName(); - case 10: + case 9: return isLiteralPropertyName(); - case 8: + case 7: if (token === 14) { return lookAhead(isValidHeritageClauseObjectLiteral); } @@ -5446,24 +5893,30 @@ var ts; else { return isIdentifier() && !isHeritageClauseExtendsOrImplementsKeyword(); } - case 9: + case 8: return isIdentifierOrPattern(); - case 11: + case 10: return token === 23 || token === 21 || isIdentifierOrPattern(); - case 16: - return isIdentifier(); - case 12: - case 14: - return token === 23 || token === 21 || isStartOfExpression(); case 15: + return isIdentifier(); + case 11: + case 13: + return token === 23 || token === 21 || isStartOfExpression(); + case 14: return isStartOfParameter(); + case 16: case 17: - case 18: return token === 23 || isStartOfType(); - case 19: + case 18: return isHeritageClause(); - case 20: + case 19: return isIdentifierOrKeyword(); + case 20: + case 21: + case 23: + return JSDocParser.isJSDocType(); + case 22: + return isSimplePropertyName(); } ts.Debug.fail("Non-exhaustive case in 'isListElement'."); } @@ -5497,34 +5950,41 @@ var ts; switch (kind) { case 1: case 2: - case 3: + case 4: case 5: case 6: - case 7: - case 13: - case 10: - case 20: - return token === 15; - case 4: - return token === 15 || token === 67 || token === 73; - case 8: - return token === 14 || token === 79 || token === 102; - case 9: - return isVariableDeclaratorListTerminator(); - case 16: - return token === 25 || token === 16 || token === 14 || token === 79 || token === 102; case 12: - return token === 17 || token === 22; - case 14: - case 18: - case 11: - return token === 19; - case 15: - return token === 17 || token === 19; - case 17: - return token === 25 || token === 16; + case 9: case 19: + return token === 15; + case 3: + return token === 15 || token === 67 || token === 73; + case 7: + return token === 14 || token === 79 || token === 102; + case 8: + return isVariableDeclaratorListTerminator(); + case 15: + return token === 25 || token === 16 || token === 14 || token === 79 || token === 102; + case 11: + return token === 17 || token === 22; + case 13: + case 17: + case 10: + return token === 19; + case 14: + return token === 17 || token === 19; + case 16: + return token === 25 || token === 16; + case 18: return token === 14 || token === 15; + case 20: + return token === 17 || token === 51 || token === 15; + case 21: + return token === 25 || token === 15; + case 23: + return token === 19 || token === 15; + case 22: + return token === 15; } } function isVariableDeclaratorListTerminator() { @@ -5540,7 +6000,7 @@ var ts; return false; } function isInSomeParsingContext() { - for (var kind = 0; kind < 21; kind++) { + for (var kind = 0; kind < 24; kind++) { if (parsingContext & (1 << kind)) { if (isListElement(kind, true) || isListTerminator(kind)) { return true; @@ -5549,43 +6009,25 @@ var ts; } return false; } - function parseList(kind, checkForStrictMode, parseElement) { + function parseList(kind, parseElement) { var saveParsingContext = parsingContext; parsingContext |= 1 << kind; var result = []; result.pos = getNodePos(); - var savedStrictModeContext = inStrictModeContext(); while (!isListTerminator(kind)) { if (isListElement(kind, false)) { var element = parseListElement(kind, parseElement); result.push(element); - if (checkForStrictMode && !inStrictModeContext()) { - if (ts.isPrologueDirective(element)) { - if (isUseStrictPrologueDirective(sourceFile, element)) { - setStrictModeContext(true); - checkForStrictMode = false; - } - } - else { - checkForStrictMode = false; - } - } continue; } if (abortParsingListOrMoveToNextToken(kind)) { break; } } - setStrictModeContext(savedStrictModeContext); result.end = getNodeEnd(); parsingContext = saveParsingContext; return result; } - function isUseStrictPrologueDirective(sourceFile, node) { - ts.Debug.assert(ts.isPrologueDirective(node)); - var nodeText = ts.getSourceTextOfNodeFromSourceFile(sourceFile, node.expression); - return nodeText === '"use strict"' || nodeText === "'use strict'"; - } function parseListElement(parsingContext, parseElement) { var node = currentNode(parsingContext); if (node) { @@ -5610,7 +6052,7 @@ var ts; if (ts.containsParseError(node)) { return undefined; } - var nodeContextFlags = node.parserContextFlags & 63; + var nodeContextFlags = node.parserContextFlags & 62; if (nodeContextFlags !== contextFlags) { return undefined; } @@ -5626,61 +6068,47 @@ var ts; } function canReuseNode(node, parsingContext) { switch (parsingContext) { - case 1: - return isReusableModuleElement(node); - case 6: - return isReusableClassMember(node); - case 3: - return isReusableSwitchClause(node); - case 2: - case 4: - return isReusableStatement(node); - case 7: - return isReusableEnumMember(node); 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 9: - return isReusableVariableDeclaration(node); - case 15: - return isReusableParameter(node); - case 19: - case 16: - case 18: - case 17: - case 12: - case 13: case 8: - } - return false; - } - function isReusableModuleElement(node) { - if (node) { - switch (node.kind) { - case 210: - case 209: - case 216: - case 215: - case 202: - case 203: - case 206: - case 205: - return true; - } - return isReusableStatement(node); + return isReusableVariableDeclaration(node); + case 14: + return isReusableParameter(node); + case 18: + case 15: + case 17: + case 16: + case 11: + case 12: + case 7: } return false; } function isReusableClassMember(node) { if (node) { switch (node.kind) { - case 136: - case 141: - case 135: case 137: + case 142: case 138: - case 133: - case 179: + case 139: + case 134: + case 181: return true; + case 136: + var methodDeclaration = node; + var nameIsConstructor = methodDeclaration.name.kind === 65 && + methodDeclaration.name.originalKeywordKind === 114; + return !nameIsConstructor; } } return false; @@ -5688,8 +6116,8 @@ var ts; function isReusableSwitchClause(node) { if (node) { switch (node.kind) { - case 221: - case 222: + case 223: + case 224: return true; } } @@ -5698,56 +6126,65 @@ var ts; function isReusableStatement(node) { if (node) { switch (node.kind) { - case 201: - case 181: - case 180: - case 184: + case 203: case 183: - case 196: - case 192: - case 194: - case 191: - case 190: - case 188: - case 189: - case 187: - case 186: - case 193: case 182: - case 197: - case 195: + case 186: case 185: case 198: + case 194: + case 196: + case 193: + case 192: + case 190: + case 191: + case 189: + case 188: + case 195: + case 184: + case 199: + case 197: + case 187: + case 200: + case 212: + case 211: + case 218: + case 217: + case 208: + case 204: + case 205: + case 207: + case 206: return true; } } return false; } function isReusableEnumMember(node) { - return node.kind === 227; + return node.kind === 229; } function isReusableTypeMember(node) { if (node) { switch (node.kind) { - case 140: - case 134: case 141: - case 132: - case 139: + case 135: + case 142: + case 133: + case 140: return true; } } return false; } function isReusableVariableDeclaration(node) { - if (node.kind !== 199) { + if (node.kind !== 201) { return false; } var variableDeclarator = node; return variableDeclarator.initializer === undefined; } function isReusableParameter(node) { - if (node.kind !== 130) { + if (node.kind !== 131) { return false; } var parameter = node; @@ -5765,25 +6202,28 @@ var ts; 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.Statement_expected; - case 3: return ts.Diagnostics.case_or_default_expected; - case 4: return ts.Diagnostics.Statement_expected; - case 5: return ts.Diagnostics.Property_or_signature_expected; - case 6: return ts.Diagnostics.Unexpected_token_A_constructor_method_accessor_or_property_was_expected; - case 7: return ts.Diagnostics.Enum_member_expected; - case 8: return ts.Diagnostics.Expression_expected; - case 9: return ts.Diagnostics.Variable_declaration_expected; - case 10: return ts.Diagnostics.Property_destructuring_pattern_expected; - case 11: return ts.Diagnostics.Array_element_destructuring_pattern_expected; - case 12: return ts.Diagnostics.Argument_expression_expected; - case 13: return ts.Diagnostics.Property_assignment_expected; - case 14: return ts.Diagnostics.Expression_or_comma_expected; - case 15: return ts.Diagnostics.Parameter_declaration_expected; - case 16: return ts.Diagnostics.Type_parameter_declaration_expected; - case 17: return ts.Diagnostics.Type_argument_expected; - case 18: return ts.Diagnostics.Type_expected; - case 19: return ts.Diagnostics.Unexpected_token_expected; - case 20: return ts.Diagnostics.Identifier_expected; + case 2: return ts.Diagnostics.case_or_default_expected; + case 3: return ts.Diagnostics.Statement_expected; + 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 13: return ts.Diagnostics.Expression_or_comma_expected; + case 14: return ts.Diagnostics.Parameter_declaration_expected; + case 15: return ts.Diagnostics.Type_parameter_declaration_expected; + case 16: return ts.Diagnostics.Type_argument_expected; + case 17: return ts.Diagnostics.Type_expected; + case 18: return ts.Diagnostics.Unexpected_token_expected; + case 19: return ts.Diagnostics.Identifier_expected; + case 20: return ts.Diagnostics.Parameter_declaration_expected; + case 21: return ts.Diagnostics.Type_argument_expected; + case 23: return ts.Diagnostics.Type_expected; + case 22: return ts.Diagnostics.Property_assignment_expected; } } ; @@ -5842,7 +6282,7 @@ var ts; function parseEntityName(allowReservedWords, diagnosticMessage) { var entity = parseIdentifier(diagnosticMessage); while (parseOptional(20)) { - var node = createNode(127, entity.pos); + var node = createNode(128, entity.pos); node.left = entity; node.right = parseRightSideOfDot(allowReservedWords); entity = finishNode(node); @@ -5850,7 +6290,7 @@ var ts; return entity; } function parseRightSideOfDot(allowIdentifierNames) { - if (scanner.hasPrecedingLineBreak() && scanner.isReservedWord()) { + if (scanner.hasPrecedingLineBreak() && isIdentifierOrKeyword()) { var matchesPattern = lookAhead(nextTokenIsIdentifierOrKeywordOnSameLine); if (matchesPattern) { return createMissingNode(65, true, ts.Diagnostics.Identifier_expected); @@ -5859,7 +6299,7 @@ var ts; return allowIdentifierNames ? parseIdentifierName() : parseIdentifier(); } function parseTemplateExpression() { - var template = createNode(172); + var template = createNode(174); template.head = parseLiteralNode(); ts.Debug.assert(template.head.kind === 11, "Template head has wrong token kind"); var templateSpans = []; @@ -5872,7 +6312,7 @@ var ts; return finishNode(template); } function parseTemplateSpan() { - var span = createNode(178); + var span = createNode(180); span.expression = allowInAnd(parseExpression); var literal; if (token === 15) { @@ -5905,22 +6345,30 @@ var ts; } return node; } - function parseTypeReference() { - var node = createNode(142); - node.typeName = parseEntityName(false, ts.Diagnostics.Type_expected); + function parseTypeReferenceOrTypePredicate() { + var typeName = parseEntityName(false, ts.Diagnostics.Type_expected); + if (typeName.kind === 65 && token === 117 && !scanner.hasPrecedingLineBreak()) { + nextToken(); + var node_1 = createNode(143, typeName.pos); + node_1.parameterName = typeName; + node_1.type = parseType(); + return finishNode(node_1); + } + var node = createNode(144, typeName.pos); + node.typeName = typeName; if (!scanner.hasPrecedingLineBreak() && token === 24) { - node.typeArguments = parseBracketedList(17, parseType, 24, 25); + node.typeArguments = parseBracketedList(16, parseType, 24, 25); } return finishNode(node); } function parseTypeQuery() { - var node = createNode(145); + var node = createNode(147); parseExpected(97); node.exprName = parseEntityName(true); return finishNode(node); } function parseTypeParameter() { - var node = createNode(129); + var node = createNode(130); node.name = parseIdentifier(); if (parseOptional(79)) { if (isStartOfType() || !isStartOfExpression()) { @@ -5934,7 +6382,7 @@ var ts; } function parseTypeParameters() { if (token === 24) { - return parseBracketedList(16, parseTypeParameter, 24, 25); + return parseBracketedList(15, parseTypeParameter, 24, 25); } } function parseParameterType() { @@ -5955,7 +6403,7 @@ var ts; } } function parseParameter() { - var node = createNode(130); + var node = createNode(131); node.decorators = parseDecorators(); setModifiers(node, parseModifiers()); node.dotDotDotToken = parseOptionalToken(21); @@ -5989,7 +6437,7 @@ var ts; var savedGeneratorParameterContext = inGeneratorParameterContext(); setYieldContext(yieldAndGeneratorParameterContext); setGeneratorParameterContext(yieldAndGeneratorParameterContext); - var result = parseDelimitedList(15, parseParameter); + var result = parseDelimitedList(14, parseParameter); setYieldContext(savedYieldContext); setGeneratorParameterContext(savedGeneratorParameterContext); if (!parseExpected(17) && requireCompleteParameterList) { @@ -6007,7 +6455,7 @@ var ts; } function parseSignatureMember(kind) { var node = createNode(kind); - if (kind === 140) { + if (kind === 141) { parseExpected(88); } fillSignature(51, false, false, node); @@ -6047,10 +6495,10 @@ var ts; return token === 51 || token === 23 || token === 19; } function parseIndexSignatureDeclaration(fullStart, decorators, modifiers) { - var node = createNode(141, fullStart); + var node = createNode(142, fullStart); node.decorators = decorators; setModifiers(node, modifiers); - node.parameters = parseBracketedList(15, parseParameter, 18, 19); + node.parameters = parseBracketedList(14, parseParameter, 18, 19); node.type = parseTypeAnnotation(); parseTypeMemberSemicolon(); return finishNode(node); @@ -6060,7 +6508,7 @@ var ts; var name = parsePropertyName(); var questionToken = parseOptionalToken(50); if (token === 16 || token === 24) { - var method = createNode(134, fullStart); + var method = createNode(135, fullStart); method.name = name; method.questionToken = questionToken; fillSignature(51, false, false, method); @@ -6068,7 +6516,7 @@ var ts; return finishNode(method); } else { - var property = createNode(132, fullStart); + var property = createNode(133, fullStart); property.name = name; property.questionToken = questionToken; property.type = parseTypeAnnotation(); @@ -6110,14 +6558,14 @@ var ts; switch (token) { case 16: case 24: - return parseSignatureMember(139); + return parseSignatureMember(140); case 18: return isIndexSignature() ? parseIndexSignatureDeclaration(scanner.getStartPos(), undefined, undefined) : parsePropertyOrMethodSignature(); case 88: if (lookAhead(isStartOfConstructSignature)) { - return parseSignatureMember(140); + return parseSignatureMember(141); } case 8: case 7: @@ -6147,14 +6595,14 @@ var ts; return token === 16 || token === 24; } function parseTypeLiteral() { - var node = createNode(146); + var node = createNode(148); node.members = parseObjectTypeMembers(); return finishNode(node); } function parseObjectTypeMembers() { var members; if (parseExpected(14)) { - members = parseList(5, false, parseTypeMember); + members = parseList(4, parseTypeMember); parseExpected(15); } else { @@ -6163,12 +6611,12 @@ var ts; return members; } function parseTupleType() { - var node = createNode(148); - node.elementTypes = parseBracketedList(18, parseType, 18, 19); + var node = createNode(150); + node.elementTypes = parseBracketedList(17, parseType, 18, 19); return finishNode(node); } function parseParenthesizedType() { - var node = createNode(150); + var node = createNode(152); parseExpected(16); node.type = parseType(); parseExpected(17); @@ -6176,7 +6624,7 @@ var ts; } function parseFunctionOrConstructorType(kind) { var node = createNode(kind); - if (kind === 144) { + if (kind === 146) { parseExpected(88); } fillSignature(32, false, false, node); @@ -6189,12 +6637,12 @@ var ts; function parseNonArrayType() { switch (token) { case 112: - case 122: - case 120: - case 113: case 123: + case 121: + case 113: + case 124: var node = tryParse(parseKeywordAndNoDot); - return node || parseTypeReference(); + return node || parseTypeReferenceOrTypePredicate(); case 99: return parseTokenNode(); case 97: @@ -6206,16 +6654,16 @@ var ts; case 16: return parseParenthesizedType(); default: - return parseTypeReference(); + return parseTypeReferenceOrTypePredicate(); } } function isStartOfType() { switch (token) { case 112: - case 122: - case 120: - case 113: case 123: + case 121: + case 113: + case 124: case 99: case 97: case 14: @@ -6237,7 +6685,7 @@ var ts; var type = parseNonArrayType(); while (!scanner.hasPrecedingLineBreak() && parseOptional(18)) { parseExpected(19); - var node = createNode(147, type.pos); + var node = createNode(149, type.pos); node.elementType = type; type = finishNode(node); } @@ -6252,7 +6700,7 @@ var ts; types.push(parseArrayTypeOrHigher()); } types.end = getNodeEnd(); - var node = createNode(149, type.pos); + var node = createNode(151, type.pos); node.types = types; type = finishNode(node); } @@ -6297,10 +6745,10 @@ var ts; } function parseTypeWorker() { if (isStartOfFunctionType()) { - return parseFunctionOrConstructorType(143); + return parseFunctionOrConstructorType(145); } if (token === 88) { - return parseFunctionOrConstructorType(144); + return parseFunctionOrConstructorType(146); } return parseUnionTypeOrHigher(); } @@ -6421,10 +6869,7 @@ var ts; if (inYieldContext()) { return true; } - if (inStrictModeContext()) { - return true; - } - return lookAhead(nextTokenIsIdentifierOnSameLine); + return lookAhead(nextTokenIsIdentifierOrKeywordOrNumberOnSameLine); } return false; } @@ -6432,13 +6877,8 @@ var ts; nextToken(); return !scanner.hasPrecedingLineBreak() && isIdentifier(); } - function nextTokenIsIdentifierOrStartOfDestructuringOnTheSameLine() { - nextToken(); - return !scanner.hasPrecedingLineBreak() && - (isIdentifier() || token === 14 || token === 18); - } function parseYieldExpression() { - var node = createNode(173); + var node = createNode(175); nextToken(); if (!scanner.hasPrecedingLineBreak() && (token === 35 || isStartOfExpression())) { @@ -6452,8 +6892,8 @@ var ts; } function parseSimpleArrowFunctionExpression(identifier) { ts.Debug.assert(token === 32, "parseSimpleArrowFunctionExpression should only have been called if we had a =>"); - var node = createNode(164, identifier.pos); - var parameter = createNode(130, identifier.pos); + var node = createNode(166, identifier.pos); + var parameter = createNode(131, identifier.pos); parameter.name = identifier; finishNode(parameter); node.parameters = [parameter]; @@ -6531,7 +6971,7 @@ var ts; return parseParenthesizedArrowFunctionExpressionHead(false); } function parseParenthesizedArrowFunctionExpressionHead(allowAmbiguity) { - var node = createNode(164); + var node = createNode(166); fillSignature(51, false, !allowAmbiguity, node); if (!node.parameters) { return undefined; @@ -6545,10 +6985,11 @@ var ts; if (token === 14) { return parseFunctionBlock(false, false); } - if (isStartOfStatement(true) && - !isStartOfExpressionStatement() && + if (token !== 22 && token !== 83 && - token !== 69) { + token !== 69 && + isStartOfStatement() && + !isStartOfExpressionStatement()) { return parseFunctionBlock(false, true); } return parseAssignmentExpressionOrHigher(); @@ -6558,7 +6999,7 @@ var ts; if (!questionToken) { return leftOperand; } - var node = createNode(171, leftOperand.pos); + var node = createNode(173, leftOperand.pos); node.condition = leftOperand; node.questionToken = questionToken; node.whenTrue = doOutsideOfContext(disallowInAndDecoratorContext, parseAssignmentExpressionOrHigher); @@ -6571,7 +7012,7 @@ var ts; return parseBinaryExpressionRest(precedence, leftOperand); } function isInOrOfKeyword(t) { - return t === 86 || t === 126; + return t === 86 || t === 127; } function parseBinaryExpressionRest(precedence, leftOperand) { while (true) { @@ -6632,33 +7073,33 @@ var ts; return -1; } function makeBinaryExpression(left, operatorToken, right) { - var node = createNode(170, left.pos); + var node = createNode(172, left.pos); node.left = left; node.operatorToken = operatorToken; node.right = right; return finishNode(node); } function parsePrefixUnaryExpression() { - var node = createNode(168); + var node = createNode(170); node.operator = token; nextToken(); node.operand = parseUnaryExpressionOrHigher(); return finishNode(node); } function parseDeleteExpression() { - var node = createNode(165); + var node = createNode(167); nextToken(); node.expression = parseUnaryExpressionOrHigher(); return finishNode(node); } function parseTypeOfExpression() { - var node = createNode(166); + var node = createNode(168); nextToken(); node.expression = parseUnaryExpressionOrHigher(); return finishNode(node); } function parseVoidExpression() { - var node = createNode(167); + var node = createNode(169); nextToken(); node.expression = parseUnaryExpressionOrHigher(); return finishNode(node); @@ -6688,7 +7129,7 @@ var ts; var expression = parseLeftHandSideExpressionOrHigher(); ts.Debug.assert(ts.isLeftHandSideExpression(expression)); if ((token === 38 || token === 39) && !scanner.hasPrecedingLineBreak()) { - var node = createNode(169, expression.pos); + var node = createNode(171, expression.pos); node.operand = expression; node.operator = token; nextToken(); @@ -6711,14 +7152,14 @@ var ts; if (token === 16 || token === 20) { return expression; } - var node = createNode(156, expression.pos); + var node = createNode(158, expression.pos); node.expression = expression; node.dotToken = parseExpectedToken(20, false, ts.Diagnostics.super_must_be_followed_by_an_argument_list_or_member_access); node.name = parseRightSideOfDot(true); return finishNode(node); } function parseTypeAssertion() { - var node = createNode(161); + var node = createNode(163); parseExpected(24); node.type = parseType(); parseExpected(25); @@ -6729,7 +7170,7 @@ var ts; while (true) { var dotToken = parseOptionalToken(20); if (dotToken) { - var propertyAccess = createNode(156, expression.pos); + var propertyAccess = createNode(158, expression.pos); propertyAccess.expression = expression; propertyAccess.dotToken = dotToken; propertyAccess.name = parseRightSideOfDot(true); @@ -6737,7 +7178,7 @@ var ts; continue; } if (!inDecoratorContext() && parseOptional(18)) { - var indexedAccess = createNode(157, expression.pos); + var indexedAccess = createNode(159, expression.pos); indexedAccess.expression = expression; if (token !== 19) { indexedAccess.argumentExpression = allowInAnd(parseExpression); @@ -6751,7 +7192,7 @@ var ts; continue; } if (token === 10 || token === 11) { - var tagExpression = createNode(160, expression.pos); + var tagExpression = createNode(162, expression.pos); tagExpression.tag = expression; tagExpression.template = token === 10 ? parseLiteralNode() @@ -6770,7 +7211,7 @@ var ts; if (!typeArguments) { return expression; } - var callExpr = createNode(158, expression.pos); + var callExpr = createNode(160, expression.pos); callExpr.expression = expression; callExpr.typeArguments = typeArguments; callExpr.arguments = parseArgumentList(); @@ -6778,7 +7219,7 @@ var ts; continue; } else if (token === 16) { - var callExpr = createNode(158, expression.pos); + var callExpr = createNode(160, expression.pos); callExpr.expression = expression; callExpr.arguments = parseArgumentList(); expression = finishNode(callExpr); @@ -6789,7 +7230,7 @@ var ts; } function parseArgumentList() { parseExpected(16); - var result = parseDelimitedList(12, parseArgumentExpression); + var result = parseDelimitedList(11, parseArgumentExpression); parseExpected(17); return result; } @@ -6797,7 +7238,7 @@ var ts; if (!parseOptional(24)) { return undefined; } - var typeArguments = parseDelimitedList(17, parseType); + var typeArguments = parseDelimitedList(16, parseType); if (!parseExpected(25)) { return undefined; } @@ -6868,42 +7309,42 @@ var ts; return parseIdentifier(ts.Diagnostics.Expression_expected); } function parseParenthesizedExpression() { - var node = createNode(162); + var node = createNode(164); parseExpected(16); node.expression = allowInAnd(parseExpression); parseExpected(17); return finishNode(node); } function parseSpreadElement() { - var node = createNode(174); + var node = createNode(176); parseExpected(21); node.expression = parseAssignmentExpressionOrHigher(); return finishNode(node); } function parseArgumentOrArrayLiteralElement() { return token === 21 ? parseSpreadElement() : - token === 23 ? createNode(176) : + token === 23 ? createNode(178) : parseAssignmentExpressionOrHigher(); } function parseArgumentExpression() { return doOutsideOfContext(disallowInAndDecoratorContext, parseArgumentOrArrayLiteralElement); } function parseArrayLiteralExpression() { - var node = createNode(154); + var node = createNode(156); parseExpected(18); if (scanner.hasPrecedingLineBreak()) node.flags |= 512; - node.elements = parseDelimitedList(14, parseArgumentOrArrayLiteralElement); + node.elements = parseDelimitedList(13, parseArgumentOrArrayLiteralElement); parseExpected(19); return finishNode(node); } function tryParseAccessorDeclaration(fullStart, decorators, modifiers) { if (parseContextualModifier(116)) { - return parseAccessorDeclaration(137, fullStart, decorators, modifiers); - } - else if (parseContextualModifier(121)) { return parseAccessorDeclaration(138, fullStart, decorators, modifiers); } + else if (parseContextualModifier(122)) { + return parseAccessorDeclaration(139, fullStart, decorators, modifiers); + } return undefined; } function parseObjectLiteralElement() { @@ -6923,13 +7364,13 @@ var ts; return parseMethodDeclaration(fullStart, decorators, modifiers, asteriskToken, propertyName, questionToken); } if ((token === 23 || token === 15) && tokenIsIdentifier) { - var shorthandDeclaration = createNode(226, fullStart); + var shorthandDeclaration = createNode(228, fullStart); shorthandDeclaration.name = propertyName; shorthandDeclaration.questionToken = questionToken; return finishNode(shorthandDeclaration); } else { - var propertyAssignment = createNode(225, fullStart); + var propertyAssignment = createNode(227, fullStart); propertyAssignment.name = propertyName; propertyAssignment.questionToken = questionToken; parseExpected(51); @@ -6938,12 +7379,12 @@ var ts; } } function parseObjectLiteralExpression() { - var node = createNode(155); + var node = createNode(157); parseExpected(14); if (scanner.hasPrecedingLineBreak()) { node.flags |= 512; } - node.properties = parseDelimitedList(13, parseObjectLiteralElement, true); + node.properties = parseDelimitedList(12, parseObjectLiteralElement, true); parseExpected(15); return finishNode(node); } @@ -6952,7 +7393,7 @@ var ts; if (saveDecoratorContext) { setDecoratorContext(false); } - var node = createNode(163); + var node = createNode(165); parseExpected(83); node.asteriskToken = parseOptionalToken(35); node.name = node.asteriskToken ? doInYieldContext(parseOptionalIdentifier) : parseOptionalIdentifier(); @@ -6967,7 +7408,7 @@ var ts; return isIdentifier() ? parseIdentifier() : undefined; } function parseNewExpression() { - var node = createNode(159); + var node = createNode(161); parseExpected(88); node.expression = parseMemberExpressionOrHigher(); node.typeArguments = tryParse(parseTypeArgumentsInExpression); @@ -6976,10 +7417,10 @@ var ts; } return finishNode(node); } - function parseBlock(ignoreMissingOpenBrace, checkForStrictMode, diagnosticMessage) { - var node = createNode(180); + function parseBlock(ignoreMissingOpenBrace, diagnosticMessage) { + var node = createNode(182); if (parseExpected(14, diagnosticMessage) || ignoreMissingOpenBrace) { - node.statements = parseList(2, checkForStrictMode, parseStatement); + node.statements = parseList(1, parseStatement); parseExpected(15); } else { @@ -6994,7 +7435,7 @@ var ts; if (saveDecoratorContext) { setDecoratorContext(false); } - var block = parseBlock(ignoreMissingOpenBrace, true, diagnosticMessage); + var block = parseBlock(ignoreMissingOpenBrace, diagnosticMessage); if (saveDecoratorContext) { setDecoratorContext(true); } @@ -7002,12 +7443,12 @@ var ts; return block; } function parseEmptyStatement() { - var node = createNode(182); + var node = createNode(184); parseExpected(22); return finishNode(node); } function parseIfStatement() { - var node = createNode(184); + var node = createNode(186); parseExpected(84); parseExpected(16); node.expression = allowInAnd(parseExpression); @@ -7017,7 +7458,7 @@ var ts; return finishNode(node); } function parseDoStatement() { - var node = createNode(185); + var node = createNode(187); parseExpected(75); node.statement = parseStatement(); parseExpected(100); @@ -7028,7 +7469,7 @@ var ts; return finishNode(node); } function parseWhileStatement() { - var node = createNode(186); + var node = createNode(188); parseExpected(100); parseExpected(16); node.expression = allowInAnd(parseExpression); @@ -7051,21 +7492,21 @@ var ts; } var forOrForInOrForOfStatement; if (parseOptional(86)) { - var forInStatement = createNode(188, pos); + var forInStatement = createNode(190, pos); forInStatement.initializer = initializer; forInStatement.expression = allowInAnd(parseExpression); parseExpected(17); forOrForInOrForOfStatement = forInStatement; } - else if (parseOptional(126)) { - var forOfStatement = createNode(189, pos); + else if (parseOptional(127)) { + var forOfStatement = createNode(191, pos); forOfStatement.initializer = initializer; forOfStatement.expression = allowInAnd(parseAssignmentExpressionOrHigher); parseExpected(17); forOrForInOrForOfStatement = forOfStatement; } else { - var forStatement = createNode(187, pos); + var forStatement = createNode(189, pos); forStatement.initializer = initializer; parseExpected(22); if (token !== 22 && token !== 17) { @@ -7083,7 +7524,7 @@ var ts; } function parseBreakOrContinueStatement(kind) { var node = createNode(kind); - parseExpected(kind === 191 ? 66 : 71); + parseExpected(kind === 193 ? 66 : 71); if (!canParseSemicolon()) { node.label = parseIdentifier(); } @@ -7091,7 +7532,7 @@ var ts; return finishNode(node); } function parseReturnStatement() { - var node = createNode(192); + var node = createNode(194); parseExpected(90); if (!canParseSemicolon()) { node.expression = allowInAnd(parseExpression); @@ -7100,7 +7541,7 @@ var ts; return finishNode(node); } function parseWithStatement() { - var node = createNode(193); + var node = createNode(195); parseExpected(101); parseExpected(16); node.expression = allowInAnd(parseExpression); @@ -7109,32 +7550,32 @@ var ts; return finishNode(node); } function parseCaseClause() { - var node = createNode(221); + var node = createNode(223); parseExpected(67); node.expression = allowInAnd(parseExpression); parseExpected(51); - node.statements = parseList(4, false, parseStatement); + node.statements = parseList(3, parseStatement); return finishNode(node); } function parseDefaultClause() { - var node = createNode(222); + var node = createNode(224); parseExpected(73); parseExpected(51); - node.statements = parseList(4, false, parseStatement); + node.statements = parseList(3, parseStatement); return finishNode(node); } function parseCaseOrDefaultClause() { return token === 67 ? parseCaseClause() : parseDefaultClause(); } function parseSwitchStatement() { - var node = createNode(194); + var node = createNode(196); parseExpected(92); parseExpected(16); node.expression = allowInAnd(parseExpression); parseExpected(17); - var caseBlock = createNode(208, scanner.getStartPos()); + var caseBlock = createNode(210, scanner.getStartPos()); parseExpected(14); - caseBlock.clauses = parseList(3, false, parseCaseOrDefaultClause); + caseBlock.clauses = parseList(2, parseCaseOrDefaultClause); parseExpected(15); node.caseBlock = finishNode(caseBlock); return finishNode(node); @@ -7142,35 +7583,35 @@ var ts; function parseThrowStatement() { // ThrowStatement[Yield] : // throw [no LineTerminator here]Expression[In, ?Yield]; - var node = createNode(196); + var node = createNode(198); parseExpected(94); node.expression = scanner.hasPrecedingLineBreak() ? undefined : allowInAnd(parseExpression); parseSemicolon(); return finishNode(node); } function parseTryStatement() { - var node = createNode(197); + var node = createNode(199); parseExpected(96); - node.tryBlock = parseBlock(false, false); + node.tryBlock = parseBlock(false); node.catchClause = token === 68 ? parseCatchClause() : undefined; if (!node.catchClause || token === 81) { parseExpected(81); - node.finallyBlock = parseBlock(false, false); + node.finallyBlock = parseBlock(false); } return finishNode(node); } function parseCatchClause() { - var result = createNode(224); + var result = createNode(226); parseExpected(68); if (parseExpected(16)) { result.variableDeclaration = parseVariableDeclaration(); } parseExpected(17); - result.block = parseBlock(false, false); + result.block = parseBlock(false); return finishNode(result); } function parseDebuggerStatement() { - var node = createNode(198); + var node = createNode(200); parseExpected(72); parseSemicolon(); return finishNode(node); @@ -7179,33 +7620,86 @@ var ts; var fullStart = scanner.getStartPos(); var expression = allowInAnd(parseExpression); if (expression.kind === 65 && parseOptional(51)) { - var labeledStatement = createNode(195, fullStart); + var labeledStatement = createNode(197, fullStart); labeledStatement.label = expression; labeledStatement.statement = parseStatement(); return finishNode(labeledStatement); } else { - var expressionStatement = createNode(183, fullStart); + var expressionStatement = createNode(185, fullStart); expressionStatement.expression = expression; parseSemicolon(); return finishNode(expressionStatement); } } - function isStartOfStatement(inErrorRecovery) { - if (ts.isModifier(token)) { - var result = lookAhead(parseVariableStatementOrFunctionDeclarationOrClassDeclarationWithDecoratorsOrModifiers); - if (result) { - return true; + function isIdentifierOrKeyword() { + return token >= 65; + } + function nextTokenIsIdentifierOrKeywordOnSameLine() { + nextToken(); + return isIdentifierOrKeyword() && !scanner.hasPrecedingLineBreak(); + } + function nextTokenIsIdentifierOrKeywordOrNumberOnSameLine() { + nextToken(); + return (isIdentifierOrKeyword() || token === 7) && !scanner.hasPrecedingLineBreak(); + } + function isDeclaration() { + while (true) { + switch (token) { + case 98: + case 104: + case 70: + case 83: + case 69: + case 77: + return true; + case 103: + case 125: + return nextTokenIsIdentifierOnSameLine(); + case 118: + case 119: + return nextTokenIsIdentifierOrStringLiteralOnSameLine(); + case 115: + nextToken(); + if (scanner.hasPrecedingLineBreak()) { + return false; + } + continue; + case 85: + nextToken(); + return token === 8 || token === 35 || + token === 14 || isIdentifierOrKeyword(); + case 78: + nextToken(); + if (token === 53 || token === 35 || + token === 14 || token === 73) { + return true; + } + continue; + case 108: + case 106: + case 107: + case 109: + nextToken(); + continue; + default: + return false; } } + } + function isStartOfDeclaration() { + return lookAhead(isDeclaration); + } + function isStartOfStatement() { switch (token) { + case 52: case 22: - return !inErrorRecovery; case 14: case 98: case 104: case 83: case 69: + case 77: case 84: case 75: case 100: @@ -7222,48 +7716,48 @@ var ts; case 81: return true; case 70: - var isConstEnum = lookAhead(nextTokenIsEnumKeyword); - return !isConstEnum; + case 78: + case 85: + return isStartOfDeclaration(); + case 115: case 103: - case 117: case 118: - case 77: - case 124: - if (isDeclarationStart()) { - return false; - } + case 119: + case 125: + return true; case 108: case 106: case 107: case 109: - if (lookAhead(nextTokenIsIdentifierOrKeywordOnSameLine)) { - return false; - } + return isStartOfDeclaration() || !lookAhead(nextTokenIsIdentifierOrKeywordOnSameLine); default: return isStartOfExpression(); } } - function nextTokenIsEnumKeyword() { + function nextTokenIsIdentifierOrStartOfDestructuring() { nextToken(); - return token === 77; + return isIdentifier() || token === 14 || token === 18; } - function nextTokenIsIdentifierOrKeywordOnSameLine() { - nextToken(); - return isIdentifierOrKeyword() && !scanner.hasPrecedingLineBreak(); + function isLetDeclaration() { + return lookAhead(nextTokenIsIdentifierOrStartOfDestructuring); } function parseStatement() { switch (token) { + case 22: + return parseEmptyStatement(); case 14: - return parseBlock(false, false); + return parseBlock(false); case 98: - case 70: return parseVariableStatement(scanner.getStartPos(), undefined, undefined); + case 104: + if (isLetDeclaration()) { + return parseVariableStatement(scanner.getStartPos(), undefined, undefined); + } + break; case 83: return parseFunctionDeclaration(scanner.getStartPos(), undefined, undefined); case 69: return parseClassDeclaration(scanner.getStartPos(), undefined, undefined); - case 22: - return parseEmptyStatement(); case 84: return parseIfStatement(); case 75: @@ -7273,9 +7767,9 @@ var ts; case 82: return parseForOrForInOrForOfStatement(); case 71: - return parseBreakOrContinueStatement(190); + return parseBreakOrContinueStatement(192); case 66: - return parseBreakOrContinueStatement(191); + return parseBreakOrContinueStatement(193); case 90: return parseReturnStatement(); case 101: @@ -7290,44 +7784,70 @@ var ts; return parseTryStatement(); case 72: return parseDebuggerStatement(); - case 104: - if (isLetDeclaration()) { - return parseVariableStatement(scanner.getStartPos(), undefined, undefined); + case 52: + return parseDeclaration(); + case 103: + case 125: + case 118: + case 119: + case 115: + case 70: + case 77: + case 78: + case 85: + case 106: + case 107: + case 108: + case 109: + if (isStartOfDeclaration()) { + return parseDeclaration(); } - default: - if (ts.isModifier(token) || token === 52) { - var result = tryParse(parseVariableStatementOrFunctionDeclarationOrClassDeclarationWithDecoratorsOrModifiers); - if (result) { - return result; - } - } - return parseExpressionOrLabeledStatement(); + break; } + return parseExpressionOrLabeledStatement(); } - function parseVariableStatementOrFunctionDeclarationOrClassDeclarationWithDecoratorsOrModifiers() { - var start = scanner.getStartPos(); + function parseDeclaration() { + var fullStart = getNodePos(); var decorators = parseDecorators(); var modifiers = parseModifiers(); switch (token) { - case 70: - var nextTokenIsEnum = lookAhead(nextTokenIsEnumKeyword); - if (nextTokenIsEnum) { - return undefined; - } - return parseVariableStatement(start, decorators, modifiers); - case 104: - if (!isLetDeclaration()) { - return undefined; - } - return parseVariableStatement(start, decorators, modifiers); case 98: - return parseVariableStatement(start, decorators, modifiers); + case 104: + case 70: + return parseVariableStatement(fullStart, decorators, modifiers); case 83: - return parseFunctionDeclaration(start, decorators, modifiers); + return parseFunctionDeclaration(fullStart, decorators, modifiers); case 69: - return parseClassDeclaration(start, decorators, modifiers); + return parseClassDeclaration(fullStart, decorators, modifiers); + case 103: + return parseInterfaceDeclaration(fullStart, decorators, modifiers); + case 125: + return parseTypeAliasDeclaration(fullStart, decorators, modifiers); + case 77: + return parseEnumDeclaration(fullStart, decorators, modifiers); + case 118: + case 119: + return parseModuleDeclaration(fullStart, decorators, modifiers); + case 85: + return parseImportDeclarationOrImportEqualsDeclaration(fullStart, decorators, modifiers); + case 78: + nextToken(); + return token === 73 || token === 53 ? + parseExportAssignment(fullStart, decorators, modifiers) : + parseExportDeclaration(fullStart, decorators, modifiers); + default: + if (decorators || modifiers) { + var node = createMissingNode(221, true, ts.Diagnostics.Declaration_expected); + node.pos = fullStart; + node.decorators = decorators; + setModifiers(node, modifiers); + return finishNode(node); + } } - return undefined; + } + function nextTokenIsIdentifierOrStringLiteralOnSameLine() { + nextToken(); + return !scanner.hasPrecedingLineBreak() && (isIdentifier() || token === 8); } function parseFunctionBlockOrSemicolon(isGenerator, diagnosticMessage) { if (token !== 14 && canParseSemicolon()) { @@ -7338,16 +7858,16 @@ var ts; } function parseArrayBindingElement() { if (token === 23) { - return createNode(176); + return createNode(178); } - var node = createNode(153); + var node = createNode(155); node.dotDotDotToken = parseOptionalToken(21); node.name = parseIdentifierOrPattern(); node.initializer = parseInitializer(false); return finishNode(node); } function parseObjectBindingElement() { - var node = createNode(153); + var node = createNode(155); var tokenIsIdentifier = isIdentifier(); var propertyName = parsePropertyName(); if (tokenIsIdentifier && token !== 51) { @@ -7362,16 +7882,16 @@ var ts; return finishNode(node); } function parseObjectBindingPattern() { - var node = createNode(151); + var node = createNode(153); parseExpected(14); - node.elements = parseDelimitedList(10, parseObjectBindingElement); + node.elements = parseDelimitedList(9, parseObjectBindingElement); parseExpected(15); return finishNode(node); } function parseArrayBindingPattern() { - var node = createNode(152); + var node = createNode(154); parseExpected(18); - node.elements = parseDelimitedList(11, parseArrayBindingElement); + node.elements = parseDelimitedList(10, parseArrayBindingElement); parseExpected(19); return finishNode(node); } @@ -7388,7 +7908,7 @@ var ts; return parseIdentifier(); } function parseVariableDeclaration() { - var node = createNode(199); + var node = createNode(201); node.name = parseIdentifierOrPattern(); node.type = parseTypeAnnotation(); if (!isInOrOfKeyword(token)) { @@ -7397,7 +7917,7 @@ var ts; return finishNode(node); } function parseVariableDeclarationList(inForStatementInitializer) { - var node = createNode(200); + var node = createNode(202); switch (token) { case 98: break; @@ -7411,13 +7931,13 @@ var ts; ts.Debug.fail(); } nextToken(); - if (token === 126 && lookAhead(canFollowContextualOfKeyword)) { + if (token === 127 && lookAhead(canFollowContextualOfKeyword)) { node.declarations = createMissingList(); } else { var savedDisallowIn = inDisallowInContext(); setDisallowInContext(inForStatementInitializer); - node.declarations = parseDelimitedList(9, parseVariableDeclaration); + node.declarations = parseDelimitedList(8, parseVariableDeclaration); setDisallowInContext(savedDisallowIn); } return finishNode(node); @@ -7426,7 +7946,7 @@ var ts; return nextTokenIsIdentifier() && nextToken() === 17; } function parseVariableStatement(fullStart, decorators, modifiers) { - var node = createNode(181, fullStart); + var node = createNode(183, fullStart); node.decorators = decorators; setModifiers(node, modifiers); node.declarationList = parseVariableDeclarationList(false); @@ -7434,7 +7954,7 @@ var ts; return finishNode(node); } function parseFunctionDeclaration(fullStart, decorators, modifiers) { - var node = createNode(201, fullStart); + var node = createNode(203, fullStart); node.decorators = decorators; setModifiers(node, modifiers); parseExpected(83); @@ -7445,7 +7965,7 @@ var ts; return finishNode(node); } function parseConstructorDeclaration(pos, decorators, modifiers) { - var node = createNode(136, pos); + var node = createNode(137, pos); node.decorators = decorators; setModifiers(node, modifiers); parseExpected(114); @@ -7454,7 +7974,7 @@ var ts; return finishNode(node); } function parseMethodDeclaration(fullStart, decorators, modifiers, asteriskToken, name, questionToken, diagnosticMessage) { - var method = createNode(135, fullStart); + var method = createNode(136, fullStart); method.decorators = decorators; setModifiers(method, modifiers); method.asteriskToken = asteriskToken; @@ -7465,13 +7985,15 @@ var ts; return finishNode(method); } function parsePropertyDeclaration(fullStart, decorators, modifiers, name, questionToken) { - var property = createNode(133, fullStart); + var property = createNode(134, fullStart); property.decorators = decorators; setModifiers(property, modifiers); property.name = name; property.questionToken = questionToken; property.type = parseTypeAnnotation(); - property.initializer = allowInAnd(parseNonParameterInitializer); + property.initializer = modifiers && modifiers.flags & 128 + ? allowInAnd(parseNonParameterInitializer) + : doOutsideOfContext(4 | 2, parseNonParameterInitializer); parseSemicolon(); return finishNode(property); } @@ -7532,7 +8054,7 @@ var ts; return true; } if (idToken !== undefined) { - if (!ts.isKeyword(idToken) || idToken === 121 || idToken === 116) { + if (!ts.isKeyword(idToken) || idToken === 122 || idToken === 116) { return true; } switch (token) { @@ -7559,7 +8081,7 @@ var ts; decorators = []; decorators.pos = scanner.getStartPos(); } - var decorator = createNode(131, decoratorStart); + var decorator = createNode(132, decoratorStart); decorator.expression = doInDecoratorContext(parseLeftHandSideExpressionOrHigher); decorators.push(finishNode(decorator)); } @@ -7592,7 +8114,7 @@ var ts; } function parseClassElement() { if (token === 22) { - var result = createNode(179); + var result = createNode(181); nextToken(); return finishNode(result); } @@ -7616,21 +8138,19 @@ var ts; token === 18) { return parsePropertyOrMethodDeclaration(fullStart, decorators, modifiers); } - if (decorators) { - var name_3 = createMissingNode(65, true, ts.Diagnostics.Declaration_expected); - return parsePropertyDeclaration(fullStart, decorators, modifiers, name_3, undefined); + if (decorators || modifiers) { + var name_6 = createMissingNode(65, true, ts.Diagnostics.Declaration_expected); + return parsePropertyDeclaration(fullStart, decorators, modifiers, name_6, undefined); } ts.Debug.fail("Should not have attempted to parse class member declaration."); } function parseClassExpression() { - return parseClassDeclarationOrExpression(scanner.getStartPos(), undefined, undefined, 175); + return parseClassDeclarationOrExpression(scanner.getStartPos(), undefined, undefined, 177); } function parseClassDeclaration(fullStart, decorators, modifiers) { - return parseClassDeclarationOrExpression(fullStart, decorators, modifiers, 202); + return parseClassDeclarationOrExpression(fullStart, decorators, modifiers, 204); } function parseClassDeclarationOrExpression(fullStart, decorators, modifiers, kind) { - var savedStrictModeContext = inStrictModeContext(); - setStrictModeContext(true); var node = createNode(kind, fullStart); node.decorators = decorators; setModifiers(node, modifiers); @@ -7647,9 +8167,7 @@ var ts; else { node.members = createMissingList(); } - var finishedNode = finishNode(node); - setStrictModeContext(savedStrictModeContext); - return finishedNode; + return finishNode(node); } function parseHeritageClauses(isClassHeritageClause) { // ClassTail[Yield,GeneratorParameter] : See 14.5 @@ -7663,23 +8181,23 @@ var ts; return undefined; } function parseHeritageClausesWorker() { - return parseList(19, false, parseHeritageClause); + return parseList(18, parseHeritageClause); } function parseHeritageClause() { if (token === 79 || token === 102) { - var node = createNode(223); + var node = createNode(225); node.token = token; nextToken(); - node.types = parseDelimitedList(8, parseExpressionWithTypeArguments); + node.types = parseDelimitedList(7, parseExpressionWithTypeArguments); return finishNode(node); } return undefined; } function parseExpressionWithTypeArguments() { - var node = createNode(177); + var node = createNode(179); node.expression = parseLeftHandSideExpressionOrHigher(); if (token === 24) { - node.typeArguments = parseBracketedList(17, parseType, 24, 25); + node.typeArguments = parseBracketedList(16, parseType, 24, 25); } return finishNode(node); } @@ -7687,10 +8205,10 @@ var ts; return token === 79 || token === 102; } function parseClassMembers() { - return parseList(6, false, parseClassElement); + return parseList(5, parseClassElement); } function parseInterfaceDeclaration(fullStart, decorators, modifiers) { - var node = createNode(203, fullStart); + var node = createNode(205, fullStart); node.decorators = decorators; setModifiers(node, modifiers); parseExpected(103); @@ -7701,30 +8219,31 @@ var ts; return finishNode(node); } function parseTypeAliasDeclaration(fullStart, decorators, modifiers) { - var node = createNode(204, fullStart); + var node = createNode(206, fullStart); node.decorators = decorators; setModifiers(node, modifiers); - parseExpected(124); + parseExpected(125); node.name = parseIdentifier(); + node.typeParameters = parseTypeParameters(); parseExpected(53); node.type = parseType(); parseSemicolon(); return finishNode(node); } function parseEnumMember() { - var node = createNode(227, scanner.getStartPos()); + var node = createNode(229, scanner.getStartPos()); node.name = parsePropertyName(); node.initializer = allowInAnd(parseNonParameterInitializer); return finishNode(node); } function parseEnumDeclaration(fullStart, decorators, modifiers) { - var node = createNode(205, fullStart); + var node = createNode(207, fullStart); node.decorators = decorators; setModifiers(node, modifiers); parseExpected(77); node.name = parseIdentifier(); if (parseExpected(14)) { - node.members = parseDelimitedList(7, parseEnumMember); + node.members = parseDelimitedList(6, parseEnumMember); parseExpected(15); } else { @@ -7733,9 +8252,9 @@ var ts; return finishNode(node); } function parseModuleBlock() { - var node = createNode(207, scanner.getStartPos()); + var node = createNode(209, scanner.getStartPos()); if (parseExpected(14)) { - node.statements = parseList(1, false, parseModuleElement); + node.statements = parseList(1, parseStatement); parseExpected(15); } else { @@ -7744,7 +8263,7 @@ var ts; return finishNode(node); } function parseModuleOrNamespaceDeclaration(fullStart, decorators, modifiers, flags) { - var node = createNode(206, fullStart); + var node = createNode(208, fullStart); node.decorators = decorators; setModifiers(node, modifiers); node.flags |= flags; @@ -7755,7 +8274,7 @@ var ts; return finishNode(node); } function parseAmbientExternalModuleDeclaration(fullStart, decorators, modifiers) { - var node = createNode(206, fullStart); + var node = createNode(208, fullStart); node.decorators = decorators; setModifiers(node, modifiers); node.name = parseLiteralNode(true); @@ -7764,11 +8283,11 @@ var ts; } function parseModuleDeclaration(fullStart, decorators, modifiers) { var flags = modifiers ? modifiers.flags : 0; - if (parseOptional(118)) { + if (parseOptional(119)) { flags |= 32768; } else { - parseExpected(117); + parseExpected(118); if (token === 8) { return parseAmbientExternalModuleDeclaration(fullStart, decorators, modifiers); } @@ -7776,7 +8295,7 @@ var ts; return parseModuleOrNamespaceDeclaration(fullStart, decorators, modifiers, flags); } function isExternalModuleReference() { - return token === 119 && + return token === 120 && lookAhead(nextTokenIsOpenParen); } function nextTokenIsOpenParen() { @@ -7785,7 +8304,7 @@ var ts; function nextTokenIsCommaOrFromKeyword() { nextToken(); return token === 23 || - token === 125; + token === 126; } function parseImportDeclarationOrImportEqualsDeclaration(fullStart, decorators, modifiers) { parseExpected(85); @@ -7793,8 +8312,8 @@ var ts; var identifier; if (isIdentifier()) { identifier = parseIdentifier(); - if (token !== 23 && token !== 125) { - var importEqualsDeclaration = createNode(209, fullStart); + if (token !== 23 && token !== 126) { + var importEqualsDeclaration = createNode(211, fullStart); importEqualsDeclaration.decorators = decorators; setModifiers(importEqualsDeclaration, modifiers); importEqualsDeclaration.name = identifier; @@ -7804,14 +8323,14 @@ var ts; return finishNode(importEqualsDeclaration); } } - var importDeclaration = createNode(210, fullStart); + var importDeclaration = createNode(212, fullStart); importDeclaration.decorators = decorators; setModifiers(importDeclaration, modifiers); if (identifier || token === 35 || token === 14) { importDeclaration.importClause = parseImportClause(identifier, afterImportPos); - parseExpected(125); + parseExpected(126); } importDeclaration.moduleSpecifier = parseModuleSpecifier(); parseSemicolon(); @@ -7824,13 +8343,13 @@ var ts; // NamedImports // ImportedDefaultBinding, NameSpaceImport // ImportedDefaultBinding, NamedImports - var importClause = createNode(211, fullStart); + var importClause = createNode(213, fullStart); if (identifier) { importClause.name = identifier; } if (!importClause.name || parseOptional(23)) { - importClause.namedBindings = token === 35 ? parseNamespaceImport() : parseNamedImportsOrExports(213); + importClause.namedBindings = token === 35 ? parseNamespaceImport() : parseNamedImportsOrExports(215); } return finishNode(importClause); } @@ -7840,8 +8359,8 @@ var ts; : parseEntityName(false); } function parseExternalModuleReference() { - var node = createNode(220); - parseExpected(119); + var node = createNode(222); + parseExpected(120); parseExpected(16); node.expression = parseModuleSpecifier(); parseExpected(17); @@ -7855,7 +8374,7 @@ var ts; return result; } function parseNamespaceImport() { - var namespaceImport = createNode(212); + var namespaceImport = createNode(214); parseExpected(35); parseExpected(111); namespaceImport.name = parseIdentifier(); @@ -7863,14 +8382,14 @@ var ts; } function parseNamedImportsOrExports(kind) { var node = createNode(kind); - node.elements = parseBracketedList(20, kind === 213 ? parseImportSpecifier : parseExportSpecifier, 14, 15); + node.elements = parseBracketedList(19, kind === 215 ? parseImportSpecifier : parseExportSpecifier, 14, 15); return finishNode(node); } function parseExportSpecifier() { - return parseImportOrExportSpecifier(218); + return parseImportOrExportSpecifier(220); } function parseImportSpecifier() { - return parseImportOrExportSpecifier(214); + return parseImportOrExportSpecifier(216); } function parseImportOrExportSpecifier(kind) { var node = createNode(kind); @@ -7889,22 +8408,22 @@ var ts; else { node.name = identifierName; } - if (kind === 214 && checkIdentifierIsKeyword) { + if (kind === 216 && checkIdentifierIsKeyword) { parseErrorAtPosition(checkIdentifierStart, checkIdentifierEnd - checkIdentifierStart, ts.Diagnostics.Identifier_expected); } return finishNode(node); } function parseExportDeclaration(fullStart, decorators, modifiers) { - var node = createNode(216, fullStart); + var node = createNode(218, fullStart); node.decorators = decorators; setModifiers(node, modifiers); if (parseOptional(35)) { - parseExpected(125); + parseExpected(126); node.moduleSpecifier = parseModuleSpecifier(); } else { - node.exportClause = parseNamedImportsOrExports(217); - if (parseOptional(125)) { + node.exportClause = parseNamedImportsOrExports(219); + if (parseOptional(126)) { node.moduleSpecifier = parseModuleSpecifier(); } } @@ -7912,7 +8431,7 @@ var ts; return finishNode(node); } function parseExportAssignment(fullStart, decorators, modifiers) { - var node = createNode(215, fullStart); + var node = createNode(217, fullStart); node.decorators = decorators; setModifiers(node, modifiers); if (parseOptional(53)) { @@ -7925,125 +8444,6 @@ var ts; parseSemicolon(); return finishNode(node); } - function isLetDeclaration() { - return inStrictModeContext() || lookAhead(nextTokenIsIdentifierOrStartOfDestructuringOnTheSameLine); - } - function isDeclarationStart(followsModifier) { - switch (token) { - case 98: - case 70: - case 83: - return true; - case 104: - return isLetDeclaration(); - case 69: - case 103: - case 77: - case 124: - return lookAhead(nextTokenIsIdentifierOrKeyword); - case 85: - return lookAhead(nextTokenCanFollowImportKeyword); - case 117: - case 118: - return lookAhead(nextTokenIsIdentifierOrKeywordOrStringLiteral); - case 78: - return lookAhead(nextTokenCanFollowExportKeyword); - case 115: - case 108: - case 106: - case 107: - case 109: - return lookAhead(nextTokenIsDeclarationStart); - case 52: - return !followsModifier; - } - } - function isIdentifierOrKeyword() { - return token >= 65; - } - function nextTokenIsIdentifierOrKeyword() { - nextToken(); - return isIdentifierOrKeyword(); - } - function nextTokenIsIdentifierOrKeywordOrStringLiteral() { - nextToken(); - return isIdentifierOrKeyword() || token === 8; - } - function nextTokenCanFollowImportKeyword() { - nextToken(); - return isIdentifierOrKeyword() || token === 8 || - token === 35 || token === 14; - } - function nextTokenCanFollowExportKeyword() { - nextToken(); - return token === 53 || token === 35 || - token === 14 || token === 73 || isDeclarationStart(true); - } - function nextTokenIsDeclarationStart() { - nextToken(); - return isDeclarationStart(true); - } - function nextTokenIsAsKeyword() { - return nextToken() === 111; - } - function parseDeclaration() { - var fullStart = getNodePos(); - var decorators = parseDecorators(); - var modifiers = parseModifiers(); - if (token === 78) { - nextToken(); - if (token === 73 || token === 53) { - return parseExportAssignment(fullStart, decorators, modifiers); - } - if (token === 35 || token === 14) { - return parseExportDeclaration(fullStart, decorators, modifiers); - } - } - switch (token) { - case 98: - case 104: - case 70: - return parseVariableStatement(fullStart, decorators, modifiers); - case 83: - return parseFunctionDeclaration(fullStart, decorators, modifiers); - case 69: - return parseClassDeclaration(fullStart, decorators, modifiers); - case 103: - return parseInterfaceDeclaration(fullStart, decorators, modifiers); - case 124: - return parseTypeAliasDeclaration(fullStart, decorators, modifiers); - case 77: - return parseEnumDeclaration(fullStart, decorators, modifiers); - case 117: - case 118: - return parseModuleDeclaration(fullStart, decorators, modifiers); - case 85: - return parseImportDeclarationOrImportEqualsDeclaration(fullStart, decorators, modifiers); - default: - if (decorators) { - var node = createMissingNode(219, true, ts.Diagnostics.Declaration_expected); - node.pos = fullStart; - node.decorators = decorators; - setModifiers(node, modifiers); - return finishNode(node); - } - ts.Debug.fail("Mismatch between isDeclarationStart and parseDeclaration"); - } - } - function isSourceElement(inErrorRecovery) { - return isDeclarationStart() || isStartOfStatement(inErrorRecovery); - } - function parseSourceElement() { - return parseSourceElementOrModuleElement(); - } - function parseModuleElement() { - return parseSourceElementOrModuleElement(); - } - function parseSourceElementOrModuleElement() { - return isDeclarationStart() - ? parseDeclaration() - : parseStatement(); - } function processReferenceComments(sourceFile) { var triviaScanner = ts.createScanner(sourceFile.languageVersion, false, sourceText); var referencedFiles = []; @@ -8068,7 +8468,7 @@ var ts; referencedFiles.push(fileReference); } if (diagnosticMessage) { - sourceFile.parseDiagnostics.push(ts.createFileDiagnostic(sourceFile, range.pos, range.end - range.pos, diagnosticMessage)); + parseDiagnostics.push(ts.createFileDiagnostic(sourceFile, range.pos, range.end - range.pos, diagnosticMessage)); } } else { @@ -8076,7 +8476,7 @@ var ts; var amdModuleNameMatchResult = amdModuleNameRegEx.exec(comment); if (amdModuleNameMatchResult) { if (amdModuleName) { - sourceFile.parseDiagnostics.push(ts.createFileDiagnostic(sourceFile, range.pos, range.end - range.pos, ts.Diagnostics.An_AMD_module_cannot_have_multiple_name_assignments)); + parseDiagnostics.push(ts.createFileDiagnostic(sourceFile, range.pos, range.end - range.pos, ts.Diagnostics.An_AMD_module_cannot_have_multiple_name_assignments)); } amdModuleName = amdModuleNameMatchResult[2]; } @@ -8096,19 +8496,527 @@ var ts; } sourceFile.referencedFiles = referencedFiles; sourceFile.amdDependencies = amdDependencies; - sourceFile.amdModuleName = amdModuleName; + sourceFile.moduleName = amdModuleName; } function setExternalModuleIndicator(sourceFile) { sourceFile.externalModuleIndicator = ts.forEach(sourceFile.statements, function (node) { return node.flags & 1 - || node.kind === 209 && node.moduleReference.kind === 220 - || node.kind === 210 - || node.kind === 215 - || node.kind === 216 + || node.kind === 211 && node.moduleReference.kind === 222 + || node.kind === 212 + || node.kind === 217 + || node.kind === 218 ? node : undefined; }); } + var JSDocParser; + (function (JSDocParser) { + function isJSDocType() { + switch (token) { + case 35: + case 50: + case 16: + case 18: + case 46: + case 14: + case 83: + case 21: + case 88: + case 93: + return true; + } + return isIdentifierOrKeyword(); + } + JSDocParser.isJSDocType = isJSDocType; + function parseJSDocTypeExpressionForTests(content, start, length) { + initializeState("file.js", content, 2, undefined); + var jsDocTypeExpression = parseJSDocTypeExpression(start, length); + var diagnostics = parseDiagnostics; + clearState(); + return jsDocTypeExpression ? { jsDocTypeExpression: jsDocTypeExpression, diagnostics: diagnostics } : undefined; + } + JSDocParser.parseJSDocTypeExpressionForTests = parseJSDocTypeExpressionForTests; + function parseJSDocTypeExpression(start, length) { + scanner.setText(sourceText, start, length); + token = nextToken(); + var result = createNode(231); + parseExpected(14); + result.type = parseJSDocTopLevelType(); + parseExpected(15); + fixupParentReferences(result); + return finishNode(result); + } + JSDocParser.parseJSDocTypeExpression = parseJSDocTypeExpression; + function parseJSDocTopLevelType() { + var type = parseJSDocType(); + if (token === 44) { + var unionType = createNode(235, type.pos); + unionType.types = parseJSDocTypeList(type); + type = finishNode(unionType); + } + if (token === 53) { + var optionalType = createNode(242, type.pos); + nextToken(); + optionalType.type = type; + type = finishNode(optionalType); + } + return type; + } + function parseJSDocType() { + var type = parseBasicTypeExpression(); + while (true) { + if (token === 18) { + var arrayType = createNode(234, type.pos); + arrayType.elementType = type; + nextToken(); + parseExpected(19); + type = finishNode(arrayType); + } + else if (token === 50) { + var nullableType = createNode(237, type.pos); + nullableType.type = type; + nextToken(); + type = finishNode(nullableType); + } + else if (token === 46) { + var nonNullableType = createNode(238, type.pos); + nonNullableType.type = type; + nextToken(); + type = finishNode(nonNullableType); + } + else { + break; + } + } + return type; + } + function parseBasicTypeExpression() { + switch (token) { + case 35: + return parseJSDocAllType(); + case 50: + return parseJSDocUnknownOrNullableType(); + case 16: + return parseJSDocUnionType(); + case 18: + return parseJSDocTupleType(); + case 46: + return parseJSDocNonNullableType(); + case 14: + return parseJSDocRecordType(); + case 83: + return parseJSDocFunctionType(); + case 21: + return parseJSDocVariadicType(); + case 88: + return parseJSDocConstructorType(); + case 93: + return parseJSDocThisType(); + case 112: + case 123: + case 121: + case 113: + case 124: + case 99: + return parseTokenNode(); + } + return parseJSDocTypeReference(); + } + function parseJSDocThisType() { + var result = createNode(246); + nextToken(); + parseExpected(51); + result.type = parseJSDocType(); + return finishNode(result); + } + function parseJSDocConstructorType() { + var result = createNode(245); + nextToken(); + parseExpected(51); + result.type = parseJSDocType(); + return finishNode(result); + } + function parseJSDocVariadicType() { + var result = createNode(244); + nextToken(); + result.type = parseJSDocType(); + return finishNode(result); + } + function parseJSDocFunctionType() { + var result = createNode(243); + nextToken(); + parseExpected(16); + result.parameters = parseDelimitedList(20, parseJSDocParameter); + checkForTrailingComma(result.parameters); + parseExpected(17); + if (token === 51) { + nextToken(); + result.type = parseJSDocType(); + } + return finishNode(result); + } + function parseJSDocParameter() { + var parameter = createNode(131); + parameter.type = parseJSDocType(); + return finishNode(parameter); + } + function parseJSDocOptionalType(type) { + var result = createNode(242, type.pos); + nextToken(); + result.type = type; + return finishNode(result); + } + function parseJSDocTypeReference() { + var result = createNode(241); + result.name = parseSimplePropertyName(); + while (parseOptional(20)) { + if (token === 24) { + result.typeArguments = parseTypeArguments(); + break; + } + else { + result.name = parseQualifiedName(result.name); + } + } + return finishNode(result); + } + function parseTypeArguments() { + nextToken(); + var typeArguments = parseDelimitedList(21, parseJSDocType); + checkForTrailingComma(typeArguments); + checkForEmptyTypeArgumentList(typeArguments); + parseExpected(25); + return typeArguments; + } + function checkForEmptyTypeArgumentList(typeArguments) { + if (parseDiagnostics.length === 0 && typeArguments && typeArguments.length === 0) { + var start = typeArguments.pos - "<".length; + var end = ts.skipTrivia(sourceText, typeArguments.end) + ">".length; + return parseErrorAtPosition(start, end - start, ts.Diagnostics.Type_argument_list_cannot_be_empty); + } + } + function parseQualifiedName(left) { + var result = createNode(128, left.pos); + result.left = left; + result.right = parseIdentifierName(); + return finishNode(result); + } + function parseJSDocRecordType() { + var result = createNode(239); + nextToken(); + result.members = parseDelimitedList(22, parseJSDocRecordMember); + checkForTrailingComma(result.members); + parseExpected(15); + return finishNode(result); + } + function parseJSDocRecordMember() { + var result = createNode(240); + result.name = parseSimplePropertyName(); + if (token === 51) { + nextToken(); + result.type = parseJSDocType(); + } + return finishNode(result); + } + function parseJSDocNonNullableType() { + var result = createNode(238); + nextToken(); + result.type = parseJSDocType(); + return finishNode(result); + } + function parseJSDocTupleType() { + var result = createNode(236); + nextToken(); + result.types = parseDelimitedList(23, parseJSDocType); + checkForTrailingComma(result.types); + parseExpected(19); + 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(235); + nextToken(); + result.types = parseJSDocTypeList(parseJSDocType()); + parseExpected(17); + return finishNode(result); + } + function parseJSDocTypeList(firstType) { + ts.Debug.assert(!!firstType); + var types = []; + types.pos = firstType.pos; + types.push(firstType); + while (parseOptional(44)) { + types.push(parseJSDocType()); + } + types.end = scanner.getStartPos(); + return types; + } + function parseJSDocAllType() { + var result = createNode(232); + nextToken(); + return finishNode(result); + } + function parseJSDocUnknownOrNullableType() { + var pos = scanner.getStartPos(); + nextToken(); + if (token === 23 || + token === 15 || + token === 17 || + token === 25 || + token === 53 || + token === 44) { + var result = createNode(233, pos); + return finishNode(result); + } + else { + var result = createNode(237, pos); + result.type = parseJSDocType(); + return finishNode(result); + } + } + function parseIsolatedJSDocComment(content, start, length) { + initializeState("file.js", content, 2, undefined); + var jsDocComment = parseJSDocComment(undefined, start, length); + var diagnostics = parseDiagnostics; + clearState(); + return jsDocComment ? { jsDocComment: jsDocComment, diagnostics: diagnostics } : undefined; + } + JSDocParser.parseIsolatedJSDocComment = parseIsolatedJSDocComment; + function parseJSDocComment(parent, start, length) { + var comment = parseJSDocCommentWorker(start, length); + if (comment) { + fixupParentReferences(comment); + comment.parent = parent; + } + return comment; + } + JSDocParser.parseJSDocComment = parseJSDocComment; + 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 pos; + if (length >= "/** */".length) { + if (content.charCodeAt(start) === 47 && + content.charCodeAt(start + 1) === 42 && + content.charCodeAt(start + 2) === 42 && + content.charCodeAt(start + 3) !== 42) { + var canParseTag = true; + var seenAsterisk = true; + for (pos = start + "/**".length; pos < end;) { + var ch = content.charCodeAt(pos); + pos++; + if (ch === 64 && canParseTag) { + parseTag(); + canParseTag = false; + continue; + } + if (ts.isLineBreak(ch)) { + canParseTag = true; + seenAsterisk = false; + continue; + } + if (ts.isWhiteSpace(ch)) { + continue; + } + if (ch === 42) { + if (seenAsterisk) { + canParseTag = false; + } + seenAsterisk = true; + continue; + } + canParseTag = false; + } + } + } + return createJSDocComment(); + function createJSDocComment() { + if (!tags) { + return undefined; + } + var result = createNode(247, start); + result.tags = tags; + return finishNode(result, end); + } + function skipWhitespace() { + while (pos < end && ts.isWhiteSpace(content.charCodeAt(pos))) { + pos++; + } + } + function parseTag() { + ts.Debug.assert(content.charCodeAt(pos - 1) === 64); + var atToken = createNode(52, pos - 1); + atToken.end = pos; + var startPos = pos; + var tagName = scanIdentifier(); + if (!tagName) { + return; + } + var tag = handleTag(atToken, tagName) || handleUnknownTag(atToken, tagName); + addTag(tag); + } + function handleTag(atToken, tagName) { + if (tagName) { + switch (tagName.text) { + case "param": + return handleParamTag(atToken, tagName); + case "return": + case "returns": + return handleReturnTag(atToken, tagName); + case "template": + return handleTemplateTag(atToken, tagName); + case "type": + return handleTypeTag(atToken, tagName); + } + } + return undefined; + } + function handleUnknownTag(atToken, tagName) { + var result = createNode(248, atToken.pos); + result.atToken = atToken; + result.tagName = tagName; + return finishNode(result, pos); + } + function addTag(tag) { + if (tag) { + if (!tags) { + tags = []; + tags.pos = tag.pos; + } + tags.push(tag); + tags.end = tag.end; + } + } + function tryParseTypeExpression() { + skipWhitespace(); + if (content.charCodeAt(pos) !== 123) { + return undefined; + } + var typeExpression = parseJSDocTypeExpression(pos, end - pos); + pos = typeExpression.end; + return typeExpression; + } + function handleParamTag(atToken, tagName) { + var typeExpression = tryParseTypeExpression(); + skipWhitespace(); + var name; + var isBracketed; + if (content.charCodeAt(pos) === 91) { + pos++; + skipWhitespace(); + name = scanIdentifier(); + isBracketed = true; + } + else { + name = scanIdentifier(); + } + if (!name) { + parseErrorAtPosition(pos, 0, ts.Diagnostics.Identifier_expected); + return undefined; + } + var preName, postName; + if (typeExpression) { + postName = name; + } + else { + preName = name; + } + if (!typeExpression) { + typeExpression = tryParseTypeExpression(); + } + var result = createNode(249, atToken.pos); + result.atToken = atToken; + result.tagName = tagName; + result.preParameterName = preName; + result.typeExpression = typeExpression; + result.postParameterName = postName; + result.isBracketed = isBracketed; + return finishNode(result, pos); + } + function handleReturnTag(atToken, tagName) { + if (ts.forEach(tags, function (t) { return t.kind === 250; })) { + parseErrorAtPosition(tagName.pos, pos - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.text); + } + var result = createNode(250, atToken.pos); + result.atToken = atToken; + result.tagName = tagName; + result.typeExpression = tryParseTypeExpression(); + return finishNode(result, pos); + } + function handleTypeTag(atToken, tagName) { + if (ts.forEach(tags, function (t) { return t.kind === 251; })) { + parseErrorAtPosition(tagName.pos, pos - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.text); + } + var result = createNode(251, atToken.pos); + result.atToken = atToken; + result.tagName = tagName; + result.typeExpression = tryParseTypeExpression(); + return finishNode(result, pos); + } + function handleTemplateTag(atToken, tagName) { + if (ts.forEach(tags, function (t) { return t.kind === 252; })) { + parseErrorAtPosition(tagName.pos, pos - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.text); + } + var typeParameters = []; + typeParameters.pos = pos; + while (true) { + skipWhitespace(); + var startPos = pos; + var name_7 = scanIdentifier(); + if (!name_7) { + parseErrorAtPosition(startPos, 0, ts.Diagnostics.Identifier_expected); + return undefined; + } + var typeParameter = createNode(130, name_7.pos); + typeParameter.name = name_7; + finishNode(typeParameter, pos); + typeParameters.push(typeParameter); + skipWhitespace(); + if (content.charCodeAt(pos) !== 44) { + break; + } + pos++; + } + typeParameters.end = pos; + var result = createNode(252, atToken.pos); + result.atToken = atToken; + result.tagName = tagName; + result.typeParameters = typeParameters; + return finishNode(result, pos); + } + function scanIdentifier() { + var startPos = pos; + for (; pos < end; pos++) { + var ch = content.charCodeAt(pos); + if (pos === startPos && ts.isIdentifierStart(ch, 2)) { + continue; + } + else if (pos > startPos && ts.isIdentifierPart(ch, 2)) { + continue; + } + break; + } + if (startPos === pos) { + return undefined; + } + var result = createNode(65, startPos); + result.text = content.substring(startPos, pos); + return finishNode(result, pos); + } + } + JSDocParser.parseJSDocCommentWorker = parseJSDocCommentWorker; + })(JSDocParser = Parser.JSDocParser || (Parser.JSDocParser = {})); })(Parser || (Parser = {})); var IncrementalParser; (function (IncrementalParser) { @@ -8149,7 +9057,12 @@ var ts; if (aggressiveChecks && shouldCheckNode(node)) { var text = oldText.substring(node.pos, node.end); } - node._children = undefined; + if (node._children) { + node._children = undefined; + } + if (node.jsDocComment) { + node.jsDocComment = undefined; + } node.pos += delta; node.end += delta; if (aggressiveChecks && shouldCheckNode(node)) { @@ -8391,16 +9304,16 @@ var ts; (function (ts) { ts.bindTime = 0; function getModuleInstanceState(node) { - if (node.kind === 203 || node.kind === 204) { + if (node.kind === 205 || node.kind === 206) { return 0; } else if (ts.isConstEnumDeclaration(node)) { return 2; } - else if ((node.kind === 210 || node.kind === 209) && !(node.flags & 1)) { + else if ((node.kind === 212 || node.kind === 211) && !(node.flags & 1)) { return 0; } - else if (node.kind === 207) { + else if (node.kind === 209) { var state = 0; ts.forEachChild(node, function (n) { switch (getModuleInstanceState(n)) { @@ -8416,7 +9329,7 @@ var ts; }); return state; } - else if (node.kind === 206) { + else if (node.kind === 208) { return getModuleInstanceState(node.body); } else { @@ -8435,44 +9348,43 @@ var ts; var container; var blockScopeContainer; var lastContainer; + var inStrictMode = !!file.externalModuleIndicator; var symbolCount = 0; var Symbol = ts.objectAllocator.getSymbolConstructor(); + var classifiableNames = {}; if (!file.locals) { - file.locals = {}; - container = file; - setBlockScopeContainer(file, false); bind(file); file.symbolCount = symbolCount; + file.classifiableNames = classifiableNames; } + return; function createSymbol(flags, name) { symbolCount++; return new Symbol(flags, name); } - function setBlockScopeContainer(node, cleanLocals) { - blockScopeContainer = node; - if (cleanLocals) { - blockScopeContainer.locals = undefined; - } - } - function addDeclarationToSymbol(symbol, node, symbolKind) { - symbol.flags |= symbolKind; - if (!symbol.declarations) - symbol.declarations = []; - symbol.declarations.push(node); - if (symbolKind & 1952 && !symbol.exports) - symbol.exports = {}; - if (symbolKind & 6240 && !symbol.members) - symbol.members = {}; + function addDeclarationToSymbol(symbol, node, symbolFlags) { + symbol.flags |= symbolFlags; node.symbol = symbol; - if (symbolKind & 107455 && !symbol.valueDeclaration) + if (!symbol.declarations) { + symbol.declarations = []; + } + symbol.declarations.push(node); + if (symbolFlags & 1952 && !symbol.exports) { + symbol.exports = {}; + } + if (symbolFlags & 6240 && !symbol.members) { + symbol.members = {}; + } + if (symbolFlags & 107455 && !symbol.valueDeclaration) { symbol.valueDeclaration = node; + } } function getDeclarationName(node) { if (node.name) { - if (node.kind === 206 && node.name.kind === 8) { + if (node.kind === 208 && node.name.kind === 8) { return '"' + node.name.text + '"'; } - if (node.name.kind === 128) { + if (node.name.kind === 129) { var nameExpression = node.name.expression; ts.Debug.assert(ts.isWellKnownSymbolSyntactically(nameExpression)); return ts.getPropertyNameForKnownSymbolName(nameExpression.name.text); @@ -8480,34 +9392,39 @@ var ts; return node.name.text; } switch (node.kind) { - case 144: - case 136: + case 137: return "__constructor"; - case 143: - case 139: - return "__call"; + case 145: case 140: - return "__new"; + return "__call"; + case 146: case 141: + return "__new"; + case 142: return "__index"; - case 216: + case 218: return "__export"; - case 215: + case 217: return node.isExportEquals ? "export=" : "default"; - case 201: - case 202: + case 203: + case 204: return node.flags & 256 ? "default" : undefined; } } function getDisplayName(node) { return node.name ? ts.declarationNameToString(node.name) : getDeclarationName(node); } - function declareSymbol(symbols, parent, node, includes, excludes) { + function declareSymbol(symbolTable, parent, node, includes, excludes) { ts.Debug.assert(!ts.hasDynamicName(node)); var name = node.flags & 256 && parent ? "default" : getDeclarationName(node); var symbol; if (name !== undefined) { - symbol = ts.hasProperty(symbols, name) ? symbols[name] : (symbols[name] = createSymbol(0, name)); + symbol = ts.hasProperty(symbolTable, name) + ? symbolTable[name] + : (symbolTable[name] = createSymbol(0, name)); + if (name && (includes & 788448)) { + classifiableNames[name] = name; + } if (symbol.flags & excludes) { if (node.name) { node.name.parent = node; @@ -8527,125 +9444,158 @@ var ts; } addDeclarationToSymbol(symbol, node, includes); symbol.parent = parent; - if ((node.kind === 202 || node.kind === 175) && symbol.exports) { - var prototypeSymbol = createSymbol(4 | 134217728, "prototype"); - if (ts.hasProperty(symbol.exports, prototypeSymbol.name)) { - if (node.name) { - node.name.parent = node; - } - file.bindDiagnostics.push(ts.createDiagnosticForNode(symbol.exports[prototypeSymbol.name].declarations[0], ts.Diagnostics.Duplicate_identifier_0, prototypeSymbol.name)); - } - symbol.exports[prototypeSymbol.name] = prototypeSymbol; - prototypeSymbol.parent = symbol; - } return symbol; } - function declareModuleMember(node, symbolKind, symbolExcludes) { + function declareModuleMember(node, symbolFlags, symbolExcludes) { var hasExportModifier = ts.getCombinedNodeFlags(node) & 1; - if (symbolKind & 8388608) { - if (node.kind === 218 || (node.kind === 209 && hasExportModifier)) { - declareSymbol(container.symbol.exports, container.symbol, node, symbolKind, symbolExcludes); + if (symbolFlags & 8388608) { + if (node.kind === 220 || (node.kind === 211 && hasExportModifier)) { + return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); } else { - declareSymbol(container.locals, undefined, node, symbolKind, symbolExcludes); + return declareSymbol(container.locals, undefined, node, symbolFlags, symbolExcludes); } } else { if (hasExportModifier || container.flags & 65536) { - var exportKind = (symbolKind & 107455 ? 1048576 : 0) | - (symbolKind & 793056 ? 2097152 : 0) | - (symbolKind & 1536 ? 4194304 : 0); + var exportKind = (symbolFlags & 107455 ? 1048576 : 0) | + (symbolFlags & 793056 ? 2097152 : 0) | + (symbolFlags & 1536 ? 4194304 : 0); var local = declareSymbol(container.locals, undefined, node, exportKind, symbolExcludes); - local.exportSymbol = declareSymbol(container.symbol.exports, container.symbol, node, symbolKind, symbolExcludes); + local.exportSymbol = declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); node.localSymbol = local; + return local; } else { - declareSymbol(container.locals, undefined, node, symbolKind, symbolExcludes); + return declareSymbol(container.locals, undefined, node, symbolFlags, symbolExcludes); } } } - function bindChildren(node, symbolKind, isBlockScopeContainer) { - if (symbolKind & 255504) { - node.locals = {}; - } + function bindChildren(node) { var saveParent = parent; var saveContainer = container; var savedBlockScopeContainer = blockScopeContainer; parent = node; - if (symbolKind & 262128) { - container = node; + var containerFlags = getContainerFlags(node); + if (containerFlags & 1) { + container = blockScopeContainer = node; + if (containerFlags & 4) { + container.locals = {}; + } addToContainerChain(container); } - if (isBlockScopeContainer) { - setBlockScopeContainer(node, (symbolKind & 255504) === 0 && node.kind !== 228); + else if (containerFlags & 2) { + blockScopeContainer = node; + blockScopeContainer.locals = undefined; } ts.forEachChild(node, bind); container = saveContainer; parent = saveParent; blockScopeContainer = savedBlockScopeContainer; } - function addToContainerChain(node) { - if (lastContainer) { - lastContainer.nextContainer = node; - } - lastContainer = node; - } - function bindDeclaration(node, symbolKind, symbolExcludes, isBlockScopeContainer) { - switch (container.kind) { - case 206: - declareModuleMember(node, symbolKind, symbolExcludes); - break; - case 228: - if (ts.isExternalModule(container)) { - declareModuleMember(node, symbolKind, symbolExcludes); - break; - } - case 143: - case 144: - case 139: + function getContainerFlags(node) { + switch (node.kind) { + case 177: + case 204: + case 205: + case 207: + case 148: + case 157: + return 1; case 140: case 141: - case 135: - case 134: + case 142: case 136: + case 135: + case 203: case 137: case 138: - case 201: - case 163: - case 164: - declareSymbol(container.locals, undefined, node, symbolKind, symbolExcludes); - break; - case 175: - case 202: - if (node.flags & 128) { - declareSymbol(container.symbol.exports, container.symbol, node, symbolKind, symbolExcludes); - break; - } + case 139: + case 145: case 146: - case 155: - case 203: - declareSymbol(container.symbol.members, container.symbol, node, symbolKind, symbolExcludes); - break; - case 205: - declareSymbol(container.symbol.exports, container.symbol, node, symbolKind, symbolExcludes); - break; + case 165: + case 166: + case 208: + case 230: + case 206: + return 5; + case 226: + case 189: + case 190: + case 191: + case 210: + return 2; + case 182: + return ts.isFunctionLike(node.parent) ? 0 : 2; } - bindChildren(node, symbolKind, isBlockScopeContainer); + return 0; + } + function addToContainerChain(next) { + if (lastContainer) { + lastContainer.nextContainer = next; + } + lastContainer = next; + } + function declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes) { + declareSymbolAndAddToSymbolTableWorker(node, symbolFlags, symbolExcludes); + } + function declareSymbolAndAddToSymbolTableWorker(node, symbolFlags, symbolExcludes) { + switch (container.kind) { + case 208: + return declareModuleMember(node, symbolFlags, symbolExcludes); + case 230: + return declareSourceFileMember(node, symbolFlags, symbolExcludes); + case 177: + case 204: + return declareClassMember(node, symbolFlags, symbolExcludes); + case 207: + return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); + case 148: + case 157: + case 205: + return declareSymbol(container.symbol.members, container.symbol, node, symbolFlags, symbolExcludes); + case 145: + case 146: + case 140: + case 141: + case 142: + case 136: + case 135: + case 137: + case 138: + case 139: + case 203: + case 165: + case 166: + case 206: + return declareSymbol(container.locals, undefined, node, symbolFlags, symbolExcludes); + } + } + function declareClassMember(node, symbolFlags, symbolExcludes) { + return node.flags & 128 + ? 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 isAmbientContext(node) { while (node) { - if (node.flags & 2) + if (node.flags & 2) { return true; + } node = node.parent; } return false; } function hasExportDeclarations(node) { - var body = node.kind === 228 ? node : node.body; - if (body.kind === 228 || body.kind === 207) { + var body = node.kind === 230 ? node : node.body; + if (body.kind === 230 || body.kind === 209) { for (var _i = 0, _a = body.statements; _i < _a.length; _i++) { var stat = _a[_i]; - if (stat.kind === 216 || stat.kind === 215) { + if (stat.kind === 218 || stat.kind === 217) { return true; } } @@ -8663,15 +9613,15 @@ var ts; function bindModuleDeclaration(node) { setExportContextFlag(node); if (node.name.kind === 8) { - bindDeclaration(node, 512, 106639, true); + declareSymbolAndAddToSymbolTable(node, 512, 106639); } else { var state = getModuleInstanceState(node); if (state === 0) { - bindDeclaration(node, 1024, 0, true); + declareSymbolAndAddToSymbolTable(node, 1024, 0); } else { - bindDeclaration(node, 512, 106639, true); + declareSymbolAndAddToSymbolTable(node, 512, 106639); var currentModuleIsConstEnumOnly = state === 2; if (node.symbol.constEnumOnlyModule === undefined) { node.symbol.constEnumOnlyModule = currentModuleIsConstEnumOnly; @@ -8683,36 +9633,50 @@ var ts; } } 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, getDeclarationName(node)); addDeclarationToSymbol(symbol, node, 131072); - bindChildren(node, 131072, false); var typeLiteralSymbol = createSymbol(2048, "__type"); addDeclarationToSymbol(typeLiteralSymbol, node, 2048); - typeLiteralSymbol.members = {}; - typeLiteralSymbol.members[node.kind === 143 ? "__call" : "__new"] = symbol; + typeLiteralSymbol.members = (_a = {}, _a[symbol.name] = symbol, _a); + var _a; } - function bindAnonymousDeclaration(node, symbolKind, name, isBlockScopeContainer) { - var symbol = createSymbol(symbolKind, name); - addDeclarationToSymbol(symbol, node, symbolKind); - bindChildren(node, symbolKind, isBlockScopeContainer); + function bindObjectLiteralExpression(node) { + if (inStrictMode) { + var seen = {}; + for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { + var prop = _a[_i]; + if (prop.name.kind !== 65) { + continue; + } + var identifier = prop.name; + var currentKind = prop.kind === 227 || prop.kind === 228 || prop.kind === 136 + ? 1 + : 2; + var existingKind = seen[identifier.text]; + if (!existingKind) { + seen[identifier.text] = currentKind; + continue; + } + if (currentKind === 1 && existingKind === 1) { + var span = ts.getErrorSpanForNode(file, identifier); + file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, ts.Diagnostics.An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode)); + } + } + } + return bindAnonymousDeclaration(node, 4096, "__object"); } - function bindCatchVariableDeclaration(node) { - bindChildren(node, 0, true); + function bindAnonymousDeclaration(node, symbolFlags, name) { + var symbol = createSymbol(symbolFlags, name); + addDeclarationToSymbol(symbol, node, symbolFlags); } - function bindBlockScopedDeclaration(node, symbolKind, symbolExcludes) { + function bindBlockScopedDeclaration(node, symbolFlags, symbolExcludes) { switch (blockScopeContainer.kind) { - case 206: - declareModuleMember(node, symbolKind, symbolExcludes); + case 208: + declareModuleMember(node, symbolFlags, symbolExcludes); break; - case 228: + case 230: if (ts.isExternalModule(container)) { - declareModuleMember(node, symbolKind, symbolExcludes); + declareModuleMember(node, symbolFlags, symbolExcludes); break; } default: @@ -8720,185 +9684,322 @@ var ts; blockScopeContainer.locals = {}; addToContainerChain(blockScopeContainer); } - declareSymbol(blockScopeContainer.locals, undefined, node, symbolKind, symbolExcludes); + declareSymbol(blockScopeContainer.locals, undefined, node, symbolFlags, symbolExcludes); } - bindChildren(node, symbolKind, false); } function bindBlockScopedVariableDeclaration(node) { bindBlockScopedDeclaration(node, 2, 107455); } + function checkStrictModeIdentifier(node) { + if (inStrictMode && + node.originalKeywordKind >= 102 && + node.originalKeywordKind <= 110 && + !ts.isIdentifierName(node)) { + if (!file.parseDiagnostics.length) { + file.bindDiagnostics.push(ts.createDiagnosticForNode(node, getStrictModeIdentifierMessage(node), ts.declarationNameToString(node))); + } + } + } + function getStrictModeIdentifierMessage(node) { + if (ts.getAncestor(node, 204) || ts.getAncestor(node, 177)) { + 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 === 65) { + var span = ts.getErrorSpanForNode(file, node.expression); + file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, ts.Diagnostics.delete_cannot_be_called_on_an_identifier_in_strict_mode)); + } + } + function isEvalOrArgumentsIdentifier(node) { + return node.kind === 65 && + (node.text === "eval" || node.text === "arguments"); + } + function checkStrictModeEvalOrArguments(contextNode, name) { + if (name && name.kind === 65) { + var identifier = name; + if (isEvalOrArgumentsIdentifier(identifier)) { + var span = ts.getErrorSpanForNode(file, name); + file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, getStrictModeEvalOrArgumentsMessage(contextNode), identifier.text)); + } + } + } + function getStrictModeEvalOrArgumentsMessage(node) { + if (ts.getAncestor(node, 204) || ts.getAncestor(node, 177)) { + 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 checkStrictModeNumericLiteral(node) { + if (inStrictMode && node.flags & 16384) { + 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 === 38 || node.operator === 39) { + checkStrictModeEvalOrArguments(node, node.operand); + } + } + } + function checkStrictModeWithStatement(node) { + if (inStrictMode) { + grammarErrorOnFirstToken(node, ts.Diagnostics.with_statements_are_not_allowed_in_strict_mode); + } + } + function grammarErrorOnFirstToken(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) { node.parent = parent; + var savedInStrictMode = inStrictMode; + if (!savedInStrictMode) { + updateStrictMode(node); + } + bindWorker(node); + bindChildren(node); + inStrictMode = savedInStrictMode; + } + function updateStrictMode(node) { switch (node.kind) { - case 129: - bindDeclaration(node, 262144, 530912, false); - break; - case 130: - bindParameter(node); - break; - case 199: - case 153: - if (ts.isBindingPattern(node.name)) { - bindChildren(node, 0, false); + case 230: + case 209: + updateStrictModeStatementList(node.statements); + return; + case 182: + if (ts.isFunctionLike(node.parent)) { + updateStrictModeStatementList(node.statements); } - else if (ts.isBlockOrCatchScoped(node)) { - bindBlockScopedVariableDeclaration(node); - } - else if (ts.isParameterDeclaration(node)) { - bindDeclaration(node, 1, 107455, false); - } - else { - bindDeclaration(node, 1, 107454, false); - } - break; - case 133: - case 132: - bindPropertyOrMethodOrAccessor(node, 4 | (node.questionToken ? 536870912 : 0), 107455, false); - break; - case 225: + return; + case 204: + case 177: + inStrictMode = true; + return; + } + } + function updateStrictModeStatementList(statements) { + for (var _i = 0; _i < statements.length; _i++) { + var statement = statements[_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 65: + return checkStrictModeIdentifier(node); + case 172: + return checkStrictModeBinaryExpression(node); case 226: - bindPropertyOrMethodOrAccessor(node, 4, 107455, false); - break; + return checkStrictModeCatchClause(node); + case 167: + return checkStrictModeDeleteExpression(node); + case 7: + return checkStrictModeNumericLiteral(node); + case 171: + return checkStrictModePostfixUnaryExpression(node); + case 170: + return checkStrictModePrefixUnaryExpression(node); + case 195: + return checkStrictModeWithStatement(node); + case 130: + return declareSymbolAndAddToSymbolTable(node, 262144, 530912); + case 131: + return bindParameter(node); + case 201: + case 155: + return bindVariableDeclarationOrBindingElement(node); + case 134: + case 133: + return bindPropertyOrMethodOrAccessor(node, 4 | (node.questionToken ? 536870912 : 0), 107455); case 227: - bindPropertyOrMethodOrAccessor(node, 8, 107455, false); - break; - case 139: + case 228: + return bindPropertyOrMethodOrAccessor(node, 4, 107455); + case 229: + return bindPropertyOrMethodOrAccessor(node, 8, 107455); case 140: case 141: - bindDeclaration(node, 131072, 0, false); - break; - case 135: - case 134: - bindPropertyOrMethodOrAccessor(node, 8192 | (node.questionToken ? 536870912 : 0), ts.isObjectLiteralMethod(node) ? 107455 : 99263, true); - break; - case 201: - bindDeclaration(node, 16, 106927, true); - break; + case 142: + return declareSymbolAndAddToSymbolTable(node, 131072, 0); case 136: - bindDeclaration(node, 16384, 0, true); - break; - case 137: - bindPropertyOrMethodOrAccessor(node, 32768, 41919, true); - break; - case 138: - bindPropertyOrMethodOrAccessor(node, 65536, 74687, true); - break; - case 143: - case 144: - bindFunctionOrConstructorType(node); - break; - case 146: - bindAnonymousDeclaration(node, 2048, "__type", false); - break; - case 155: - bindAnonymousDeclaration(node, 4096, "__object", false); - break; - case 163: - case 164: - bindAnonymousDeclaration(node, 16, "__function", true); - break; - case 175: - bindAnonymousDeclaration(node, 32, "__class", false); - break; - case 224: - bindCatchVariableDeclaration(node); - break; - case 202: - bindBlockScopedDeclaration(node, 32, 899583); - break; + case 135: + return bindPropertyOrMethodOrAccessor(node, 8192 | (node.questionToken ? 536870912 : 0), ts.isObjectLiteralMethod(node) ? 107455 : 99263); case 203: - bindDeclaration(node, 64, 792992, false); - break; + checkStrictModeFunctionName(node); + return declareSymbolAndAddToSymbolTable(node, 16, 106927); + case 137: + return declareSymbolAndAddToSymbolTable(node, 16384, 0); + case 138: + return bindPropertyOrMethodOrAccessor(node, 32768, 41919); + case 139: + return bindPropertyOrMethodOrAccessor(node, 65536, 74687); + case 145: + case 146: + return bindFunctionOrConstructorType(node); + case 148: + return bindAnonymousDeclaration(node, 2048, "__type"); + case 157: + return bindObjectLiteralExpression(node); + case 165: + case 166: + checkStrictModeFunctionName(node); + return bindAnonymousDeclaration(node, 16, "__function"); + case 177: case 204: - bindDeclaration(node, 524288, 793056, false); - break; + return bindClassLikeDeclaration(node); case 205: - if (ts.isConst(node)) { - bindDeclaration(node, 128, 899967, false); - } - else { - bindDeclaration(node, 256, 899327, false); - } - break; + return bindBlockScopedDeclaration(node, 64, 792992); case 206: - bindModuleDeclaration(node); - break; - case 209: - case 212: - case 214: - case 218: - bindDeclaration(node, 8388608, 8388608, false); - break; - case 211: - if (node.name) { - bindDeclaration(node, 8388608, 8388608, false); - } - else { - bindChildren(node, 0, false); - } - break; - case 216: - if (!node.exportClause) { - declareSymbol(container.symbol.exports, container.symbol, node, 1073741824, 0); - } - bindChildren(node, 0, false); - break; - case 215: - if (node.expression.kind === 65) { - declareSymbol(container.symbol.exports, container.symbol, node, 8388608, 107455 | 8388608); - } - else { - declareSymbol(container.symbol.exports, container.symbol, node, 4, 107455 | 8388608); - } - bindChildren(node, 0, false); - break; - case 228: - setExportContextFlag(node); - if (ts.isExternalModule(node)) { - bindAnonymousDeclaration(node, 512, '"' + ts.removeFileExtension(node.fileName) + '"', true); - break; - } - case 180: - bindChildren(node, 0, !ts.isFunctionLike(node.parent)); - break; - case 224: - case 187: - case 188: - case 189: + return bindBlockScopedDeclaration(node, 524288, 793056); + case 207: + return bindEnumDeclaration(node); case 208: - bindChildren(node, 0, true); - break; - default: - var saveParent = parent; - parent = node; - ts.forEachChild(node, bind); - parent = saveParent; + return bindModuleDeclaration(node); + case 211: + case 214: + case 216: + case 220: + return declareSymbolAndAddToSymbolTable(node, 8388608, 8388608); + case 213: + return bindImportClause(node); + case 218: + return bindExportDeclaration(node); + case 217: + return bindExportAssignment(node); + case 230: + return bindSourceFileIfExternalModule(); + } + } + function bindSourceFileIfExternalModule() { + setExportContextFlag(file); + if (ts.isExternalModule(file)) { + bindAnonymousDeclaration(file, 512, '"' + ts.removeFileExtension(file.fileName) + '"'); + } + } + function bindExportAssignment(node) { + if (!container.symbol || !container.symbol.exports) { + bindAnonymousDeclaration(node, 8388608, getDeclarationName(node)); + } + else if (node.expression.kind === 65) { + declareSymbol(container.symbol.exports, container.symbol, node, 8388608, 107455 | 8388608); + } + else { + declareSymbol(container.symbol.exports, container.symbol, node, 4, 107455 | 8388608); + } + } + function bindExportDeclaration(node) { + if (!container.symbol || !container.symbol.exports) { + bindAnonymousDeclaration(node, 1073741824, getDeclarationName(node)); + } + else if (!node.exportClause) { + declareSymbol(container.symbol.exports, container.symbol, node, 1073741824, 0); + } + } + function bindImportClause(node) { + if (node.name) { + declareSymbolAndAddToSymbolTable(node, 8388608, 8388608); + } + } + function bindClassLikeDeclaration(node) { + if (node.kind === 204) { + bindBlockScopedDeclaration(node, 32, 899583); + } + else { + bindAnonymousDeclaration(node, 32, "__class"); + } + var symbol = node.symbol; + var prototypeSymbol = createSymbol(4 | 134217728, "prototype"); + if (ts.hasProperty(symbol.exports, prototypeSymbol.name)) { + if (node.name) { + node.name.parent = node; + } + file.bindDiagnostics.push(ts.createDiagnosticForNode(symbol.exports[prototypeSymbol.name].declarations[0], ts.Diagnostics.Duplicate_identifier_0, prototypeSymbol.name)); + } + symbol.exports[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) { + checkStrictModeEvalOrArguments(node, node.name); + } if (ts.isBindingPattern(node.name)) { - bindAnonymousDeclaration(node, 1, getDestructuringParameterName(node), false); + bindAnonymousDeclaration(node, 1, getDestructuringParameterName(node)); } else { - bindDeclaration(node, 1, 107455, false); + declareSymbolAndAddToSymbolTable(node, 1, 107455); } if (node.flags & 112 && - node.parent.kind === 136 && - (node.parent.parent.kind === 202 || node.parent.parent.kind === 175)) { + node.parent.kind === 137 && + (node.parent.parent.kind === 204 || node.parent.parent.kind === 177)) { var classDeclaration = node.parent.parent; declareSymbol(classDeclaration.symbol.members, classDeclaration.symbol, node, 4, 107455); } } - function bindPropertyOrMethodOrAccessor(node, symbolKind, symbolExcludes, isBlockScopeContainer) { - if (ts.hasDynamicName(node)) { - bindAnonymousDeclaration(node, symbolKind, "__computed", isBlockScopeContainer); - } - else { - bindDeclaration(node, symbolKind, symbolExcludes, isBlockScopeContainer); - } + function bindPropertyOrMethodOrAccessor(node, symbolFlags, symbolExcludes) { + return ts.hasDynamicName(node) + ? bindAnonymousDeclaration(node, symbolFlags, "__computed") + : declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes); } } })(ts || (ts = {})); @@ -8976,18 +10077,20 @@ var ts; var stringType = createIntrinsicType(2, "string"); var numberType = createIntrinsicType(4, "number"); var booleanType = createIntrinsicType(8, "boolean"); - var esSymbolType = createIntrinsicType(1048576, "symbol"); + var esSymbolType = createIntrinsicType(2097152, "symbol"); var voidType = createIntrinsicType(16, "void"); - var undefinedType = createIntrinsicType(32 | 262144, "undefined"); - var nullType = createIntrinsicType(64 | 262144, "null"); + var undefinedType = createIntrinsicType(32 | 524288, "undefined"); + var nullType = createIntrinsicType(64 | 524288, "null"); var unknownType = createIntrinsicType(1, "unknown"); + var circularType = createIntrinsicType(1, "__circular__"); var emptyObjectType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); + var emptyGenericType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); + emptyGenericType.instantiations = {}; var anyFunctionType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); var noConstraintType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); - var anySignature = createSignature(undefined, undefined, emptyArray, anyType, 0, false, false); - var unknownSignature = createSignature(undefined, undefined, emptyArray, unknownType, 0, false, false); + var anySignature = createSignature(undefined, undefined, emptyArray, anyType, undefined, 0, false, false); + var unknownSignature = createSignature(undefined, undefined, emptyArray, unknownType, undefined, 0, false, false); var globals = {}; - var globalArraySymbol; var globalESSymbolConstructorSymbol; var globalObjectType; var globalFunctionType; @@ -8999,6 +10102,8 @@ var ts; var globalTemplateStringsArrayType; var globalESSymbolType; var globalIterableType; + var globalIteratorType; + var globalIterableIteratorType; var anyArrayType; var getGlobalClassDecoratorType; var getGlobalParameterDecoratorType; @@ -9032,9 +10137,14 @@ var ts; }, "symbol": { type: esSymbolType, - flags: 1048576 + flags: 2097152 } }; + var subtypeRelation = {}; + var assignableRelation = {}; + var identityRelation = {}; + initializeTypeChecker(); + return checker; function getEmitResolver(sourceFile) { getDiagnostics(sourceFile); return emitResolver; @@ -9174,10 +10284,10 @@ var ts; return nodeLinks[nodeId] || (nodeLinks[nodeId] = {}); } function getSourceFile(node) { - return ts.getAncestor(node, 228); + return ts.getAncestor(node, 230); } function isGlobalSourceFile(node) { - return node.kind === 228 && !ts.isExternalModule(node); + return node.kind === 230 && !ts.isExternalModule(node); } function getSymbol(symbols, name, meaning) { if (meaning && ts.hasProperty(symbols, name)) { @@ -9215,38 +10325,47 @@ var ts; loop: while (location) { if (location.locals && !isGlobalSourceFile(location)) { if (result = getSymbol(location.locals, name, meaning)) { - break loop; + if (!(meaning & 793056) || + !(result.flags & (793056 & ~262144)) || + !ts.isFunctionLike(location) || + lastLocation === location.body) { + break loop; + } + result = undefined; } } switch (location.kind) { - case 228: + case 230: if (!ts.isExternalModule(location)) break; - case 206: - if (result = getSymbol(getSymbolOfNode(location).exports, name, meaning & 8914931)) { - if (result.flags & meaning || !(result.flags & 8388608 && getDeclarationOfAliasSymbol(result).kind === 218)) { - break loop; + case 208: + var moduleExports = getSymbolOfNode(location).exports; + if (location.kind === 230 || + (location.kind === 208 && location.name.kind === 8)) { + if (ts.hasProperty(moduleExports, name) && + moduleExports[name].flags === 8388608 && + ts.getDeclarationOfKind(moduleExports[name], 220)) { + break; } - result = undefined; - } - else if (location.kind === 228 || - (location.kind === 206 && location.name.kind === 8)) { - result = getSymbolOfNode(location).exports["default"]; + result = moduleExports["default"]; var localSymbol = ts.getLocalSymbolForExportDefault(result); if (result && localSymbol && (result.flags & meaning) && localSymbol.name === name) { break loop; } result = undefined; } + if (result = getSymbol(moduleExports, name, meaning & 8914931)) { + break loop; + } break; - case 205: + case 207: if (result = getSymbol(getSymbolOfNode(location).exports, name, meaning & 8)) { break loop; } break; + case 134: case 133: - case 132: - if (location.parent.kind === 202 && !(location.flags & 128)) { + if (location.parent.kind === 204 && !(location.flags & 128)) { var ctor = findConstructorDeclaration(location.parent); if (ctor && ctor.locals) { if (getSymbol(ctor.locals, name, meaning & 107455)) { @@ -9255,8 +10374,8 @@ var ts; } } break; - case 202: - case 203: + case 204: + case 205: if (result = getSymbol(getSymbolOfNode(location).members, name, meaning & 793056)) { if (lastLocation && lastLocation.flags & 128) { error(errorLocation, ts.Diagnostics.Static_members_cannot_reference_class_type_parameters); @@ -9265,47 +10384,51 @@ var ts; break loop; } break; - case 128: + case 129: grandparent = location.parent.parent; - if (grandparent.kind === 202 || grandparent.kind === 203) { + if (grandparent.kind === 204 || grandparent.kind === 205) { if (result = getSymbol(getSymbolOfNode(grandparent).members, name, meaning & 793056)) { error(errorLocation, ts.Diagnostics.A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type); return undefined; } } break; - case 135: - case 134: case 136: + case 135: case 137: case 138: - case 201: - case 164: - if (name === "arguments") { + case 139: + case 203: + case 166: + if (meaning & 3 && name === "arguments") { result = argumentsSymbol; break loop; } break; - case 163: - if (name === "arguments") { + case 165: + if (meaning & 3 && name === "arguments") { result = argumentsSymbol; break loop; } - var functionName = location.name; - if (functionName && name === functionName.text) { - result = location.symbol; - break loop; + if (meaning & 16) { + var functionName = location.name; + if (functionName && name === functionName.text) { + result = location.symbol; + break loop; + } } break; - case 175: - var className = location.name; - if (className && name === className.text) { - result = location.symbol; - break loop; + case 177: + if (meaning & 32) { + var className = location.name; + if (className && name === className.text) { + result = location.symbol; + break loop; + } } break; - case 131: - if (location.parent && location.parent.kind === 130) { + case 132: + if (location.parent && location.parent.kind === 131) { location = location.parent; } if (location.parent && ts.isClassElement(location.parent)) { @@ -9343,14 +10466,14 @@ var ts; ts.Debug.assert(declaration !== undefined, "Block-scoped variable declaration is undefined"); var isUsedBeforeDeclaration = !isDefinedBefore(declaration, errorLocation); if (!isUsedBeforeDeclaration) { - var variableDeclaration = ts.getAncestor(declaration, 199); + var variableDeclaration = ts.getAncestor(declaration, 201); var container = ts.getEnclosingBlockScopeContainer(variableDeclaration); - if (variableDeclaration.parent.parent.kind === 181 || - variableDeclaration.parent.parent.kind === 187) { + if (variableDeclaration.parent.parent.kind === 183 || + variableDeclaration.parent.parent.kind === 189) { isUsedBeforeDeclaration = isSameScopeDescendentOf(errorLocation, variableDeclaration, container); } - else if (variableDeclaration.parent.parent.kind === 189 || - variableDeclaration.parent.parent.kind === 188) { + else if (variableDeclaration.parent.parent.kind === 191 || + variableDeclaration.parent.parent.kind === 190) { var expression = variableDeclaration.parent.parent.expression; isUsedBeforeDeclaration = isSameScopeDescendentOf(errorLocation, expression, container); } @@ -9372,10 +10495,10 @@ var ts; } function getAnyImportSyntax(node) { if (ts.isAliasSymbolDeclaration(node)) { - if (node.kind === 209) { + if (node.kind === 211) { return node; } - while (node && node.kind !== 210) { + while (node && node.kind !== 212) { node = node.parent; } return node; @@ -9385,7 +10508,7 @@ var ts; return ts.forEach(symbol.declarations, function (d) { return ts.isAliasSymbolDeclaration(d) ? d : undefined; }); } function getTargetOfImportEqualsDeclaration(node) { - if (node.moduleReference.kind === 220) { + if (node.moduleReference.kind === 222) { return resolveExternalModuleSymbol(resolveExternalModuleName(node, ts.getExternalModuleImportEqualsDeclarationExpression(node))); } return getSymbolOfPartOfRightHandSideOfImportEquals(node.moduleReference, node); @@ -9447,15 +10570,15 @@ var ts; var moduleSymbol = resolveExternalModuleName(node, node.moduleSpecifier); var targetSymbol = resolveESModuleSymbol(moduleSymbol, node.moduleSpecifier); if (targetSymbol) { - var name_4 = specifier.propertyName || specifier.name; - if (name_4.text) { - var symbolFromModule = getExportOfModule(targetSymbol, name_4.text); - var symbolFromVariable = getPropertyOfVariable(targetSymbol, name_4.text); + var name_8 = specifier.propertyName || specifier.name; + if (name_8.text) { + var symbolFromModule = getExportOfModule(targetSymbol, name_8.text); + var symbolFromVariable = getPropertyOfVariable(targetSymbol, name_8.text); var symbol = symbolFromModule && symbolFromVariable ? combineValueAndTypeSymbols(symbolFromVariable, symbolFromModule) : symbolFromModule || symbolFromVariable; if (!symbol) { - error(name_4, ts.Diagnostics.Module_0_has_no_exported_member_1, getFullyQualifiedName(moduleSymbol), ts.declarationNameToString(name_4)); + error(name_8, ts.Diagnostics.Module_0_has_no_exported_member_1, getFullyQualifiedName(moduleSymbol), ts.declarationNameToString(name_8)); } return symbol; } @@ -9474,17 +10597,17 @@ var ts; } function getTargetOfAliasDeclaration(node) { switch (node.kind) { - case 209: - return getTargetOfImportEqualsDeclaration(node); case 211: + return getTargetOfImportEqualsDeclaration(node); + case 213: return getTargetOfImportClause(node); - case 212: - return getTargetOfNamespaceImport(node); case 214: + return getTargetOfNamespaceImport(node); + case 216: return getTargetOfImportSpecifier(node); - case 218: + case 220: return getTargetOfExportSpecifier(node); - case 215: + case 217: return getTargetOfExportAssignment(node); } } @@ -9514,7 +10637,7 @@ var ts; var symbol = getSymbolOfNode(node); var target = resolveAlias(symbol); if (target) { - var markAlias = (target === unknownSymbol && compilerOptions.separateCompilation) || + var markAlias = (target === unknownSymbol && compilerOptions.isolatedModules) || (target !== unknownSymbol && (target.flags & 107455) && !isConstEnumOrConstEnumOnlyModule(target)); if (markAlias) { markAliasSymbolAsReferenced(symbol); @@ -9526,10 +10649,10 @@ var ts; if (!links.referenced) { links.referenced = true; var node = getDeclarationOfAliasSymbol(symbol); - if (node.kind === 215) { + if (node.kind === 217) { checkExpressionCached(node.expression); } - else if (node.kind === 218) { + else if (node.kind === 220) { checkExpressionCached(node.propertyName || node.name); } else if (ts.isInternalModuleImportEqualsDeclaration(node)) { @@ -9539,17 +10662,17 @@ var ts; } function getSymbolOfPartOfRightHandSideOfImportEquals(entityName, importDeclaration) { if (!importDeclaration) { - importDeclaration = ts.getAncestor(entityName, 209); + importDeclaration = ts.getAncestor(entityName, 211); ts.Debug.assert(importDeclaration !== undefined); } if (entityName.kind === 65 && ts.isRightSideOfQualifiedNameOrPropertyAccess(entityName)) { entityName = entityName.parent; } - if (entityName.kind === 65 || entityName.parent.kind === 127) { + if (entityName.kind === 65 || entityName.parent.kind === 128) { return resolveEntityName(entityName, 1536); } else { - ts.Debug.assert(entityName.parent.kind === 209); + ts.Debug.assert(entityName.parent.kind === 211); return resolveEntityName(entityName, 107455 | 793056 | 1536); } } @@ -9568,9 +10691,9 @@ var ts; return undefined; } } - else if (name.kind === 127 || name.kind === 156) { - var left = name.kind === 127 ? name.left : name.expression; - var right = name.kind === 127 ? name.right : name.name; + else if (name.kind === 128 || name.kind === 158) { + var left = name.kind === 128 ? name.left : name.expression; + var right = name.kind === 128 ? name.right : name.name; var namespace = resolveEntityName(left, 1536); if (!namespace || namespace === unknownSymbol || ts.nodeIsMissing(right)) { return undefined; @@ -9715,7 +10838,7 @@ var ts; var members = node.members; for (var _i = 0; _i < members.length; _i++) { var member = members[_i]; - if (member.kind === 136 && ts.nodeIsPresent(member.body)) { + if (member.kind === 137 && ts.nodeIsPresent(member.body)) { return member; } } @@ -9780,17 +10903,17 @@ var ts; } } switch (location_1.kind) { - case 228: + case 230: if (!ts.isExternalModule(location_1)) { break; } - case 206: + case 208: if (result = callback(getSymbolOfNode(location_1).exports)) { return result; } break; - case 202: - case 203: + case 204: + case 205: if (result = callback(getSymbolOfNode(location_1).members)) { return result; } @@ -9905,8 +11028,8 @@ var ts; } } function hasExternalModuleSymbol(declaration) { - return (declaration.kind === 206 && declaration.name.kind === 8) || - (declaration.kind === 228 && ts.isExternalModule(declaration)); + return (declaration.kind === 208 && declaration.name.kind === 8) || + (declaration.kind === 230 && ts.isExternalModule(declaration)); } function hasVisibleDeclarations(symbol) { var aliasesToMakeVisible; @@ -9938,11 +11061,11 @@ var ts; } function isEntityNameVisible(entityName, enclosingDeclaration) { var meaning; - if (entityName.parent.kind === 145) { + if (entityName.parent.kind === 147) { meaning = 107455 | 1048576; } - else if (entityName.kind === 127 || entityName.kind === 156 || - entityName.parent.kind === 209) { + else if (entityName.kind === 128 || entityName.kind === 158 || + entityName.parent.kind === 211) { meaning = 1536; } else { @@ -9972,6 +11095,13 @@ var ts; ts.releaseStringWriter(writer); return result; } + function signatureToString(signature, enclosingDeclaration, flags) { + var writer = ts.getSingleLineStringWriter(); + getSymbolDisplayBuilder().buildSignatureDisplay(signature, writer, enclosingDeclaration, flags); + var result = writer.string(); + ts.releaseStringWriter(writer); + return result; + } function typeToString(type, enclosingDeclaration, flags) { var writer = ts.getSingleLineStringWriter(); getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); @@ -9986,10 +11116,10 @@ var ts; function getTypeAliasForTypeLiteral(type) { if (type.symbol && type.symbol.flags & 2048) { var node = type.symbol.declarations[0].parent; - while (node.kind === 150) { + while (node.kind === 152) { node = node.parent; } - if (node.kind === 204) { + if (node.kind === 206) { return getSymbolOfNode(node); } } @@ -10057,13 +11187,14 @@ var ts; } return appendParentTypeArgumentsAndSymbolName(symbol); } - function buildTypeDisplay(type, writer, enclosingDeclaration, globalFlags, typeStack) { + function buildTypeDisplay(type, writer, enclosingDeclaration, globalFlags, symbolStack) { var globalFlagsToPass = globalFlags & 16; return writeType(type, globalFlags); function writeType(type, flags) { - if (type.flags & 1048703) { - writer.writeKeyword(!(globalFlags & 16) && - (type.flags & 1) ? "any" : type.intrinsicName); + if (type.flags & 2097279) { + writer.writeKeyword(!(globalFlags & 16) && isTypeAny(type) + ? "any" + : type.intrinsicName); } else if (type.flags & 4096) { writeTypeReference(type, flags); @@ -10103,17 +11234,46 @@ var ts; writeType(types[i], union ? 64 : 0); } } + function writeSymbolTypeReference(symbol, typeArguments, pos, end) { + if (!isReservedMemberName(symbol.name)) { + buildSymbolDisplay(symbol, writer, enclosingDeclaration, 793056); + } + if (pos < end) { + writePunctuation(writer, 24); + writeType(typeArguments[pos++], 0); + while (pos < end) { + writePunctuation(writer, 23); + writeSpace(writer); + writeType(typeArguments[pos++], 0); + } + writePunctuation(writer, 25); + } + } function writeTypeReference(type, flags) { + var typeArguments = type.typeArguments; if (type.target === globalArrayType && !(flags & 1)) { - writeType(type.typeArguments[0], 64); + writeType(typeArguments[0], 64); writePunctuation(writer, 18); writePunctuation(writer, 19); } else { - buildSymbolDisplay(type.target.symbol, writer, enclosingDeclaration, 793056); - writePunctuation(writer, 24); - writeTypeList(type.typeArguments, false); - writePunctuation(writer, 25); + var outerTypeParameters = type.target.outerTypeParameters; + var i = 0; + if (outerTypeParameters) { + var length_1 = outerTypeParameters.length; + while (i < length_1) { + var start = i; + var parent_3 = getParentSymbolOfTypeParameter(outerTypeParameters[i]); + do { + i++; + } while (i < length_1 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent_3); + if (!ts.rangeEquals(outerTypeParameters, typeArguments, start, i)) { + writeSymbolTypeReference(parent_3, typeArguments, start, i); + writePunctuation(writer, 20); + } + } + } + writeSymbolTypeReference(type.symbol, typeArguments, i, typeArguments.length); } } function writeTupleType(type) { @@ -10131,42 +11291,46 @@ var ts; } } function writeAnonymousType(type, flags) { - if (type.symbol && type.symbol.flags & (32 | 384 | 512)) { - writeTypeofSymbol(type, flags); - } - else if (shouldWriteTypeOfFunctionSymbol()) { - writeTypeofSymbol(type, flags); - } - else if (typeStack && ts.contains(typeStack, type)) { - var typeAlias = getTypeAliasForTypeLiteral(type); - if (typeAlias) { - buildSymbolDisplay(typeAlias, writer, enclosingDeclaration, 793056, 0, flags); + var symbol = type.symbol; + if (symbol) { + if (symbol.flags & (32 | 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, 793056, 0, flags); + } + else { + writeKeyword(writer, 112); + } } else { - writeKeyword(writer, 112); + if (!symbolStack) { + symbolStack = []; + } + symbolStack.push(symbol); + writeLiteralType(type, flags); + symbolStack.pop(); } } else { - if (!typeStack) { - typeStack = []; - } - typeStack.push(type); writeLiteralType(type, flags); - typeStack.pop(); } function shouldWriteTypeOfFunctionSymbol() { - if (type.symbol) { - var isStaticMethodSymbol = !!(type.symbol.flags & 8192 && - ts.forEach(type.symbol.declarations, function (declaration) { return declaration.flags & 128; })); - var isNonLocalFunctionSymbol = !!(type.symbol.flags & 16) && - (type.symbol.parent || - ts.forEach(type.symbol.declarations, function (declaration) { - return declaration.parent.kind === 228 || declaration.parent.kind === 207; - })); - if (isStaticMethodSymbol || isNonLocalFunctionSymbol) { - return !!(flags & 2) || - (typeStack && ts.contains(typeStack, type)); - } + var isStaticMethodSymbol = !!(symbol.flags & 8192 && + ts.forEach(symbol.declarations, function (declaration) { return declaration.flags & 128; })); + var isNonLocalFunctionSymbol = !!(symbol.flags & 16) && + (symbol.parent || + ts.forEach(symbol.declarations, function (declaration) { + return declaration.parent.kind === 230 || declaration.parent.kind === 209; + })); + if (isStaticMethodSymbol || isNonLocalFunctionSymbol) { + return !!(flags & 2) || + (ts.contains(symbolStack, symbol)); } } } @@ -10195,7 +11359,7 @@ var ts; if (flags & 64) { writePunctuation(writer, 16); } - buildSignatureDisplay(resolved.callSignatures[0], writer, enclosingDeclaration, globalFlagsToPass | 8, typeStack); + buildSignatureDisplay(resolved.callSignatures[0], writer, enclosingDeclaration, globalFlagsToPass | 8, symbolStack); if (flags & 64) { writePunctuation(writer, 17); } @@ -10207,7 +11371,7 @@ var ts; } writeKeyword(writer, 88); writeSpace(writer); - buildSignatureDisplay(resolved.constructSignatures[0], writer, enclosingDeclaration, globalFlagsToPass | 8, typeStack); + buildSignatureDisplay(resolved.constructSignatures[0], writer, enclosingDeclaration, globalFlagsToPass | 8, symbolStack); if (flags & 64) { writePunctuation(writer, 17); } @@ -10219,7 +11383,7 @@ var ts; writer.increaseIndent(); for (var _i = 0, _a = resolved.callSignatures; _i < _a.length; _i++) { var signature = _a[_i]; - buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, typeStack); + buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, symbolStack); writePunctuation(writer, 22); writer.writeLine(); } @@ -10227,7 +11391,7 @@ var ts; var signature = _c[_b]; writeKeyword(writer, 88); writeSpace(writer); - buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, typeStack); + buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, symbolStack); writePunctuation(writer, 22); writer.writeLine(); } @@ -10236,7 +11400,7 @@ var ts; writer.writeParameter(getIndexerParameterName(resolved, 0, "x")); writePunctuation(writer, 51); writeSpace(writer); - writeKeyword(writer, 122); + writeKeyword(writer, 123); writePunctuation(writer, 19); writePunctuation(writer, 51); writeSpace(writer); @@ -10249,7 +11413,7 @@ var ts; writer.writeParameter(getIndexerParameterName(resolved, 1, "x")); writePunctuation(writer, 51); writeSpace(writer); - writeKeyword(writer, 120); + writeKeyword(writer, 121); writePunctuation(writer, 19); writePunctuation(writer, 51); writeSpace(writer); @@ -10268,7 +11432,7 @@ var ts; if (p.flags & 536870912) { writePunctuation(writer, 50); } - buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, typeStack); + buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, symbolStack); writePunctuation(writer, 22); writer.writeLine(); } @@ -10292,32 +11456,33 @@ var ts; function buildTypeParameterDisplayFromSymbol(symbol, writer, enclosingDeclaraiton, flags) { var targetSymbol = getTargetSymbol(symbol); if (targetSymbol.flags & 32 || targetSymbol.flags & 64) { - buildDisplayForTypeParametersAndDelimiters(getTypeParametersOfClassOrInterface(symbol), writer, enclosingDeclaraiton, flags); + buildDisplayForTypeParametersAndDelimiters(getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol), writer, enclosingDeclaraiton, flags); } } - function buildTypeParameterDisplay(tp, writer, enclosingDeclaration, flags, typeStack) { + function buildTypeParameterDisplay(tp, writer, enclosingDeclaration, flags, symbolStack) { appendSymbolNameOnly(tp.symbol, writer); var constraint = getConstraintOfTypeParameter(tp); if (constraint) { writeSpace(writer); writeKeyword(writer, 79); writeSpace(writer); - buildTypeDisplay(constraint, writer, enclosingDeclaration, flags, typeStack); + buildTypeDisplay(constraint, writer, enclosingDeclaration, flags, symbolStack); } } - function buildParameterDisplay(p, writer, enclosingDeclaration, flags, typeStack) { - if (ts.hasDotDotDotToken(p.valueDeclaration)) { + function buildParameterDisplay(p, writer, enclosingDeclaration, flags, symbolStack) { + var parameterNode = p.valueDeclaration; + if (ts.isRestParameter(parameterNode)) { writePunctuation(writer, 21); } appendSymbolNameOnly(p, writer); - if (ts.hasQuestionToken(p.valueDeclaration) || p.valueDeclaration.initializer) { + if (isOptionalParameter(parameterNode)) { writePunctuation(writer, 50); } writePunctuation(writer, 51); writeSpace(writer); - buildTypeDisplay(getTypeOfSymbol(p), writer, enclosingDeclaration, flags, typeStack); + buildTypeDisplay(getTypeOfSymbol(p), writer, enclosingDeclaration, flags, symbolStack); } - function buildDisplayForTypeParametersAndDelimiters(typeParameters, writer, enclosingDeclaration, flags, typeStack) { + function buildDisplayForTypeParametersAndDelimiters(typeParameters, writer, enclosingDeclaration, flags, symbolStack) { if (typeParameters && typeParameters.length) { writePunctuation(writer, 24); for (var i = 0; i < typeParameters.length; i++) { @@ -10325,12 +11490,12 @@ var ts; writePunctuation(writer, 23); writeSpace(writer); } - buildTypeParameterDisplay(typeParameters[i], writer, enclosingDeclaration, flags, typeStack); + buildTypeParameterDisplay(typeParameters[i], writer, enclosingDeclaration, flags, symbolStack); } writePunctuation(writer, 25); } } - function buildDisplayForTypeArgumentsAndDelimiters(typeParameters, mapper, writer, enclosingDeclaration, flags, typeStack) { + function buildDisplayForTypeArgumentsAndDelimiters(typeParameters, mapper, writer, enclosingDeclaration, flags, symbolStack) { if (typeParameters && typeParameters.length) { writePunctuation(writer, 24); for (var i = 0; i < typeParameters.length; i++) { @@ -10343,18 +11508,18 @@ var ts; writePunctuation(writer, 25); } } - function buildDisplayForParametersAndDelimiters(parameters, writer, enclosingDeclaration, flags, typeStack) { + function buildDisplayForParametersAndDelimiters(parameters, writer, enclosingDeclaration, flags, symbolStack) { writePunctuation(writer, 16); for (var i = 0; i < parameters.length; i++) { if (i > 0) { writePunctuation(writer, 23); writeSpace(writer); } - buildParameterDisplay(parameters[i], writer, enclosingDeclaration, flags, typeStack); + buildParameterDisplay(parameters[i], writer, enclosingDeclaration, flags, symbolStack); } writePunctuation(writer, 17); } - function buildReturnTypeDisplay(signature, writer, enclosingDeclaration, flags, typeStack) { + function buildReturnTypeDisplay(signature, writer, enclosingDeclaration, flags, symbolStack) { if (flags & 8) { writeSpace(writer); writePunctuation(writer, 32); @@ -10363,17 +11528,17 @@ var ts; writePunctuation(writer, 51); } writeSpace(writer); - buildTypeDisplay(getReturnTypeOfSignature(signature), writer, enclosingDeclaration, flags, typeStack); + buildTypeDisplay(getReturnTypeOfSignature(signature), writer, enclosingDeclaration, flags, symbolStack); } - function buildSignatureDisplay(signature, writer, enclosingDeclaration, flags, typeStack) { + function buildSignatureDisplay(signature, writer, enclosingDeclaration, flags, symbolStack) { if (signature.target && (flags & 32)) { buildDisplayForTypeArgumentsAndDelimiters(signature.target.typeParameters, signature.mapper, writer, enclosingDeclaration); } else { - buildDisplayForTypeParametersAndDelimiters(signature.typeParameters, writer, enclosingDeclaration, flags, typeStack); + buildDisplayForTypeParametersAndDelimiters(signature.typeParameters, writer, enclosingDeclaration, flags, symbolStack); } - buildDisplayForParametersAndDelimiters(signature.parameters, writer, enclosingDeclaration, flags, typeStack); - buildReturnTypeDisplay(signature, writer, enclosingDeclaration, flags, typeStack); + buildDisplayForParametersAndDelimiters(signature.parameters, writer, enclosingDeclaration, flags, symbolStack); + buildReturnTypeDisplay(signature, writer, enclosingDeclaration, flags, symbolStack); } return _displayBuilder || (_displayBuilder = { symbolToString: symbolToString, @@ -10393,12 +11558,12 @@ var ts; function isDeclarationVisible(node) { function getContainingExternalModule(node) { for (; node; node = node.parent) { - if (node.kind === 206) { + if (node.kind === 208) { if (node.name.kind === 8) { return node; } } - else if (node.kind === 228) { + else if (node.kind === 230) { return ts.isExternalModule(node) ? node : undefined; } } @@ -10441,58 +11606,58 @@ var ts; } function determineIfDeclarationIsVisible() { switch (node.kind) { - case 153: + case 155: return isDeclarationVisible(node.parent.parent); - case 199: + case 201: if (ts.isBindingPattern(node.name) && !node.name.elements.length) { return false; } - case 206: - case 202: - case 203: + case 208: case 204: - case 201: case 205: - case 209: - var parent_2 = getDeclarationContainer(node); + case 206: + case 203: + case 207: + case 211: + var parent_4 = getDeclarationContainer(node); if (!(ts.getCombinedNodeFlags(node) & 1) && - !(node.kind !== 209 && parent_2.kind !== 228 && ts.isInAmbientContext(parent_2))) { - return isGlobalSourceFile(parent_2); + !(node.kind !== 211 && parent_4.kind !== 230 && ts.isInAmbientContext(parent_4))) { + return isGlobalSourceFile(parent_4); } - return isDeclarationVisible(parent_2); - case 133: - case 132: - case 137: - case 138: - case 135: + return isDeclarationVisible(parent_4); case 134: + case 133: + case 138: + case 139: + case 136: + case 135: if (node.flags & (32 | 64)) { return false; } - case 136: - case 140: - case 139: + case 137: case 141: - case 130: - case 207: - case 143: - case 144: - case 146: + case 140: case 142: - case 147: + case 131: + case 209: + case 145: + case 146: case 148: + case 144: case 149: case 150: + case 151: + case 152: return isDeclarationVisible(node.parent); - case 211: - case 212: + case 213: case 214: + case 216: return false; - case 129: - case 228: + case 130: + case 230: return true; - case 215: + case 217: return false; default: ts.Debug.fail("isDeclarationVisible unknown: SyntaxKind: " + node.kind); @@ -10508,10 +11673,10 @@ var ts; } function collectLinkedAliases(node) { var exportSymbol; - if (node.parent && node.parent.kind === 215) { + if (node.parent && node.parent.kind === 217) { exportSymbol = resolveName(node.parent, node.text, 107455 | 793056 | 1536, ts.Diagnostics.Cannot_find_name_0, node); } - else if (node.parent.kind === 218) { + else if (node.parent.kind === 220) { exportSymbol = getTargetOfExportSpecifier(node.parent); } var result = []; @@ -10557,7 +11722,7 @@ var ts; } function getDeclarationContainer(node) { node = ts.getRootDeclaration(node); - return node.kind === 199 ? node.parent.parent.parent : node.parent; + return node.kind === 201 ? node.parent.parent.parent : node.parent; } function getTypeOfPrototypeProperty(prototype) { var classType = getDeclaredTypeOfSymbol(prototype.parent); @@ -10567,33 +11732,36 @@ var ts; var prop = getPropertyOfType(type, name); return prop ? getTypeOfSymbol(prop) : undefined; } + function isTypeAny(type) { + return type && (type.flags & 1) !== 0; + } function getTypeForBindingElement(declaration) { var pattern = declaration.parent; var parentType = getTypeForVariableLikeDeclaration(pattern.parent); if (parentType === unknownType) { return unknownType; } - if (!parentType || parentType === anyType) { + if (!parentType || isTypeAny(parentType)) { if (declaration.initializer) { return checkExpressionCached(declaration.initializer); } return parentType; } var type; - if (pattern.kind === 151) { - var name_5 = declaration.propertyName || declaration.name; - type = getTypeOfPropertyOfType(parentType, name_5.text) || - isNumericLiteralName(name_5.text) && getIndexTypeOfType(parentType, 1) || + if (pattern.kind === 153) { + var name_9 = declaration.propertyName || declaration.name; + type = getTypeOfPropertyOfType(parentType, name_9.text) || + isNumericLiteralName(name_9.text) && getIndexTypeOfType(parentType, 1) || getIndexTypeOfType(parentType, 0); if (!type) { - error(name_5, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(parentType), ts.declarationNameToString(name_5)); + error(name_9, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(parentType), ts.declarationNameToString(name_9)); return unknownType; } } else { var elementType = checkIteratedTypeOrElementType(parentType, pattern, false); if (!declaration.dotDotDotToken) { - if (elementType.flags & 1) { + if (isTypeAny(elementType)) { return elementType; } var propName = "" + ts.indexOf(pattern.elements, declaration); @@ -10617,10 +11785,10 @@ var ts; return type; } function getTypeForVariableLikeDeclaration(declaration) { - if (declaration.parent.parent.kind === 188) { + if (declaration.parent.parent.kind === 190) { return anyType; } - if (declaration.parent.parent.kind === 189) { + if (declaration.parent.parent.kind === 191) { return checkRightHandSideOfForOf(declaration.parent.parent.expression) || anyType; } if (ts.isBindingPattern(declaration.parent)) { @@ -10629,10 +11797,10 @@ var ts; if (declaration.type) { return getTypeFromTypeNode(declaration.type); } - if (declaration.kind === 130) { + if (declaration.kind === 131) { var func = declaration.parent; - if (func.kind === 138 && !ts.hasDynamicName(func)) { - var getter = ts.getDeclarationOfKind(declaration.parent.symbol, 137); + if (func.kind === 139 && !ts.hasDynamicName(func)) { + var getter = ts.getDeclarationOfKind(declaration.parent.symbol, 138); if (getter) { return getReturnTypeOfSignature(getSignatureFromDeclaration(getter)); } @@ -10645,7 +11813,7 @@ var ts; if (declaration.initializer) { return checkExpressionCached(declaration.initializer); } - if (declaration.kind === 226) { + if (declaration.kind === 228) { return checkIdentifier(declaration.name); } return undefined; @@ -10674,7 +11842,7 @@ var ts; var hasSpreadElement = false; var elementTypes = []; ts.forEach(pattern.elements, function (e) { - elementTypes.push(e.kind === 176 || e.dotDotDotToken ? anyType : getTypeFromBindingElement(e)); + elementTypes.push(e.kind === 178 || e.dotDotDotToken ? anyType : getTypeFromBindingElement(e)); if (e.dotDotDotToken) { hasSpreadElement = true; } @@ -10689,7 +11857,7 @@ var ts; return createTupleType(elementTypes); } function getTypeFromBindingPattern(pattern) { - return pattern.kind === 151 + return pattern.kind === 153 ? getTypeFromObjectBindingPattern(pattern) : getTypeFromArrayBindingPattern(pattern); } @@ -10699,7 +11867,7 @@ var ts; if (reportErrors) { reportErrorsFromWidening(declaration, type); } - return declaration.kind !== 225 ? getWidenedType(type) : type; + return declaration.kind !== 227 ? getWidenedType(type) : type; } if (ts.isBindingPattern(declaration.name)) { return getTypeFromBindingPattern(declaration.name); @@ -10707,7 +11875,7 @@ var ts; type = declaration.dotDotDotToken ? anyArrayType : anyType; if (reportErrors && compilerOptions.noImplicitAny) { var root = ts.getRootDeclaration(declaration); - if (!isPrivateWithinAmbient(root) && !(root.kind === 130 && isPrivateWithinAmbient(root.parent))) { + if (!isPrivateWithinAmbient(root) && !(root.kind === 131 && isPrivateWithinAmbient(root.parent))) { reportImplicitAnyError(declaration, type); } } @@ -10720,10 +11888,10 @@ var ts; return links.type = getTypeOfPrototypeProperty(symbol); } var declaration = symbol.valueDeclaration; - if (declaration.parent.kind === 224) { + if (declaration.parent.kind === 226) { return links.type = anyType; } - if (declaration.kind === 215) { + if (declaration.kind === 217) { return links.type = checkExpression(declaration.expression); } if (!pushTypeResolution(symbol)) { @@ -10738,7 +11906,7 @@ var ts; else { type = anyType; if (compilerOptions.noImplicitAny) { - error(symbol.valueDeclaration, ts.Diagnostics._0_implicitly_has_type_any_because_it_is_does_not_have_a_type_annotation_and_is_referenced_directly_or_indirectly_in_its_own_initializer, symbolToString(symbol)); + 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)); } } } @@ -10751,7 +11919,7 @@ var ts; } function getAnnotatedAccessorType(accessor) { if (accessor) { - if (accessor.kind === 137) { + if (accessor.kind === 138) { return accessor.type && getTypeFromTypeNode(accessor.type); } else { @@ -10767,8 +11935,8 @@ var ts; if (!pushTypeResolution(symbol)) { return unknownType; } - var getter = ts.getDeclarationOfKind(symbol, 137); - var setter = ts.getDeclarationOfKind(symbol, 138); + var getter = ts.getDeclarationOfKind(symbol, 138); + var setter = ts.getDeclarationOfKind(symbol, 139); var type; var getterReturnType = getAnnotatedAccessorType(getter); if (getterReturnType) { @@ -10794,7 +11962,7 @@ var ts; if (!popTypeResolution()) { type = anyType; if (compilerOptions.noImplicitAny) { - var getter_1 = ts.getDeclarationOfKind(symbol, 137); + var getter_1 = ts.getDeclarationOfKind(symbol, 138); 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)); } } @@ -10864,74 +12032,156 @@ var ts; return target === checkBase || ts.forEach(getBaseTypes(target), check); } } - function getTypeParametersOfClassOrInterface(symbol) { - var result; - ts.forEach(symbol.declarations, function (node) { - if (node.kind === 203 || node.kind === 202) { - var declaration = node; - if (declaration.typeParameters && declaration.typeParameters.length) { - ts.forEach(declaration.typeParameters, function (node) { - var tp = getDeclaredTypeOfTypeParameter(getSymbolOfNode(node)); - if (!result) { - result = [tp]; - } - else if (!ts.contains(result, tp)) { - result.push(tp); - } - }); + function appendTypeParameters(typeParameters, declarations) { + for (var _i = 0; _i < declarations.length; _i++) { + var declaration = declarations[_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 === 204 || node.kind === 203 || + node.kind === 165 || node.kind === 136 || + node.kind === 166) { + var declarations = node.typeParameters; + if (declarations) { + return appendTypeParameters(appendOuterTypeParameters(typeParameters, node), declarations); } } - }); + } + } + function getOuterTypeParametersOfClassOrInterface(symbol) { + var kind = symbol.flags & 32 ? 204 : 205; + return appendOuterTypeParameters(undefined, ts.getDeclarationOfKind(symbol, kind)); + } + function getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol) { + var result; + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var node = _a[_i]; + if (node.kind === 205 || node.kind === 204 || node.kind === 206) { + var declaration = node; + if (declaration.typeParameters) { + result = appendTypeParameters(result, declaration.typeParameters); + } + } + } return result; } + function getTypeParametersOfClassOrInterface(symbol) { + return ts.concatenate(getOuterTypeParametersOfClassOrInterface(symbol), getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol)); + } + function isConstructorType(type) { + return type.flags & 48128 && getSignaturesOfType(type, 1).length > 0; + } + function getBaseTypeNodeOfClass(type) { + return ts.getClassExtendsHeritageClauseElement(type.symbol.valueDeclaration); + } + function getConstructorsForTypeArguments(type, typeArgumentNodes) { + var typeArgCount = typeArgumentNodes ? typeArgumentNodes.length : 0; + return ts.filter(getSignaturesOfType(type, 1), function (sig) { return (sig.typeParameters ? sig.typeParameters.length : 0) === typeArgCount; }); + } + function getInstantiatedConstructorsForTypeArguments(type, typeArgumentNodes) { + var signatures = getConstructorsForTypeArguments(type, typeArgumentNodes); + if (typeArgumentNodes) { + var typeArguments = ts.map(typeArgumentNodes, getTypeFromTypeNode); + signatures = ts.map(signatures, function (sig) { return getSignatureInstantiation(sig, typeArguments); }); + } + return signatures; + } + function getBaseConstructorTypeOfClass(type) { + if (!type.resolvedBaseConstructorType) { + var baseTypeNode = getBaseTypeNodeOfClass(type); + if (!baseTypeNode) { + return type.resolvedBaseConstructorType = undefinedType; + } + if (!pushTypeResolution(type)) { + return unknownType; + } + var baseConstructorType = checkExpression(baseTypeNode.expression); + if (baseConstructorType.flags & 48128) { + resolveObjectOrUnionTypeMembers(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 !== unknownType && baseConstructorType !== nullType && !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) { - var typeWithBaseTypes = type; - if (!typeWithBaseTypes.baseTypes) { + if (!type.resolvedBaseTypes) { if (type.symbol.flags & 32) { - resolveBaseTypesOfClass(typeWithBaseTypes); + resolveBaseTypesOfClass(type); } else if (type.symbol.flags & 64) { - resolveBaseTypesOfInterface(typeWithBaseTypes); + resolveBaseTypesOfInterface(type); } else { ts.Debug.fail("type must be class or interface"); } } - return typeWithBaseTypes.baseTypes; + return type.resolvedBaseTypes; } function resolveBaseTypesOfClass(type) { - type.baseTypes = []; - var declaration = ts.getDeclarationOfKind(type.symbol, 202); - var baseTypeNode = ts.getClassExtendsHeritageClauseElement(declaration); - if (baseTypeNode) { - var baseType = getTypeFromTypeNode(baseTypeNode); - if (baseType !== unknownType) { - if (getTargetType(baseType).flags & 1024) { - if (type !== baseType && !hasBaseType(baseType, type)) { - type.baseTypes.push(baseType); - } - else { - error(declaration, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, undefined, 1)); - } - } - else { - error(baseTypeNode, ts.Diagnostics.A_class_may_only_extend_another_class); - } - } + type.resolvedBaseTypes = emptyArray; + var baseContructorType = getBaseConstructorTypeOfClass(type); + if (!(baseContructorType.flags & 48128)) { + return; } + var baseTypeNode = getBaseTypeNodeOfClass(type); + var baseType; + if (baseContructorType.symbol && baseContructorType.symbol.flags & 32) { + baseType = getTypeFromClassOrInterfaceReference(baseTypeNode, baseContructorType.symbol); + } + else { + var constructors = getInstantiatedConstructorsForTypeArguments(baseContructorType, baseTypeNode.typeArguments); + if (!constructors.length) { + error(baseTypeNode.expression, ts.Diagnostics.No_base_constructor_has_the_specified_number_of_type_arguments); + return; + } + baseType = getReturnTypeOfSignature(constructors[0]); + } + if (baseType === unknownType) { + return; + } + if (!(getTargetType(baseType).flags & (1024 | 2048))) { + 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(type.symbol.valueDeclaration, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, undefined, 1)); + return; + } + type.resolvedBaseTypes = [baseType]; } function resolveBaseTypesOfInterface(type) { - type.baseTypes = []; + type.resolvedBaseTypes = []; for (var _i = 0, _a = type.symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (declaration.kind === 203 && ts.getInterfaceBaseTypeNodes(declaration)) { + if (declaration.kind === 205 && 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 (getTargetType(baseType).flags & (1024 | 2048)) { if (type !== baseType && !hasBaseType(baseType, type)) { - type.baseTypes.push(baseType); + type.resolvedBaseTypes.push(baseType); } else { error(declaration, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, undefined, 1)); @@ -10950,10 +12200,13 @@ var ts; if (!links.declaredType) { var kind = symbol.flags & 32 ? 1024 : 2048; var type = links.declaredType = createObjectType(kind, symbol); - var typeParameters = getTypeParametersOfClassOrInterface(symbol); - if (typeParameters) { + var outerTypeParameters = getOuterTypeParametersOfClassOrInterface(symbol); + var localTypeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); + if (outerTypeParameters || localTypeParameters) { type.flags |= 4096; - type.typeParameters = typeParameters; + type.typeParameters = ts.concatenate(outerTypeParameters, localTypeParameters); + type.outerTypeParameters = outerTypeParameters; + type.localTypeParameters = localTypeParameters; type.instantiations = {}; type.instantiations[getTypeListId(type.typeParameters)] = type; type.target = type; @@ -10968,9 +12221,16 @@ var ts; if (!pushTypeResolution(links)) { return unknownType; } - var declaration = ts.getDeclarationOfKind(symbol, 204); + var declaration = ts.getDeclarationOfKind(symbol, 206); var type = getTypeFromTypeNode(declaration.type); - if (!popTypeResolution()) { + if (popTypeResolution()) { + links.typeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); + if (links.typeParameters) { + links.instantiations = {}; + links.instantiations[getTypeListId(links.typeParameters)] = type; + } + } + else { type = unknownType; error(declaration.name, ts.Diagnostics.Type_alias_0_circularly_references_itself, symbolToString(symbol)); } @@ -10992,7 +12252,7 @@ var ts; if (!links.declaredType) { var type = createType(512); type.symbol = symbol; - if (!ts.getDeclarationOfKind(symbol, 129).constraint) { + if (!ts.getDeclarationOfKind(symbol, 130).constraint) { type.constraint = noConstraintType; } links.declaredType = type; @@ -11107,34 +12367,42 @@ var ts; }); setObjectTypeMembers(type, members, callSignatures, constructSignatures, stringIndexType, numberIndexType); } - function createSignature(declaration, typeParameters, parameters, resolvedReturnType, minArgumentCount, hasRestParameter, hasStringLiterals) { + function createSignature(declaration, typeParameters, parameters, resolvedReturnType, typePredicate, minArgumentCount, hasRestParameter, hasStringLiterals) { var sig = new Signature(checker); sig.declaration = declaration; sig.typeParameters = typeParameters; sig.parameters = parameters; sig.resolvedReturnType = resolvedReturnType; + sig.typePredicate = typePredicate; sig.minArgumentCount = minArgumentCount; sig.hasRestParameter = hasRestParameter; sig.hasStringLiterals = hasStringLiterals; return sig; } function cloneSignature(sig) { - return createSignature(sig.declaration, sig.typeParameters, sig.parameters, sig.resolvedReturnType, sig.minArgumentCount, sig.hasRestParameter, sig.hasStringLiterals); + return createSignature(sig.declaration, sig.typeParameters, sig.parameters, sig.resolvedReturnType, sig.typePredicate, sig.minArgumentCount, sig.hasRestParameter, sig.hasStringLiterals); } function getDefaultConstructSignatures(classType) { - var baseTypes = getBaseTypes(classType); - if (baseTypes.length) { - var baseType = baseTypes[0]; - var baseSignatures = getSignaturesOfType(getTypeOfSymbol(baseType.symbol), 1); - return ts.map(baseSignatures, function (baseSignature) { - var signature = baseType.flags & 4096 ? - getSignatureInstantiation(baseSignature, baseType.typeArguments) : cloneSignature(baseSignature); - signature.typeParameters = classType.typeParameters; - signature.resolvedReturnType = classType; - return signature; - }); + if (!getBaseTypes(classType).length) { + return [createSignature(undefined, classType.localTypeParameters, emptyArray, classType, undefined, 0, false, false)]; } - return [createSignature(undefined, classType.typeParameters, emptyArray, classType, 0, false, false)]; + var baseConstructorType = getBaseConstructorTypeOfClass(classType); + var baseSignatures = getSignaturesOfType(baseConstructorType, 1); + var baseTypeNode = getBaseTypeNodeOfClass(classType); + var typeArguments = ts.map(baseTypeNode.typeArguments, getTypeFromTypeNode); + var typeArgCount = typeArguments ? typeArguments.length : 0; + var result = []; + for (var _i = 0; _i < baseSignatures.length; _i++) { + var baseSig = baseSignatures[_i]; + var typeParamCount = baseSig.typeParameters ? baseSig.typeParameters.length : 0; + if (typeParamCount === typeArgCount) { + var sig = typeParamCount ? getSignatureInstantiation(baseSig, typeArguments) : cloneSignature(baseSig); + sig.typeParameters = classType.localTypeParameters; + sig.resolvedReturnType = classType; + result.push(sig); + } + } + return result; } function createTupleTypeMemberSymbols(memberTypes) { var members = {}; @@ -11233,10 +12501,10 @@ var ts; if (!constructSignatures.length) { constructSignatures = getDefaultConstructSignatures(classType); } - var baseTypes = getBaseTypes(classType); - if (baseTypes.length) { + var baseConstructorType = getBaseConstructorTypeOfClass(classType); + if (baseConstructorType.flags & 48128) { members = createSymbolTable(getNamedMembers(members)); - addInheritedMembers(members, getPropertiesOfObjectType(getTypeOfSymbol(baseTypes[0].symbol))); + addInheritedMembers(members, getPropertiesOfObjectType(baseConstructorType)); } } stringIndexType = undefined; @@ -11316,7 +12584,7 @@ var ts; else if (type.flags & 8) { type = globalBooleanType; } - else if (type.flags & 1048576) { + else if (type.flags & 2097152) { type = globalESSymbolType; } return type; @@ -11436,11 +12704,14 @@ var ts; } return result; } + function isOptionalParameter(node) { + return ts.hasQuestionToken(node) || !!node.initializer; + } function getSignatureFromDeclaration(declaration) { var links = getNodeLinks(declaration); if (!links.resolvedSignature) { - var classType = declaration.kind === 136 ? getDeclaredTypeOfClassOrInterface(declaration.parent.symbol) : undefined; - var typeParameters = classType ? classType.typeParameters : + var classType = declaration.kind === 137 ? getDeclaredTypeOfClassOrInterface(declaration.parent.symbol) : undefined; + var typeParameters = classType ? classType.localTypeParameters : declaration.typeParameters ? getTypeParametersFromDeclaration(declaration.typeParameters) : undefined; var parameters = []; var hasStringLiterals = false; @@ -11461,22 +12732,31 @@ var ts; minArgumentCount = declaration.parameters.length; } var returnType; + var typePredicate; if (classType) { returnType = classType; } else if (declaration.type) { returnType = getTypeFromTypeNode(declaration.type); + if (declaration.type.kind === 143) { + var typePredicateNode = declaration.type; + typePredicate = { + parameterName: typePredicateNode.parameterName ? typePredicateNode.parameterName.text : undefined, + parameterIndex: typePredicateNode.parameterName ? getTypePredicateParameterIndex(declaration.parameters, typePredicateNode.parameterName) : undefined, + type: getTypeFromTypeNode(typePredicateNode.type) + }; + } } else { - if (declaration.kind === 137 && !ts.hasDynamicName(declaration)) { - var setter = ts.getDeclarationOfKind(declaration.symbol, 138); + if (declaration.kind === 138 && !ts.hasDynamicName(declaration)) { + var setter = ts.getDeclarationOfKind(declaration.symbol, 139); returnType = getAnnotatedAccessorType(setter); } if (!returnType && ts.nodeIsMissing(declaration.body)) { returnType = anyType; } } - links.resolvedSignature = createSignature(declaration, typeParameters, parameters, returnType, minArgumentCount, ts.hasRestParameters(declaration), hasStringLiterals); + links.resolvedSignature = createSignature(declaration, typeParameters, parameters, returnType, typePredicate, minArgumentCount, ts.hasRestParameter(declaration), hasStringLiterals); } return links.resolvedSignature; } @@ -11487,19 +12767,19 @@ var ts; for (var i = 0, len = symbol.declarations.length; i < len; i++) { var node = symbol.declarations[i]; switch (node.kind) { - case 143: - case 144: - case 201: - case 135: - case 134: + case 145: + case 146: + case 203: case 136: - case 139: + case 135: + case 137: case 140: case 141: - case 137: + case 142: case 138: - case 163: - case 164: + case 139: + case 165: + case 166: if (i > 0 && node.body) { var previous = symbol.declarations[i - 1]; if (node.parent === previous.parent && node.kind === previous.kind && node.pos === previous.end) { @@ -11569,8 +12849,8 @@ var ts; } function getOrCreateTypeFromSignature(signature) { if (!signature.isolatedSignatureType) { - var isConstructor = signature.declaration.kind === 136 || signature.declaration.kind === 140; - var type = createObjectType(32768 | 65536); + var isConstructor = signature.declaration.kind === 137 || signature.declaration.kind === 141; + var type = createObjectType(32768 | 131072); type.members = emptySymbols; type.properties = emptyArray; type.callSignatures = !isConstructor ? [signature] : emptyArray; @@ -11583,7 +12863,7 @@ var ts; return symbol.members["__index"]; } function getIndexDeclarationOfSymbol(symbol, kind) { - var syntaxKind = kind === 1 ? 120 : 122; + var syntaxKind = kind === 1 ? 121 : 123; var indexSymbol = getIndexSymbol(symbol); if (indexSymbol) { var len = indexSymbol.declarations.length; @@ -11613,11 +12893,14 @@ var ts; type.constraint = targetConstraint ? instantiateType(targetConstraint, type.mapper) : noConstraintType; } else { - type.constraint = getTypeFromTypeNode(ts.getDeclarationOfKind(type.symbol, 129).constraint); + type.constraint = getTypeFromTypeNode(ts.getDeclarationOfKind(type.symbol, 130).constraint); } } return type.constraint === noConstraintType ? undefined : type.constraint; } + function getParentSymbolOfTypeParameter(typeParameter) { + return getSymbolOfNode(ts.getDeclarationOfKind(typeParameter.symbol, 130).parent); + } function getTypeListId(types) { switch (types.length) { case 1: @@ -11641,7 +12924,7 @@ var ts; var type = types[_i]; result |= type.flags; } - return result & 786432; + return result & 1572864; } function createTypeReference(target, typeArguments) { var id = getTypeListId(typeArguments); @@ -11663,18 +12946,18 @@ var ts; while (!ts.forEach(typeParameterSymbol.declarations, function (d) { return d.parent === currentNode.parent; })) { currentNode = currentNode.parent; } - links.isIllegalTypeReferenceInConstraint = currentNode.kind === 129; + links.isIllegalTypeReferenceInConstraint = currentNode.kind === 130; return links.isIllegalTypeReferenceInConstraint; } function checkTypeParameterHasIllegalReferencesInConstraint(typeParameter) { var typeParameterSymbol; function check(n) { - if (n.kind === 142 && n.typeName.kind === 65) { + if (n.kind === 144 && n.typeName.kind === 65) { var links = getNodeLinks(n); if (links.isIllegalTypeReferenceInConstraint === undefined) { var symbol = resolveName(typeParameter, n.typeName.text, 793056, undefined, undefined); if (symbol && (symbol.flags & 262144)) { - links.isIllegalTypeReferenceInConstraint = ts.forEach(symbol.declarations, function (d) { return d.parent == typeParameter.parent; }); + links.isIllegalTypeReferenceInConstraint = ts.forEach(symbol.declarations, function (d) { return d.parent === typeParameter.parent; }); } } if (links.isIllegalTypeReferenceInConstraint) { @@ -11688,48 +12971,71 @@ var ts; check(typeParameter.constraint); } } - function getTypeFromTypeReferenceOrExpressionWithTypeArguments(node) { + function getTypeFromClassOrInterfaceReference(node, symbol) { + var type = getDeclaredTypeOfSymbol(symbol); + var typeParameters = type.localTypeParameters; + if (typeParameters) { + if (!node.typeArguments || node.typeArguments.length !== typeParameters.length) { + error(node, ts.Diagnostics.Generic_type_0_requires_1_type_argument_s, typeToString(type, undefined, 1), typeParameters.length); + return unknownType; + } + return createTypeReference(type, ts.concatenate(type.outerTypeParameters, ts.map(node.typeArguments, getTypeFromTypeNode))); + } + if (node.typeArguments) { + error(node, ts.Diagnostics.Type_0_is_not_generic, typeToString(type)); + return unknownType; + } + return type; + } + function getTypeFromTypeAliasReference(node, symbol) { + var type = getDeclaredTypeOfSymbol(symbol); + var links = getSymbolLinks(symbol); + var typeParameters = links.typeParameters; + if (typeParameters) { + if (!node.typeArguments || node.typeArguments.length !== typeParameters.length) { + error(node, ts.Diagnostics.Generic_type_0_requires_1_type_argument_s, symbolToString(symbol), typeParameters.length); + return unknownType; + } + var typeArguments = ts.map(node.typeArguments, getTypeFromTypeNode); + var id = getTypeListId(typeArguments); + return links.instantiations[id] || (links.instantiations[id] = instantiateType(type, createTypeMapper(typeParameters, typeArguments))); + } + if (node.typeArguments) { + error(node, ts.Diagnostics.Type_0_is_not_generic, symbolToString(symbol)); + return unknownType; + } + return type; + } + function getTypeFromNonGenericTypeReference(node, symbol) { + if (symbol.flags & 262144 && isTypeParameterReferenceIllegalInConstraint(node, symbol)) { + return unknownType; + } + if (node.typeArguments) { + error(node, ts.Diagnostics.Type_0_is_not_generic, symbolToString(symbol)); + return unknownType; + } + return getDeclaredTypeOfSymbol(symbol); + } + function getTypeFromTypeReference(node) { var links = getNodeLinks(node); if (!links.resolvedType) { - var type; - if (node.kind !== 177 || ts.isSupportedExpressionWithTypeArguments(node)) { - var typeNameOrExpression = node.kind === 142 - ? node.typeName - : node.expression; - var symbol = resolveEntityName(typeNameOrExpression, 793056); - if (symbol) { - if ((symbol.flags & 262144) && isTypeParameterReferenceIllegalInConstraint(node, symbol)) { - type = unknownType; - } - else { - type = getDeclaredTypeOfSymbol(symbol); - if (type.flags & (1024 | 2048) && type.flags & 4096) { - var typeParameters = type.typeParameters; - if (node.typeArguments && node.typeArguments.length === typeParameters.length) { - type = createTypeReference(type, ts.map(node.typeArguments, getTypeFromTypeNode)); - } - else { - error(node, ts.Diagnostics.Generic_type_0_requires_1_type_argument_s, typeToString(type, undefined, 1), typeParameters.length); - type = undefined; - } - } - else { - if (node.typeArguments) { - error(node, ts.Diagnostics.Type_0_is_not_generic, typeToString(type)); - type = undefined; - } - } - } - } - } - links.resolvedType = type || unknownType; + var typeNameOrExpression = node.kind === 144 ? node.typeName : + ts.isSupportedExpressionWithTypeArguments(node) ? node.expression : + undefined; + var symbol = typeNameOrExpression && resolveEntityName(typeNameOrExpression, 793056) || unknownSymbol; + var type = symbol === unknownSymbol ? unknownType : + symbol.flags & (32 | 64) ? getTypeFromClassOrInterfaceReference(node, symbol) : + symbol.flags & 524288 ? getTypeFromTypeAliasReference(node, symbol) : + getTypeFromNonGenericTypeReference(node, symbol); + links.resolvedSymbol = symbol; + links.resolvedType = type; } return links.resolvedType; } function getTypeFromTypeQueryNode(node) { var links = getNodeLinks(node); if (!links.resolvedType) { - links.resolvedType = getWidenedType(checkExpressionOrQualifiedName(node.exprName)); + links.resolvedType = getWidenedType(checkExpression(node.exprName)); } return links.resolvedType; } @@ -11739,24 +13045,24 @@ var ts; for (var _i = 0; _i < declarations.length; _i++) { var declaration = declarations[_i]; switch (declaration.kind) { - case 202: - case 203: + case 204: case 205: + case 207: return declaration; } } } if (!symbol) { - return emptyObjectType; + return arity ? emptyGenericType : emptyObjectType; } var type = getDeclaredTypeOfSymbol(symbol); if (!(type.flags & 48128)) { error(getTypeDeclaration(symbol), ts.Diagnostics.Global_type_0_must_be_a_class_or_interface_type, symbol.name); - return emptyObjectType; + return arity ? emptyGenericType : emptyObjectType; } if ((type.typeParameters ? type.typeParameters.length : 0) !== arity) { error(getTypeDeclaration(symbol), ts.Diagnostics.Global_type_0_must_have_1_type_parameter_s, symbol.name, arity); - return emptyObjectType; + return arity ? emptyGenericType : emptyObjectType; } return type; } @@ -11776,12 +13082,17 @@ var ts; function getGlobalESSymbolConstructorSymbol() { return globalESSymbolConstructorSymbol || (globalESSymbolConstructorSymbol = getGlobalValueSymbol("Symbol")); } + function createTypeFromGenericGlobalType(genericGlobalType, elementType) { + return genericGlobalType !== emptyGenericType ? createTypeReference(genericGlobalType, [elementType]) : emptyObjectType; + } function createIterableType(elementType) { - return globalIterableType !== emptyObjectType ? createTypeReference(globalIterableType, [elementType]) : emptyObjectType; + return createTypeFromGenericGlobalType(globalIterableType, elementType); + } + function createIterableIteratorType(elementType) { + return createTypeFromGenericGlobalType(globalIterableIteratorType, elementType); } function createArrayType(elementType) { - var arrayType = globalArrayType || getDeclaredTypeOfSymbol(globalArraySymbol); - return arrayType !== emptyObjectType ? createTypeReference(arrayType, [elementType]) : emptyObjectType; + return createTypeFromGenericGlobalType(globalArrayType, elementType); } function getTypeFromArrayTypeNode(node) { var links = getNodeLinks(node); @@ -11836,13 +13147,7 @@ var ts; } return false; } - var removeSubtypesStack = []; function removeSubtypes(types) { - var typeListId = getTypeListId(types); - if (removeSubtypesStack.lastIndexOf(typeListId) >= 0) { - return; - } - removeSubtypesStack.push(typeListId); var i = types.length; while (i > 0) { i--; @@ -11850,12 +13155,11 @@ var ts; types.splice(i, 1); } } - removeSubtypesStack.pop(); } - function containsAnyType(types) { + function containsTypeAny(types) { for (var _i = 0; _i < types.length; _i++) { var type = types[_i]; - if (type.flags & 1) { + if (isTypeAny(type)) { return true; } } @@ -11877,7 +13181,7 @@ var ts; var sortedTypes = []; addTypesToSortedSet(sortedTypes, types); if (noSubtypeReduction) { - if (containsAnyType(sortedTypes)) { + if (containsTypeAny(sortedTypes)) { return anyType; } removeAllButLast(sortedTypes, undefinedType); @@ -11900,7 +13204,14 @@ var ts; } function getReducedTypeOfUnionType(type) { if (!type.reducedType) { - type.reducedType = getUnionType(type.types, false); + type.reducedType = circularType; + var reducedType = getUnionType(type.types, false); + if (type.reducedType === circularType) { + type.reducedType = reducedType; + } + } + else if (type.reducedType === circularType) { + type.reducedType = type; } return type.reducedType; } @@ -11937,38 +13248,40 @@ var ts; switch (node.kind) { case 112: return anyType; - case 122: + case 123: return stringType; - case 120: + case 121: return numberType; case 113: return booleanType; - case 123: + case 124: return esSymbolType; case 99: return voidType; case 8: return getTypeFromStringLiteral(node); - case 142: - return getTypeFromTypeReferenceOrExpressionWithTypeArguments(node); - case 177: - return getTypeFromTypeReferenceOrExpressionWithTypeArguments(node); - case 145: - return getTypeFromTypeQueryNode(node); - case 147: - return getTypeFromArrayTypeNode(node); - case 148: - return getTypeFromTupleTypeNode(node); - case 149: - return getTypeFromUnionTypeNode(node); - case 150: - return getTypeFromTypeNode(node.type); - case 143: case 144: + return getTypeFromTypeReference(node); + case 143: + return booleanType; + case 179: + return getTypeFromTypeReference(node); + case 147: + return getTypeFromTypeQueryNode(node); + case 149: + return getTypeFromArrayTypeNode(node); + case 150: + return getTypeFromTupleTypeNode(node); + case 151: + return getTypeFromUnionTypeNode(node); + case 152: + return getTypeFromTypeNode(node.type); + case 145: case 146: + case 148: return getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node); case 65: - case 127: + case 128: var symbol = getSymbolInfo(node); return symbol && getDeclaredTypeOfSymbol(symbol); default: @@ -12058,11 +13371,19 @@ var ts; } function instantiateSignature(signature, mapper, eraseTypeParameters) { var freshTypeParameters; + var freshTypePredicate; if (signature.typeParameters && !eraseTypeParameters) { freshTypeParameters = instantiateList(signature.typeParameters, mapper, instantiateTypeParameter); mapper = combineTypeMappers(createTypeMapper(signature.typeParameters, freshTypeParameters), mapper); } - var result = createSignature(signature.declaration, freshTypeParameters, instantiateList(signature.parameters, mapper, instantiateSymbol), signature.resolvedReturnType ? instantiateType(signature.resolvedReturnType, mapper) : undefined, signature.minArgumentCount, signature.hasRestParameter, signature.hasStringLiterals); + if (signature.typePredicate) { + freshTypePredicate = { + parameterName: signature.typePredicate.parameterName, + parameterIndex: signature.typePredicate.parameterIndex, + type: instantiateType(signature.typePredicate.type, mapper) + }; + } + var result = createSignature(signature.declaration, freshTypeParameters, instantiateList(signature.parameters, mapper, instantiateSymbol), signature.resolvedReturnType ? instantiateType(signature.resolvedReturnType, mapper) : undefined, freshTypePredicate, signature.minArgumentCount, signature.hasRestParameter, signature.hasStringLiterals); result.target = signature; result.mapper = mapper; return result; @@ -12084,7 +13405,7 @@ var ts; return result; } function instantiateAnonymousType(type, mapper) { - var result = createObjectType(32768, type.symbol); + var result = createObjectType(32768 | 65536, type.symbol); result.properties = instantiateList(getPropertiesOfObjectType(type), mapper, instantiateSymbol); result.members = createSymbolTable(result.properties); result.callSignatures = instantiateList(getSignaturesOfType(type, 0), mapper, instantiateSignature); @@ -12103,7 +13424,7 @@ var ts; return mapper(type); } if (type.flags & 32768) { - return type.symbol && type.symbol.flags & (16 | 8192 | 2048 | 4096) ? + return type.symbol && type.symbol.flags & (16 | 8192 | 32 | 2048 | 4096) ? instantiateAnonymousType(type, mapper) : type; } if (type.flags & 4096) { @@ -12119,27 +13440,27 @@ var ts; return type; } function isContextSensitive(node) { - ts.Debug.assert(node.kind !== 135 || ts.isObjectLiteralMethod(node)); + ts.Debug.assert(node.kind !== 136 || ts.isObjectLiteralMethod(node)); switch (node.kind) { - case 163: - case 164: + case 165: + case 166: return isContextSensitiveFunctionLikeDeclaration(node); - case 155: + case 157: return ts.forEach(node.properties, isContextSensitive); - case 154: + case 156: return ts.forEach(node.elements, isContextSensitive); - case 171: + case 173: return isContextSensitive(node.whenTrue) || isContextSensitive(node.whenFalse); - case 170: + case 172: return node.operatorToken.kind === 49 && (isContextSensitive(node.left) || isContextSensitive(node.right)); - case 225: + case 227: return isContextSensitive(node.initializer); + case 136: case 135: - case 134: return isContextSensitiveFunctionLikeDeclaration(node); - case 162: + case 164: return isContextSensitive(node.expression); } return false; @@ -12147,23 +13468,20 @@ var ts; function isContextSensitiveFunctionLikeDeclaration(node) { return !node.typeParameters && node.parameters.length && !ts.forEach(node.parameters, function (p) { return p.type; }); } - function getTypeWithoutConstructors(type) { + function getTypeWithoutSignatures(type) { if (type.flags & 48128) { var resolved = resolveObjectOrUnionTypeMembers(type); if (resolved.constructSignatures.length) { var result = createObjectType(32768, type.symbol); result.members = resolved.members; result.properties = resolved.properties; - result.callSignatures = resolved.callSignatures; + result.callSignatures = emptyArray; result.constructSignatures = emptyArray; type = result; } } return type; } - var subtypeRelation = {}; - var assignableRelation = {}; - var identityRelation = {}; function isTypeIdenticalTo(source, target) { return checkTypeRelatedTo(source, target, identityRelation, undefined); } @@ -12221,7 +13539,7 @@ var ts; if (source === target) return -1; if (relation !== identityRelation) { - if (target.flags & 1) + if (isTypeAny(target)) return -1; if (source === undefinedType) return -1; @@ -12232,7 +13550,7 @@ var ts; if (source.flags & 256 && target === stringType) return -1; if (relation === assignableRelation) { - if (source.flags & 1) + if (isTypeAny(source)) return -1; if (source === numberType && target.flags & 128) return -1; @@ -12414,9 +13732,9 @@ var ts; maybeStack[depth][id] = 1; depth++; var saveExpandingFlags = expandingFlags; - if (!(expandingFlags & 1) && isDeeplyNestedGeneric(source, sourceStack)) + if (!(expandingFlags & 1) && isDeeplyNestedGeneric(source, sourceStack, depth)) expandingFlags |= 1; - if (!(expandingFlags & 2) && isDeeplyNestedGeneric(target, targetStack)) + if (!(expandingFlags & 2) && isDeeplyNestedGeneric(target, targetStack, depth)) expandingFlags |= 2; var result; if (expandingFlags === 3) { @@ -12449,28 +13767,13 @@ var ts; } return result; } - function isDeeplyNestedGeneric(type, stack) { - if (type.flags & 4096 && depth >= 10) { - var target_1 = type.target; - var count = 0; - for (var i = 0; i < depth; i++) { - var t = stack[i]; - if (t.flags & 4096 && t.target === target_1) { - count++; - if (count >= 10) - return true; - } - } - } - return false; - } function propertiesRelatedTo(source, target, reportErrors) { if (relation === identityRelation) { return propertiesIdenticalTo(source, target); } var result = -1; var properties = getPropertiesOfObjectType(target); - var requireOptionalProperties = relation === subtypeRelation && !(source.flags & 131072); + var requireOptionalProperties = relation === subtypeRelation && !(source.flags & 262144); for (var _i = 0; _i < properties.length; _i++) { var targetProp = properties[_i]; var sourceProp = getPropertyOfType(source, targetProp.name); @@ -12569,11 +13872,11 @@ var ts; var saveErrorInfo = errorInfo; outer: for (var _i = 0; _i < targetSignatures.length; _i++) { var t = targetSignatures[_i]; - if (!t.hasStringLiterals || target.flags & 65536) { + if (!t.hasStringLiterals || target.flags & 131072) { var localErrors = reportErrors; for (var _a = 0; _a < sourceSignatures.length; _a++) { var s = sourceSignatures[_a]; - if (!s.hasStringLiterals || source.flags & 65536) { + if (!s.hasStringLiterals || source.flags & 131072) { var related = signatureRelatedTo(s, t, localErrors); if (related) { result &= related; @@ -12634,6 +13937,33 @@ var ts; } result &= related; } + if (source.typePredicate && target.typePredicate) { + var hasDifferentParameterIndex = source.typePredicate.parameterIndex !== target.typePredicate.parameterIndex; + var hasDifferentTypes; + if (hasDifferentParameterIndex || + (hasDifferentTypes = !isTypeIdenticalTo(source.typePredicate.type, target.typePredicate.type))) { + if (reportErrors) { + var sourceParamText = source.typePredicate.parameterName; + var targetParamText = target.typePredicate.parameterName; + var sourceTypeText = typeToString(source.typePredicate.type); + var targetTypeText = typeToString(target.typePredicate.type); + if (hasDifferentParameterIndex) { + reportError(ts.Diagnostics.Parameter_0_is_not_in_the_same_position_as_parameter_1, sourceParamText, targetParamText); + } + else if (hasDifferentTypes) { + reportError(ts.Diagnostics.Type_0_is_not_assignable_to_type_1, sourceTypeText, targetTypeText); + } + reportError(ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1, sourceParamText + " is " + sourceTypeText, targetParamText + " is " + targetTypeText); + } + return 0; + } + } + else if (!source.typePredicate && target.typePredicate) { + if (reportErrors) { + reportError(ts.Diagnostics.Signature_0_must_have_a_type_predicate, signatureToString(source)); + } + return 0; + } var t = getReturnTypeOfSignature(target); if (t === voidType) return result; @@ -12723,6 +14053,21 @@ var ts; return 0; } } + function isDeeplyNestedGeneric(type, stack, depth) { + if (type.flags & (4096 | 65536) && depth >= 5) { + var symbol = type.symbol; + var count = 0; + for (var i = 0; i < depth; i++) { + var t = stack[i]; + if (t.flags & (4096 | 65536) && t.symbol === symbol) { + count++; + if (count >= 5) + return true; + } + } + } + return false; + } function isPropertyIdenticalTo(sourceProp, targetProp) { return compareProperties(sourceProp, targetProp, compareTypes) !== 0; } @@ -12865,11 +14210,11 @@ var ts; return createAnonymousType(type.symbol, members, emptyArray, emptyArray, stringIndexType, numberIndexType); } function getWidenedType(type) { - if (type.flags & 786432) { + if (type.flags & 1572864) { if (type.flags & (32 | 64)) { return anyType; } - if (type.flags & 131072) { + if (type.flags & 262144) { return getWidenedTypeOfObjectLiteral(type); } if (type.flags & 16384) { @@ -12894,11 +14239,11 @@ var ts; if (isArrayType(type)) { return reportWideningErrorsInType(type.typeArguments[0]); } - if (type.flags & 131072) { + if (type.flags & 262144) { var errorReported = false; ts.forEach(getPropertiesOfObjectType(type), function (p) { var t = getTypeOfSymbol(p); - if (t.flags & 262144) { + if (t.flags & 524288) { if (!reportWideningErrorsInType(t)) { error(p.valueDeclaration, ts.Diagnostics.Object_literal_s_property_0_implicitly_has_an_1_type, p.name, typeToString(getWidenedType(t))); } @@ -12913,22 +14258,22 @@ var ts; var typeAsString = typeToString(getWidenedType(type)); var diagnostic; switch (declaration.kind) { + case 134: case 133: - case 132: diagnostic = ts.Diagnostics.Member_0_implicitly_has_an_1_type; break; - case 130: + case 131: diagnostic = declaration.dotDotDotToken ? ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type : ts.Diagnostics.Parameter_0_implicitly_has_an_1_type; break; - case 201: + case 203: + case 136: case 135: - case 134: - case 137: case 138: - case 163: - case 164: + case 139: + case 165: + case 166: if (!declaration.name) { error(declaration, ts.Diagnostics.Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeAsString); return; @@ -12941,7 +14286,7 @@ var ts; error(declaration, diagnostic, ts.declarationNameToString(declaration.name), typeAsString); } function reportErrorsFromWidening(declaration, type) { - if (produceDiagnostics && compilerOptions.noImplicitAny && type.flags & 262144) { + if (produceDiagnostics && compilerOptions.noImplicitAny && type.flags & 524288) { if (!reportWideningErrorsInType(type)) { reportImplicitAnyError(declaration, type); } @@ -13000,20 +14345,6 @@ var ts; } return false; } - function isWithinDepthLimit(type, stack) { - if (depth >= 5) { - var target_2 = type.target; - var count = 0; - for (var i = 0; i < depth; i++) { - var t = stack[i]; - if (t.flags & 4096 && t.target === target_2) { - count++; - } - } - return count < 5; - } - return true; - } function inferFromTypes(source, target) { if (source === anyFunctionType) { return; @@ -13071,22 +14402,26 @@ var ts; } else if (source.flags & 48128 && (target.flags & (4096 | 8192) || (target.flags & 32768) && target.symbol && target.symbol.flags & (8192 | 2048))) { - if (!isInProcess(source, target) && isWithinDepthLimit(source, sourceStack) && isWithinDepthLimit(target, targetStack)) { - if (depth === 0) { - sourceStack = []; - targetStack = []; - } - sourceStack[depth] = source; - targetStack[depth] = target; - depth++; - inferFromProperties(source, target); - inferFromSignatures(source, target, 0); - inferFromSignatures(source, target, 1); - inferFromIndexTypes(source, target, 0, 0); - inferFromIndexTypes(source, target, 1, 1); - inferFromIndexTypes(source, target, 0, 1); - depth--; + if (isInProcess(source, target)) { + return; } + if (isDeeplyNestedGeneric(source, sourceStack, depth) && isDeeplyNestedGeneric(target, targetStack, depth)) { + return; + } + if (depth === 0) { + sourceStack = []; + targetStack = []; + } + sourceStack[depth] = source; + targetStack[depth] = target; + depth++; + inferFromProperties(source, target); + inferFromSignatures(source, target, 0); + inferFromSignatures(source, target, 1); + inferFromIndexTypes(source, target, 0, 0); + inferFromIndexTypes(source, target, 1, 1); + inferFromIndexTypes(source, target, 0, 1); + depth--; } } function inferFromProperties(source, target) { @@ -13111,7 +14446,14 @@ var ts; } function inferFromSignature(source, target) { forEachMatchingParameterType(source, target, inferFromTypes); - inferFromTypes(getReturnTypeOfSignature(source), getReturnTypeOfSignature(target)); + if (source.typePredicate && target.typePredicate) { + if (target.typePredicate.parameterIndex === source.typePredicate.parameterIndex) { + inferFromTypes(source.typePredicate.type, target.typePredicate.type); + } + } + else { + inferFromTypes(getReturnTypeOfSignature(source), getReturnTypeOfSignature(target)); + } } function inferFromIndexTypes(source, target, sourceKind, targetKind) { var targetIndexType = getIndexTypeOfType(target, targetKind); @@ -13171,10 +14513,10 @@ var ts; function isInTypeQuery(node) { while (node) { switch (node.kind) { - case 145: + case 147: return true; case 65: - case 127: + case 128: node = node.parent; continue; default: @@ -13216,7 +14558,7 @@ var ts; function isAssignedInBinaryExpression(node) { if (node.operatorToken.kind >= 53 && node.operatorToken.kind <= 64) { var n = node.left; - while (n.kind === 162) { + while (n.kind === 164) { n = n.expression; } if (n.kind === 65 && getResolvedSymbol(n) === symbol) { @@ -13233,46 +14575,46 @@ var ts; } function isAssignedIn(node) { switch (node.kind) { - case 170: + case 172: return isAssignedInBinaryExpression(node); - case 199: - case 153: - return isAssignedInVariableDeclaration(node); - case 151: - case 152: - case 154: + case 201: case 155: + return isAssignedInVariableDeclaration(node); + case 153: + case 154: case 156: case 157: case 158: case 159: + case 160: case 161: - case 162: - case 168: - case 165: - case 166: + case 163: + case 164: + case 170: case 167: + case 168: case 169: case 171: - case 174: - case 180: - case 181: + case 173: + case 176: + case 182: case 183: - case 184: case 185: case 186: case 187: case 188: case 189: - case 192: - case 193: + case 190: + case 191: case 194: - case 221: - case 222: case 195: case 196: - case 197: + case 223: case 224: + case 197: + case 198: + case 199: + case 226: return ts.forEachChild(node, isAssignedIn); } return false; @@ -13280,10 +14622,10 @@ var ts; } function resolveLocation(node) { var containerNodes = []; - for (var parent_3 = node.parent; parent_3; parent_3 = parent_3.parent) { - if ((ts.isExpression(parent_3) || ts.isObjectLiteralMethod(node)) && - isContextSensitive(parent_3)) { - containerNodes.unshift(parent_3); + for (var parent_5 = node.parent; parent_5; parent_5 = parent_5.parent) { + if ((ts.isExpression(parent_5) || ts.isObjectLiteralMethod(node)) && + isContextSensitive(parent_5)) { + containerNodes.unshift(parent_5); } } ts.forEach(containerNodes, function (node) { getTypeOfNode(node); }); @@ -13302,53 +14644,55 @@ var ts; } function getNarrowedTypeOfSymbol(symbol, node) { var type = getTypeOfSymbol(symbol); - if (node && symbol.flags & 3 && type.flags & (1 | 48128 | 16384 | 512)) { - loop: while (node.parent) { - var child = node; - node = node.parent; - var narrowedType = type; - switch (node.kind) { - case 184: - if (child !== node.expression) { - narrowedType = narrowType(type, node.expression, child === node.thenStatement); - } - break; - case 171: - if (child !== node.condition) { - narrowedType = narrowType(type, node.condition, child === node.whenTrue); - } - break; - case 170: - if (child === node.right) { - if (node.operatorToken.kind === 48) { - narrowedType = narrowType(type, node.left, true); + if (node && symbol.flags & 3) { + if (isTypeAny(type) || type.flags & (48128 | 16384 | 512)) { + loop: while (node.parent) { + var child = node; + node = node.parent; + var narrowedType = type; + switch (node.kind) { + case 186: + if (child !== node.expression) { + narrowedType = narrowType(type, node.expression, child === node.thenStatement); } - else if (node.operatorToken.kind === 49) { - narrowedType = narrowType(type, node.left, false); + break; + case 173: + if (child !== node.condition) { + narrowedType = narrowType(type, node.condition, child === node.whenTrue); } - } - break; - case 228: - case 206: - case 201: - case 135: - case 134: - case 137: - case 138: - case 136: - break loop; - } - if (narrowedType !== type) { - if (isVariableAssignedWithin(symbol, node)) { - break; + break; + case 172: + if (child === node.right) { + if (node.operatorToken.kind === 48) { + narrowedType = narrowType(type, node.left, true); + } + else if (node.operatorToken.kind === 49) { + narrowedType = narrowType(type, node.left, false); + } + } + break; + case 230: + case 208: + case 203: + case 136: + case 135: + case 138: + case 139: + case 137: + break loop; + } + if (narrowedType !== type) { + if (isVariableAssignedWithin(symbol, node)) { + break; + } + type = narrowedType; } - type = narrowedType; } } } return type; function narrowTypeByEquality(type, expr, assumeTrue) { - if (expr.left.kind !== 166 || expr.right.kind !== 8) { + if (expr.left.kind !== 168 || expr.right.kind !== 8) { return type; } var left = expr.left; @@ -13362,7 +14706,7 @@ var ts; } if (assumeTrue) { if (!typeInfo) { - return removeTypesFromUnionType(type, 258 | 132 | 8 | 1048576, true, false); + return removeTypesFromUnionType(type, 258 | 132 | 8 | 2097152, true, false); } if (isTypeSubtypeOf(typeInfo.type, type)) { return typeInfo.type; @@ -13399,7 +14743,7 @@ var ts; } } function narrowTypeByInstanceof(type, expr, assumeTrue) { - if (type.flags & 1 || !assumeTrue || expr.left.kind !== 65 || getResolvedSymbol(expr.left) !== symbol) { + if (isTypeAny(type) || !assumeTrue || expr.left.kind !== 65 || getResolvedSymbol(expr.left) !== symbol) { return type; } var rightType = checkExpression(expr.right); @@ -13410,7 +14754,7 @@ var ts; var prototypeProperty = getPropertyOfType(rightType, "prototype"); if (prototypeProperty) { var prototypePropertyType = getTypeOfSymbol(prototypeProperty); - if (prototypePropertyType !== anyType) { + if (!isTypeAny(prototypePropertyType)) { targetType = prototypePropertyType; } } @@ -13427,20 +14771,44 @@ var ts; } } if (targetType) { - if (isTypeSubtypeOf(targetType, type)) { - return targetType; - } - if (type.flags & 16384) { - return getUnionType(ts.filter(type.types, function (t) { return isTypeSubtypeOf(t, targetType); })); + return getNarrowedType(type, targetType); + } + return type; + } + function getNarrowedType(originalType, narrowedTypeCandidate) { + if (isTypeSubtypeOf(narrowedTypeCandidate, originalType)) { + return narrowedTypeCandidate; + } + if (originalType.flags & 16384) { + return getUnionType(ts.filter(originalType.types, function (t) { return isTypeSubtypeOf(t, narrowedTypeCandidate); })); + } + return originalType; + } + function narrowTypeByTypePredicate(type, expr, assumeTrue) { + if (type.flags & 1) { + return type; + } + var signature = getResolvedSignature(expr); + if (signature.typePredicate && + expr.arguments[signature.typePredicate.parameterIndex] && + getSymbolAtLocation(expr.arguments[signature.typePredicate.parameterIndex]) === symbol) { + if (!assumeTrue) { + if (type.flags & 16384) { + return getUnionType(ts.filter(type.types, function (t) { return !isTypeSubtypeOf(t, signature.typePredicate.type); })); + } + return type; } + return getNarrowedType(type, signature.typePredicate.type); } return type; } function narrowType(type, expr, assumeTrue) { switch (expr.kind) { - case 162: + case 160: + return narrowTypeByTypePredicate(type, expr, assumeTrue); + case 164: return narrowType(type, expr.expression, assumeTrue); - case 170: + case 172: var operator = expr.operatorToken.kind; if (operator === 30 || operator === 31) { return narrowTypeByEquality(type, expr, assumeTrue); @@ -13455,7 +14823,7 @@ var ts; return narrowTypeByInstanceof(type, expr, assumeTrue); } break; - case 168: + case 170: if (expr.operator === 46) { return narrowType(type, expr.operand, !assumeTrue); } @@ -13466,7 +14834,7 @@ var ts; } function checkIdentifier(node) { var symbol = getResolvedSymbol(node); - if (symbol === argumentsSymbol && ts.getContainingFunction(node).kind === 164 && languageVersion < 2) { + if (symbol === argumentsSymbol && ts.getContainingFunction(node).kind === 166 && languageVersion < 2) { error(node, ts.Diagnostics.The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_standard_function_expression); } if (symbol.flags & 8388608 && !isInTypeQuery(node) && !isConstEnumOrConstEnumOnlyModule(resolveAlias(symbol))) { @@ -13490,15 +14858,15 @@ var ts; function checkBlockScopedBindingCapturedInLoop(node, symbol) { if (languageVersion >= 2 || (symbol.flags & 2) === 0 || - symbol.valueDeclaration.parent.kind === 224) { + symbol.valueDeclaration.parent.kind === 226) { return; } var container = symbol.valueDeclaration; - while (container.kind !== 200) { + while (container.kind !== 202) { container = container.parent; } container = container.parent; - if (container.kind === 181) { + if (container.kind === 183) { container = container.parent; } var inFunction = isInsideFunction(node.parent, container); @@ -13515,9 +14883,9 @@ var ts; } } function captureLexicalThis(node, container) { - var classNode = container.parent && container.parent.kind === 202 ? container.parent : undefined; + var classNode = container.parent && container.parent.kind === 204 ? container.parent : undefined; getNodeLinks(node).flags |= 2; - if (container.kind === 133 || container.kind === 136) { + if (container.kind === 134 || container.kind === 137) { getNodeLinks(classNode).flags |= 4; } else { @@ -13527,36 +14895,36 @@ var ts; function checkThisExpression(node) { var container = ts.getThisContainer(node, true); var needToCaptureLexicalThis = false; - if (container.kind === 164) { + if (container.kind === 166) { container = ts.getThisContainer(container, false); needToCaptureLexicalThis = (languageVersion < 2); } switch (container.kind) { - case 206: + case 208: error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_module_or_namespace_body); break; - case 205: + case 207: error(node, ts.Diagnostics.this_cannot_be_referenced_in_current_location); break; - case 136: + case 137: if (isInConstructorArgumentInitializer(node, container)) { error(node, ts.Diagnostics.this_cannot_be_referenced_in_constructor_arguments); } break; + case 134: case 133: - case 132: if (container.flags & 128) { error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_static_property_initializer); } break; - case 128: + case 129: error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_computed_property_name); break; } if (needToCaptureLexicalThis) { captureLexicalThis(node, container); } - var classNode = container.parent && container.parent.kind === 202 ? container.parent : undefined; + var classNode = container.parent && container.parent.kind === 204 ? container.parent : undefined; if (classNode) { var symbol = getSymbolOfNode(classNode); return container.flags & 128 ? getTypeOfSymbol(symbol) : getDeclaredTypeOfSymbol(symbol); @@ -13565,23 +14933,21 @@ var ts; } function isInConstructorArgumentInitializer(node, constructorDecl) { for (var n = node; n && n !== constructorDecl; n = n.parent) { - if (n.kind === 130) { + if (n.kind === 131) { return true; } } return false; } function checkSuperExpression(node) { - var isCallExpression = node.parent.kind === 158 && node.parent.expression === node; - var enclosingClass = ts.getAncestor(node, 202); - var baseClass; - if (enclosingClass && ts.getClassExtendsHeritageClauseElement(enclosingClass)) { - var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(enclosingClass)); - var baseTypes = getBaseTypes(classType); - baseClass = baseTypes.length && baseTypes[0]; - } - if (!baseClass) { - error(node, ts.Diagnostics.super_can_only_be_referenced_in_a_derived_class); + var isCallExpression = node.parent.kind === 160 && node.parent.expression === node; + var classDeclaration = ts.getAncestor(node, 204); + var classType = classDeclaration && getDeclaredTypeOfSymbol(getSymbolOfNode(classDeclaration)); + var baseClassType = classType && getBaseTypes(classType)[0]; + if (!baseClassType) { + if (!classDeclaration || !ts.getClassExtendsHeritageClauseElement(classDeclaration)) { + error(node, ts.Diagnostics.super_can_only_be_referenced_in_a_derived_class); + } return unknownType; } var container = ts.getSuperContainer(node, true); @@ -13589,31 +14955,31 @@ var ts; var canUseSuperExpression = false; var needToCaptureLexicalThis; if (isCallExpression) { - canUseSuperExpression = container.kind === 136; + canUseSuperExpression = container.kind === 137; } else { needToCaptureLexicalThis = false; - while (container && container.kind === 164) { + while (container && container.kind === 166) { container = ts.getSuperContainer(container, true); needToCaptureLexicalThis = languageVersion < 2; } - if (container && container.parent && container.parent.kind === 202) { + if (container && container.parent && container.parent.kind === 204) { if (container.flags & 128) { canUseSuperExpression = - container.kind === 135 || - container.kind === 134 || - container.kind === 137 || - container.kind === 138; + container.kind === 136 || + container.kind === 135 || + container.kind === 138 || + container.kind === 139; } else { canUseSuperExpression = - container.kind === 135 || - container.kind === 134 || - container.kind === 137 || + container.kind === 136 || + container.kind === 135 || container.kind === 138 || + container.kind === 139 || + container.kind === 134 || container.kind === 133 || - container.kind === 132 || - container.kind === 136; + container.kind === 137; } } } @@ -13621,13 +14987,13 @@ var ts; var returnType; if ((container.flags & 128) || isCallExpression) { getNodeLinks(node).flags |= 32; - returnType = getTypeOfSymbol(baseClass.symbol); + returnType = getBaseConstructorTypeOfClass(classType); } else { getNodeLinks(node).flags |= 16; - returnType = baseClass; + returnType = baseClassType; } - if (container.kind === 136 && isInConstructorArgumentInitializer(node, container)) { + if (container.kind === 137 && isInConstructorArgumentInitializer(node, container)) { error(node, ts.Diagnostics.super_cannot_be_referenced_in_constructor_arguments); returnType = unknownType; } @@ -13637,7 +15003,7 @@ var ts; return returnType; } } - if (container && container.kind === 128) { + if (container && container.kind === 129) { error(node, ts.Diagnostics.super_cannot_be_referenced_in_a_computed_property_name); } else if (isCallExpression) { @@ -13654,7 +15020,7 @@ var ts; if (isContextSensitive(func)) { var contextualSignature = getContextualSignature(func); if (contextualSignature) { - var funcHasRestParameters = ts.hasRestParameters(func); + var funcHasRestParameters = ts.hasRestParameter(func); var len = func.parameters.length - (funcHasRestParameters ? 1 : 0); var indexOfParameter = ts.indexOf(func.parameters, parameter); if (indexOfParameter < len) { @@ -13675,7 +15041,7 @@ var ts; if (declaration.type) { return getTypeFromTypeNode(declaration.type); } - if (declaration.kind === 130) { + if (declaration.kind === 131) { var type = getContextuallyTypedParameterType(declaration); if (type) { return type; @@ -13688,18 +15054,36 @@ var ts; return undefined; } function getContextualTypeForReturnExpression(node) { + var func = ts.getContainingFunction(node); + if (func && !func.asteriskToken) { + return getContextualReturnType(func); + } + return undefined; + } + function getContextualTypeForYieldOperand(node) { var func = ts.getContainingFunction(node); if (func) { - if (func.type || func.kind === 136 || func.kind === 137 && getSetAccessorTypeAnnotationNode(ts.getDeclarationOfKind(func.symbol, 138))) { - return getReturnTypeOfSignature(getSignatureFromDeclaration(func)); - } - var signature = getContextualSignatureForFunctionLikeDeclaration(func); - if (signature) { - return getReturnTypeOfSignature(signature); + var contextualReturnType = getContextualReturnType(func); + if (contextualReturnType) { + return node.asteriskToken + ? contextualReturnType + : getElementTypeOfIterableIterator(contextualReturnType); } } return undefined; } + function getContextualReturnType(functionDecl) { + if (functionDecl.type || + functionDecl.kind === 137 || + functionDecl.kind === 138 && getSetAccessorTypeAnnotationNode(ts.getDeclarationOfKind(functionDecl.symbol, 139))) { + 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); @@ -13710,7 +15094,7 @@ var ts; return undefined; } function getContextualTypeForSubstitutionExpression(template, substitutionExpression) { - if (template.parent.kind === 160) { + if (template.parent.kind === 162) { return getContextualTypeForArgument(template.parent, substitutionExpression); } return undefined; @@ -13801,7 +15185,7 @@ var ts; var index = ts.indexOf(arrayLiteral.elements, node); return getTypeOfPropertyOfContextualType(type, "" + index) || getIndexTypeOfContextualType(type, 1) - || (languageVersion >= 2 ? checkIteratedType(type, undefined) : undefined); + || (languageVersion >= 2 ? getElementTypeOfIterable(type, undefined) : undefined); } return undefined; } @@ -13818,32 +15202,34 @@ var ts; } var parent = node.parent; switch (parent.kind) { - case 199: - case 130: + case 201: + case 131: + case 134: case 133: - case 132: - case 153: + case 155: return getContextualTypeForInitializerExpression(node); - case 164: - case 192: + case 166: + case 194: return getContextualTypeForReturnExpression(node); - case 158: - case 159: - return getContextualTypeForArgument(parent, node); + case 175: + return getContextualTypeForYieldOperand(parent); + case 160: case 161: + return getContextualTypeForArgument(parent, node); + case 163: return getTypeFromTypeNode(parent.type); - case 170: + case 172: return getContextualTypeForBinaryOperand(node); - case 225: + case 227: return getContextualTypeForObjectLiteralElement(parent); - case 154: + case 156: return getContextualTypeForElementExpression(node); - case 171: + case 173: return getContextualTypeForConditionalOperand(node); - case 178: - ts.Debug.assert(parent.parent.kind === 172); + case 180: + ts.Debug.assert(parent.parent.kind === 174); return getContextualTypeForSubstitutionExpression(parent.parent, node); - case 162: + case 164: return getContextualType(parent); } return undefined; @@ -13858,13 +15244,15 @@ var ts; } } function isFunctionExpressionOrArrowFunction(node) { - return node.kind === 163 || node.kind === 164; + return node.kind === 165 || node.kind === 166; } function getContextualSignatureForFunctionLikeDeclaration(node) { - return isFunctionExpressionOrArrowFunction(node) ? getContextualSignature(node) : undefined; + return isFunctionExpressionOrArrowFunction(node) || ts.isObjectLiteralMethod(node) + ? getContextualSignature(node) + : undefined; } function getContextualSignature(node) { - ts.Debug.assert(node.kind !== 135 || ts.isObjectLiteralMethod(node)); + ts.Debug.assert(node.kind !== 136 || ts.isObjectLiteralMethod(node)); var type = ts.isObjectLiteralMethod(node) ? getContextualTypeForObjectLiteralMethod(node) : getContextualType(node); @@ -13908,13 +15296,13 @@ var ts; } function isAssignmentTarget(node) { var parent = node.parent; - if (parent.kind === 170 && parent.operatorToken.kind === 53 && parent.left === node) { + if (parent.kind === 172 && parent.operatorToken.kind === 53 && parent.left === node) { return true; } - if (parent.kind === 225) { + if (parent.kind === 227) { return isAssignmentTarget(parent.parent); } - if (parent.kind === 154) { + if (parent.kind === 156) { return isAssignmentTarget(parent); } return false; @@ -13933,10 +15321,10 @@ var ts; var inDestructuringPattern = isAssignmentTarget(node); for (var _i = 0; _i < elements.length; _i++) { var e = elements[_i]; - if (inDestructuringPattern && e.kind === 174) { + if (inDestructuringPattern && e.kind === 176) { var restArrayType = checkExpression(e.expression, contextualMapper); var restElementType = getIndexTypeOfType(restArrayType, 1) || - (languageVersion >= 2 ? checkIteratedType(restArrayType, undefined) : undefined); + (languageVersion >= 2 ? getElementTypeOfIterable(restArrayType, undefined) : undefined); if (restElementType) { elementTypes.push(restElementType); } @@ -13945,7 +15333,7 @@ var ts; var type = checkExpression(e, contextualMapper); elementTypes.push(type); } - hasSpreadElement = hasSpreadElement || e.kind === 174; + hasSpreadElement = hasSpreadElement || e.kind === 176; } if (!hasSpreadElement) { var contextualType = getContextualType(node); @@ -13956,10 +15344,13 @@ var ts; return createArrayType(getUnionType(elementTypes)); } function isNumericName(name) { - return name.kind === 128 ? isNumericComputedName(name) : isNumericLiteralName(name.text); + return name.kind === 129 ? isNumericComputedName(name) : isNumericLiteralName(name.text); } function isNumericComputedName(name) { - return allConstituentTypesHaveKind(checkComputedPropertyName(name), 1 | 132); + return isTypeAnyOrAllConstituentTypesHaveKind(checkComputedPropertyName(name), 132); + } + function isTypeAnyOrAllConstituentTypesHaveKind(type, kind) { + return isTypeAny(type) || allConstituentTypesHaveKind(type, kind); } function isNumericLiteralName(name) { return (+name).toString() === name; @@ -13968,7 +15359,7 @@ var ts; var links = getNodeLinks(node.expression); if (!links.resolvedType) { links.resolvedType = checkExpression(node.expression); - if (!allConstituentTypesHaveKind(links.resolvedType, 1 | 132 | 258 | 1048576)) { + if (!isTypeAnyOrAllConstituentTypesHaveKind(links.resolvedType, 132 | 258 | 2097152)) { error(node, ts.Diagnostics.A_computed_property_name_must_be_of_type_string_number_symbol_or_any); } else { @@ -13986,18 +15377,18 @@ var ts; for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { var memberDecl = _a[_i]; var member = memberDecl.symbol; - if (memberDecl.kind === 225 || - memberDecl.kind === 226 || + if (memberDecl.kind === 227 || + memberDecl.kind === 228 || ts.isObjectLiteralMethod(memberDecl)) { var type = void 0; - if (memberDecl.kind === 225) { + if (memberDecl.kind === 227) { type = checkPropertyAssignment(memberDecl, contextualMapper); } - else if (memberDecl.kind === 135) { + else if (memberDecl.kind === 136) { type = checkObjectLiteralMethod(memberDecl, contextualMapper); } else { - ts.Debug.assert(memberDecl.kind === 226); + ts.Debug.assert(memberDecl.kind === 228); type = checkExpression(memberDecl.name, contextualMapper); } typeFlags |= type.flags; @@ -14012,7 +15403,7 @@ var ts; member = prop; } else { - ts.Debug.assert(memberDecl.kind === 137 || memberDecl.kind === 138); + ts.Debug.assert(memberDecl.kind === 138 || memberDecl.kind === 139); checkAccessorDeclaration(memberDecl); } if (!ts.hasDynamicName(memberDecl)) { @@ -14023,7 +15414,7 @@ var ts; var stringIndexType = getIndexType(0); var numberIndexType = getIndexType(1); var result = createAnonymousType(node.symbol, propertiesTable, emptyArray, emptyArray, stringIndexType, numberIndexType); - result.flags |= 131072 | 524288 | (typeFlags & 262144); + result.flags |= 262144 | 1048576 | (typeFlags & 524288); return result; function getIndexType(kind) { if (contextualType && contextualTypeHasIndexSignature(contextualType, kind)) { @@ -14045,7 +15436,7 @@ var ts; } } function getDeclarationKindFromSymbol(s) { - return s.valueDeclaration ? s.valueDeclaration.kind : 133; + return s.valueDeclaration ? s.valueDeclaration.kind : 134; } function getDeclarationFlagsFromSymbol(s) { return s.valueDeclaration ? ts.getCombinedNodeFlags(s.valueDeclaration) : s.flags & 134217728 ? 16 | 128 : 0; @@ -14055,7 +15446,7 @@ var ts; if (!(flags & (32 | 64))) { return; } - var enclosingClassDeclaration = ts.getAncestor(node, 202); + var enclosingClassDeclaration = ts.getAncestor(node, 204); var enclosingClass = enclosingClassDeclaration ? getDeclaredTypeOfSymbol(getSymbolOfNode(enclosingClassDeclaration)) : undefined; var declaringClass = getDeclaredTypeOfSymbol(prop.parent); if (flags & 32) { @@ -14085,43 +15476,41 @@ var ts; return checkPropertyAccessExpressionOrQualifiedName(node, node.left, node.right); } function checkPropertyAccessExpressionOrQualifiedName(node, left, right) { - var type = checkExpressionOrQualifiedName(left); - if (type === unknownType) + var type = checkExpression(left); + if (isTypeAny(type)) { return type; - if (type !== anyType) { - var apparentType = getApparentType(getWidenedType(type)); - if (apparentType === unknownType) { - return unknownType; - } - var prop = getPropertyOfType(apparentType, right.text); - if (!prop) { - if (right.text) { - error(right, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(right), typeToString(type)); - } - return unknownType; - } - getNodeLinks(node).resolvedSymbol = prop; - if (prop.parent && prop.parent.flags & 32) { - if (left.kind === 91 && getDeclarationKindFromSymbol(prop) !== 135) { - error(right, ts.Diagnostics.Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword); - } - else { - checkClassPropertyAccess(node, left, type, prop); - } - } - return getTypeOfSymbol(prop); } - return anyType; + var apparentType = getApparentType(getWidenedType(type)); + if (apparentType === unknownType) { + return unknownType; + } + var prop = getPropertyOfType(apparentType, right.text); + if (!prop) { + if (right.text) { + error(right, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(right), typeToString(type)); + } + return unknownType; + } + getNodeLinks(node).resolvedSymbol = prop; + if (prop.parent && prop.parent.flags & 32) { + if (left.kind === 91 && getDeclarationKindFromSymbol(prop) !== 136) { + error(right, ts.Diagnostics.Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword); + } + else { + checkClassPropertyAccess(node, left, type, prop); + } + } + return getTypeOfSymbol(prop); } function isValidPropertyAccess(node, propertyName) { - var left = node.kind === 156 + var left = node.kind === 158 ? node.expression : node.left; - var type = checkExpressionOrQualifiedName(left); - if (type !== unknownType && type !== anyType) { + var type = checkExpression(left); + if (type !== unknownType && !isTypeAny(type)) { var prop = getPropertyOfType(getWidenedType(type), propertyName); if (prop && prop.parent && prop.parent.flags & 32) { - if (left.kind === 91 && getDeclarationKindFromSymbol(prop) !== 135) { + if (left.kind === 91 && getDeclarationKindFromSymbol(prop) !== 136) { return false; } else { @@ -14136,7 +15525,7 @@ var ts; function checkIndexedAccess(node) { if (!node.argumentExpression) { var sourceFile = getSourceFile(node); - if (node.parent.kind === 159 && node.parent.expression === node) { + if (node.parent.kind === 161 && 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); @@ -14159,21 +15548,21 @@ var ts; return unknownType; } if (node.argumentExpression) { - var name_6 = getPropertyNameForIndexedAccess(node.argumentExpression, indexType); - if (name_6 !== undefined) { - var prop = getPropertyOfType(objectType, name_6); + var name_10 = getPropertyNameForIndexedAccess(node.argumentExpression, indexType); + if (name_10 !== undefined) { + var prop = getPropertyOfType(objectType, name_10); if (prop) { getNodeLinks(node).resolvedSymbol = prop; return getTypeOfSymbol(prop); } else if (isConstEnum) { - error(node.argumentExpression, ts.Diagnostics.Property_0_does_not_exist_on_const_enum_1, name_6, symbolToString(objectType.symbol)); + error(node.argumentExpression, ts.Diagnostics.Property_0_does_not_exist_on_const_enum_1, name_10, symbolToString(objectType.symbol)); return unknownType; } } } - if (allConstituentTypesHaveKind(indexType, 1 | 258 | 132 | 1048576)) { - if (allConstituentTypesHaveKind(indexType, 1 | 132)) { + if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 258 | 132 | 2097152)) { + if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 132)) { var numberIndexType = getIndexTypeOfType(objectType, 1); if (numberIndexType) { return numberIndexType; @@ -14183,7 +15572,7 @@ var ts; if (stringIndexType) { return stringIndexType; } - if (compilerOptions.noImplicitAny && !compilerOptions.suppressImplicitAnyIndexErrors && objectType !== anyType) { + if (compilerOptions.noImplicitAny && !compilerOptions.suppressImplicitAnyIndexErrors && !isTypeAny(objectType)) { error(node, ts.Diagnostics.Index_signature_of_object_type_implicitly_has_an_any_type); } return anyType; @@ -14208,7 +15597,7 @@ var ts; if (!ts.isWellKnownSymbolSyntactically(expression)) { return false; } - if ((expressionType.flags & 1048576) === 0) { + if ((expressionType.flags & 2097152) === 0) { if (reportError) { error(expression, ts.Diagnostics.A_computed_property_name_of_the_form_0_must_be_of_type_symbol, ts.getTextOfNode(expression)); } @@ -14232,7 +15621,7 @@ var ts; return true; } function resolveUntypedCall(node) { - if (node.kind === 160) { + if (node.kind === 162) { checkExpression(node.template); } else { @@ -14257,19 +15646,19 @@ var ts; for (var _i = 0; _i < signatures.length; _i++) { var signature = signatures[_i]; var symbol = signature.declaration && getSymbolOfNode(signature.declaration); - var parent_4 = signature.declaration && signature.declaration.parent; + var parent_6 = signature.declaration && signature.declaration.parent; if (!lastSymbol || symbol === lastSymbol) { - if (lastParent && parent_4 === lastParent) { + if (lastParent && parent_6 === lastParent) { index++; } else { - lastParent = parent_4; + lastParent = parent_6; index = cutoffIndex; } } else { index = cutoffIndex = result.length; - lastParent = parent_4; + lastParent = parent_6; } lastSymbol = symbol; if (signature.hasStringLiterals) { @@ -14285,7 +15674,7 @@ var ts; } function getSpreadArgumentIndex(args) { for (var i = 0; i < args.length; i++) { - if (args[i].kind === 174) { + if (args[i].kind === 176) { return i; } } @@ -14295,11 +15684,11 @@ var ts; var adjustedArgCount; var typeArguments; var callIsIncomplete; - if (node.kind === 160) { + if (node.kind === 162) { var tagExpression = node; adjustedArgCount = args.length; typeArguments = undefined; - if (tagExpression.template.kind === 172) { + if (tagExpression.template.kind === 174) { var templateExpression = tagExpression.template; var lastSpan = ts.lastOrUndefined(templateExpression.templateSpans); ts.Debug.assert(lastSpan !== undefined); @@ -14314,7 +15703,7 @@ var ts; else { var callExpression = node; if (!callExpression.arguments) { - ts.Debug.assert(callExpression.kind === 159); + ts.Debug.assert(callExpression.kind === 161); return signature.minArgumentCount === 0; } adjustedArgCount = callExpression.arguments.hasTrailingComma ? args.length + 1 : args.length; @@ -14366,10 +15755,10 @@ var ts; } for (var i = 0; i < args.length; i++) { var arg = args[i]; - if (arg.kind !== 176) { + if (arg.kind !== 178) { var paramType = getTypeAtPosition(signature, i); var argType = void 0; - if (i === 0 && args[i].parent.kind === 160) { + if (i === 0 && args[i].parent.kind === 162) { argType = globalTemplateStringsArrayType; } else { @@ -14409,9 +15798,9 @@ var ts; function checkApplicableSignature(node, args, signature, relation, excludeArgument, reportErrors) { for (var i = 0; i < args.length; i++) { var arg = args[i]; - if (arg.kind !== 176) { + if (arg.kind !== 178) { var paramType = getTypeAtPosition(signature, i); - var argType = i === 0 && node.kind === 160 + var argType = i === 0 && node.kind === 162 ? globalTemplateStringsArrayType : arg.kind === 8 && !reportErrors ? getStringLiteralType(arg) @@ -14425,10 +15814,10 @@ var ts; } function getEffectiveCallArguments(node) { var args; - if (node.kind === 160) { + if (node.kind === 162) { var template = node.template; args = [template]; - if (template.kind === 172) { + if (template.kind === 174) { ts.forEach(template.templateSpans, function (span) { args.push(span.expression); }); @@ -14439,21 +15828,11 @@ var ts; } return args; } - function getEffectiveTypeArguments(callExpression) { - if (callExpression.expression.kind === 91) { - var containingClass = ts.getAncestor(callExpression, 202); - var baseClassTypeNode = containingClass && ts.getClassExtendsHeritageClauseElement(containingClass); - return baseClassTypeNode && baseClassTypeNode.typeArguments; - } - else { - return callExpression.typeArguments; - } - } function resolveCall(node, signatures, candidatesOutArray) { - var isTaggedTemplate = node.kind === 160; + var isTaggedTemplate = node.kind === 162; var typeArguments; if (!isTaggedTemplate) { - typeArguments = getEffectiveTypeArguments(node); + typeArguments = node.typeArguments; if (node.expression.kind !== 91) { ts.forEach(typeArguments, checkSourceElement); } @@ -14494,8 +15873,8 @@ var ts; checkApplicableSignature(node, args, candidateForArgumentError, assignableRelation, undefined, true); } else if (candidateForTypeArgumentError) { - if (!isTaggedTemplate && node.typeArguments) { - checkTypeArguments(candidateForTypeArgumentError, node.typeArguments, [], true); + if (!isTaggedTemplate && typeArguments) { + checkTypeArguments(candidateForTypeArgumentError, typeArguments, [], true); } else { ts.Debug.assert(resultOfFailedInference.failedTypeParameterIndex >= 0); @@ -14579,7 +15958,9 @@ var ts; if (node.expression.kind === 91) { var superType = checkSuperExpression(node.expression); if (superType !== unknownType) { - return resolveCall(node, getSignaturesOfType(superType, 1), candidatesOutArray); + var baseTypeNode = ts.getClassExtendsHeritageClauseElement(ts.getAncestor(node, 204)); + var baseConstructors = getInstantiatedConstructorsForTypeArguments(superType, baseTypeNode.typeArguments); + return resolveCall(node, baseConstructors, candidatesOutArray); } return resolveUntypedCall(node); } @@ -14590,8 +15971,8 @@ var ts; } var callSignatures = getSignaturesOfType(apparentType, 0); var constructSignatures = getSignaturesOfType(apparentType, 1); - if (funcType === anyType || (!callSignatures.length && !constructSignatures.length && !(funcType.flags & 16384) && isTypeAssignableTo(funcType, globalFunctionType))) { - if (node.typeArguments) { + if (isTypeAny(funcType) || (!callSignatures.length && !constructSignatures.length && !(funcType.flags & 16384) && isTypeAssignableTo(funcType, globalFunctionType))) { + if (funcType !== unknownType && node.typeArguments) { error(node, ts.Diagnostics.Untyped_function_calls_may_not_accept_type_arguments); } return resolveUntypedCall(node); @@ -14608,23 +15989,23 @@ var ts; return resolveCall(node, callSignatures, candidatesOutArray); } function resolveNewExpression(node, candidatesOutArray) { - if (node.arguments && languageVersion < 2) { + 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_6_and_higher); + error(node.arguments[spreadIndex], ts.Diagnostics.Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher); } } var expressionType = checkExpression(node.expression); - if (expressionType === anyType) { + expressionType = getApparentType(expressionType); + if (expressionType === unknownType) { + return resolveErrorCall(node); + } + if (isTypeAny(expressionType)) { if (node.typeArguments) { error(node, ts.Diagnostics.Untyped_function_calls_may_not_accept_type_arguments); } return resolveUntypedCall(node); } - expressionType = getApparentType(expressionType); - if (expressionType === unknownType) { - return resolveErrorCall(node); - } var constructSignatures = getSignaturesOfType(expressionType, 1); if (constructSignatures.length) { return resolveCall(node, constructSignatures, candidatesOutArray); @@ -14647,7 +16028,7 @@ var ts; return resolveErrorCall(node); } var callSignatures = getSignaturesOfType(apparentType, 0); - if (tagType === anyType || (!callSignatures.length && !(tagType.flags & 16384) && isTypeAssignableTo(tagType, globalFunctionType))) { + if (isTypeAny(tagType) || (!callSignatures.length && !(tagType.flags & 16384) && isTypeAssignableTo(tagType, globalFunctionType))) { return resolveUntypedCall(node); } if (!callSignatures.length) { @@ -14660,13 +16041,13 @@ var ts; var links = getNodeLinks(node); if (!links.resolvedSignature || candidatesOutArray) { links.resolvedSignature = anySignature; - if (node.kind === 158) { + if (node.kind === 160) { links.resolvedSignature = resolveCallExpression(node, candidatesOutArray); } - else if (node.kind === 159) { + else if (node.kind === 161) { links.resolvedSignature = resolveNewExpression(node, candidatesOutArray); } - else if (node.kind === 160) { + else if (node.kind === 162) { links.resolvedSignature = resolveTaggedTemplateExpression(node, candidatesOutArray); } else { @@ -14681,12 +16062,12 @@ var ts; if (node.expression.kind === 91) { return voidType; } - if (node.kind === 159) { + if (node.kind === 161) { var declaration = signature.declaration; if (declaration && - declaration.kind !== 136 && - declaration.kind !== 140 && - declaration.kind !== 144) { + declaration.kind !== 137 && + declaration.kind !== 141 && + declaration.kind !== 146) { if (compilerOptions.noImplicitAny) { error(node, ts.Diagnostics.new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type); } @@ -14733,18 +16114,41 @@ var ts; return unknownType; } var type; - if (func.body.kind !== 180) { + if (func.body.kind !== 182) { type = checkExpressionCached(func.body, contextualMapper); } else { - var types = checkAndAggregateReturnExpressionTypes(func.body, contextualMapper); - if (types.length === 0) { - return voidType; + var types; + var funcIsGenerator = !!func.asteriskToken; + if (funcIsGenerator) { + types = checkAndAggregateYieldOperandTypes(func.body, contextualMapper); + if (types.length === 0) { + var iterableIteratorAny = createIterableIteratorType(anyType); + if (compilerOptions.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.body, contextualMapper); + if (types.length === 0) { + return voidType; + } } type = contextualSignature ? getUnionType(types) : getCommonSupertype(types); if (!type) { - error(func, ts.Diagnostics.No_best_common_type_exists_among_return_expressions); - return unknownType; + if (funcIsGenerator) { + error(func, ts.Diagnostics.No_best_common_type_exists_among_yield_expressions); + return createIterableIteratorType(unknownType); + } + else { + error(func, ts.Diagnostics.No_best_common_type_exists_among_return_expressions); + return unknownType; + } + } + if (funcIsGenerator) { + type = createIterableIteratorType(type); } } if (!contextualSignature) { @@ -14752,6 +16156,22 @@ var ts; } return getWidenedType(type); } + function checkAndAggregateYieldOperandTypes(body, contextualMapper) { + var aggregatedTypes = []; + ts.forEachYieldExpression(body, function (yieldExpression) { + var expr = yieldExpression.expression; + if (expr) { + var type = checkExpressionCached(expr, contextualMapper); + if (yieldExpression.asteriskToken) { + type = checkElementTypeOfIterable(type, yieldExpression.expression); + } + if (!ts.contains(aggregatedTypes, type)) { + aggregatedTypes.push(type); + } + } + }); + return aggregatedTypes; + } function checkAndAggregateReturnExpressionTypes(body, contextualMapper) { var aggregatedTypes = []; ts.forEachReturnStatement(body, function (returnStatement) { @@ -14771,16 +16191,16 @@ var ts; }); } function bodyContainsSingleThrowStatement(body) { - return (body.statements.length === 1) && (body.statements[0].kind === 196); + return (body.statements.length === 1) && (body.statements[0].kind === 198); } function checkIfNonVoidFunctionHasReturnExpressionsOrSingleThrowStatment(func, returnType) { if (!produceDiagnostics) { return; } - if (returnType === voidType || returnType === anyType) { + if (returnType === voidType || isTypeAny(returnType)) { return; } - if (ts.nodeIsMissing(func.body) || func.body.kind !== 180) { + if (ts.nodeIsMissing(func.body) || func.body.kind !== 182) { return; } var bodyBlock = func.body; @@ -14793,10 +16213,10 @@ var ts; error(func.type, ts.Diagnostics.A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value_or_consist_of_a_single_throw_statement); } function checkFunctionExpressionOrObjectLiteralMethod(node, contextualMapper) { - ts.Debug.assert(node.kind !== 135 || ts.isObjectLiteralMethod(node)); - var hasGrammarError = checkGrammarDeclarationNameInStrictMode(node) || checkGrammarFunctionLikeDeclaration(node); - if (!hasGrammarError && node.kind === 163) { - checkGrammarFunctionName(node.name) || checkGrammarForGenerator(node); + ts.Debug.assert(node.kind !== 136 || ts.isObjectLiteralMethod(node)); + var hasGrammarError = checkGrammarFunctionLikeDeclaration(node); + if (!hasGrammarError && node.kind === 165) { + checkGrammarForGenerator(node); } if (contextualMapper === identityMapper && isContextSensitive(node)) { return anyFunctionType; @@ -14822,19 +16242,22 @@ var ts; checkSignatureDeclaration(node); } } - if (produceDiagnostics && node.kind !== 135 && node.kind !== 134) { + if (produceDiagnostics && node.kind !== 136 && node.kind !== 135) { checkCollisionWithCapturedSuperVariable(node, node.name); checkCollisionWithCapturedThisVariable(node, node.name); } return type; } function checkFunctionExpressionOrObjectLiteralMethodBody(node) { - ts.Debug.assert(node.kind !== 135 || ts.isObjectLiteralMethod(node)); + ts.Debug.assert(node.kind !== 136 || ts.isObjectLiteralMethod(node)); if (node.type && !node.asteriskToken) { checkIfNonVoidFunctionHasReturnExpressionsOrSingleThrowStatment(node, getTypeFromTypeNode(node.type)); } if (node.body) { - if (node.body.kind === 180) { + if (!node.type) { + getReturnTypeOfSignature(getSignatureFromDeclaration(node)); + } + if (node.body.kind === 182) { checkSourceElement(node.body); } else { @@ -14847,7 +16270,7 @@ var ts; } } function checkArithmeticOperandType(operand, type, diagnostic) { - if (!allConstituentTypesHaveKind(type, 1 | 132)) { + if (!isTypeAnyOrAllConstituentTypesHaveKind(type, 132)) { error(operand, diagnostic); return false; } @@ -14864,13 +16287,13 @@ var ts; var symbol = findSymbol(n); return !symbol || symbol === unknownSymbol || symbol === argumentsSymbol || (symbol.flags & 3) !== 0; } - case 156: { + case 158: { var symbol = findSymbol(n); return !symbol || symbol === unknownSymbol || (symbol.flags & ~8) !== 0; } - case 157: + case 159: return true; - case 162: + case 164: return isReferenceOrErrorExpression(n.expression); default: return false; @@ -14879,21 +16302,21 @@ var ts; function isConstVariableReference(n) { switch (n.kind) { case 65: - case 156: { + case 158: { var symbol = findSymbol(n); return symbol && (symbol.flags & 3) !== 0 && (getDeclarationFlagsFromSymbol(symbol) & 8192) !== 0; } - case 157: { + case 159: { var index = n.argumentExpression; var symbol = findSymbol(n.expression); if (symbol && index && index.kind === 8) { - var name_7 = index.text; - var prop = getPropertyOfType(getTypeOfSymbol(symbol), name_7); + var name_11 = index.text; + var prop = getPropertyOfType(getTypeOfSymbol(symbol), name_11); return prop && (prop.flags & 3) !== 0 && (getDeclarationFlagsFromSymbol(prop) & 8192) !== 0; } return false; } - case 162: + case 164: return isConstVariableReference(n.expression); default: return false; @@ -14910,10 +16333,7 @@ var ts; return true; } function checkDeleteExpression(node) { - if (node.parserContextFlags & 1 && node.expression.kind === 65) { - grammarErrorOnNode(node.expression, ts.Diagnostics.delete_cannot_be_called_on_an_identifier_in_strict_mode); - } - var operandType = checkExpression(node.expression); + checkExpression(node.expression); return booleanType; } function checkTypeOfExpression(node) { @@ -14925,15 +16345,12 @@ var ts; return undefinedType; } function checkPrefixUnaryExpression(node) { - if ((node.operator === 38 || node.operator === 39)) { - checkGrammarEvalOrArgumentsInStrictMode(node, node.operand); - } var operandType = checkExpression(node.operand); switch (node.operator) { case 33: case 34: case 47: - if (someConstituentTypeHasKind(operandType, 1048576)) { + if (someConstituentTypeHasKind(operandType, 2097152)) { error(node.operand, ts.Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, ts.tokenToString(node.operator)); } return numberType; @@ -14950,7 +16367,6 @@ var ts; return unknownType; } function checkPostfixUnaryExpression(node) { - checkGrammarEvalOrArgumentsInStrictMode(node, node.operand); var operandType = checkExpression(node.operand); var ok = checkArithmeticOperandType(node.operand, operandType, ts.Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type); if (ok) { @@ -14997,19 +16413,19 @@ var ts; return (symbol.flags & 128) !== 0; } function checkInstanceOfExpression(node, leftType, rightType) { - if (allConstituentTypesHaveKind(leftType, 1049086)) { + if (allConstituentTypesHaveKind(leftType, 2097662)) { error(node.left, ts.Diagnostics.The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_parameter); } - if (!(rightType.flags & 1 || isTypeSubtypeOf(rightType, globalFunctionType))) { + if (!(isTypeAny(rightType) || isTypeSubtypeOf(rightType, globalFunctionType))) { error(node.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(node, leftType, rightType) { - if (!allConstituentTypesHaveKind(leftType, 1 | 258 | 132 | 1048576)) { + if (!isTypeAnyOrAllConstituentTypesHaveKind(leftType, 258 | 132 | 2097152)) { error(node.left, ts.Diagnostics.The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol); } - if (!allConstituentTypesHaveKind(rightType, 1 | 48128 | 512)) { + if (!isTypeAnyOrAllConstituentTypesHaveKind(rightType, 48128 | 512)) { error(node.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; @@ -15018,17 +16434,18 @@ var ts; var properties = node.properties; for (var _i = 0; _i < properties.length; _i++) { var p = properties[_i]; - if (p.kind === 225 || p.kind === 226) { - var name_8 = p.name; - var type = sourceType.flags & 1 ? sourceType : - getTypeOfPropertyOfType(sourceType, name_8.text) || - isNumericLiteralName(name_8.text) && getIndexTypeOfType(sourceType, 1) || + if (p.kind === 227 || p.kind === 228) { + var name_12 = p.name; + var type = isTypeAny(sourceType) + ? sourceType + : getTypeOfPropertyOfType(sourceType, name_12.text) || + isNumericLiteralName(name_12.text) && getIndexTypeOfType(sourceType, 1) || getIndexTypeOfType(sourceType, 0); if (type) { - checkDestructuringAssignment(p.initializer || name_8, type); + checkDestructuringAssignment(p.initializer || name_12, type); } else { - error(name_8, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(sourceType), ts.declarationNameToString(name_8)); + error(name_12, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(sourceType), ts.declarationNameToString(name_12)); } } else { @@ -15042,11 +16459,12 @@ var ts; var elements = node.elements; for (var i = 0; i < elements.length; i++) { var e = elements[i]; - if (e.kind !== 176) { - if (e.kind !== 174) { + if (e.kind !== 178) { + if (e.kind !== 176) { var propName = "" + i; - var type = sourceType.flags & 1 ? sourceType : - isTupleLikeType(sourceType) + var type = isTypeAny(sourceType) + ? sourceType + : isTupleLikeType(sourceType) ? getTypeOfPropertyOfType(sourceType, propName) : elementType; if (type) { @@ -15067,7 +16485,7 @@ var ts; } else { var restExpression = e.expression; - if (restExpression.kind === 170 && restExpression.operatorToken.kind === 53) { + if (restExpression.kind === 172 && restExpression.operatorToken.kind === 53) { error(restExpression.operatorToken, ts.Diagnostics.A_rest_element_cannot_have_an_initializer); } else { @@ -15080,14 +16498,14 @@ var ts; return sourceType; } function checkDestructuringAssignment(target, sourceType, contextualMapper) { - if (target.kind === 170 && target.operatorToken.kind === 53) { + if (target.kind === 172 && target.operatorToken.kind === 53) { checkBinaryExpression(target, contextualMapper); target = target.left; } - if (target.kind === 155) { + if (target.kind === 157) { return checkObjectLiteralAssignment(target, sourceType, contextualMapper); } - if (target.kind === 154) { + if (target.kind === 156) { return checkArrayLiteralAssignment(target, sourceType, contextualMapper); } return checkReferenceAssignment(target, sourceType, contextualMapper); @@ -15100,11 +16518,8 @@ var ts; return sourceType; } function checkBinaryExpression(node, contextualMapper) { - if (ts.isLeftHandSideExpression(node.left) && ts.isAssignmentOperator(node.operatorToken.kind)) { - checkGrammarEvalOrArgumentsInStrictMode(node, node.left); - } var operator = node.operatorToken.kind; - if (operator === 53 && (node.left.kind === 155 || node.left.kind === 154)) { + if (operator === 53 && (node.left.kind === 157 || node.left.kind === 156)) { return checkDestructuringAssignment(node.left, checkExpression(node.right, contextualMapper), contextualMapper); } var leftType = checkExpression(node.left, contextualMapper); @@ -15162,8 +16577,8 @@ var ts; if (allConstituentTypesHaveKind(leftType, 258) || allConstituentTypesHaveKind(rightType, 258)) { resultType = stringType; } - else if (leftType.flags & 1 || rightType.flags & 1) { - resultType = anyType; + else if (isTypeAny(leftType) || isTypeAny(rightType)) { + resultType = leftType === unknownType || rightType === unknownType ? unknownType : anyType; } if (resultType && !checkForDisallowedESSymbolOperand(operator)) { return resultType; @@ -15207,8 +16622,8 @@ var ts; return rightType; } function checkForDisallowedESSymbolOperand(operator) { - var offendingSymbolOperand = someConstituentTypeHasKind(leftType, 1048576) ? node.left : - someConstituentTypeHasKind(rightType, 1048576) ? node.right : + var offendingSymbolOperand = someConstituentTypeHasKind(leftType, 2097152) ? node.left : + someConstituentTypeHasKind(rightType, 2097152) ? node.right : undefined; if (offendingSymbolOperand) { error(offendingSymbolOperand, ts.Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, ts.tokenToString(operator)); @@ -15243,13 +16658,46 @@ var ts; error(node, ts.Diagnostics.Operator_0_cannot_be_applied_to_types_1_and_2, ts.tokenToString(node.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 (current.kind === 204 || current.kind === 177) { + return true; + } + current = parent; + parent = parent.parent; + } + return false; + } function checkYieldExpression(node) { - if (!(node.parserContextFlags & 4)) { - grammarErrorOnFirstToken(node, ts.Diagnostics.yield_expression_must_be_contained_within_a_generator_declaration); + if (!(node.parserContextFlags & 4) || isYieldExpressionInClass(node)) { + grammarErrorOnFirstToken(node, ts.Diagnostics.A_yield_expression_is_only_allowed_in_a_generator_body); } - else { - grammarErrorOnFirstToken(node, ts.Diagnostics.yield_expressions_are_not_currently_supported); + if (node.expression) { + var func = ts.getContainingFunction(node); + if (func && func.asteriskToken) { + var expressionType = checkExpressionCached(node.expression, undefined); + var expressionElementType; + var nodeIsYieldStar = !!node.asteriskToken; + if (nodeIsYieldStar) { + expressionElementType = checkElementTypeOfIterable(expressionType, node.expression); + } + if (func.type) { + var signatureElementType = getElementTypeOfIterableIterator(getTypeFromTypeNode(func.type)) || anyType; + if (nodeIsYieldStar) { + checkTypeAssignableTo(expressionElementType, signatureElementType, node.expression, undefined); + } + else { + checkTypeAssignableTo(expressionType, signatureElementType, node.expression, undefined); + } + } + } } + return anyType; } function checkConditionalExpression(node, contextualMapper) { checkExpression(node.condition); @@ -15278,14 +16726,14 @@ var ts; return links.resolvedType; } function checkPropertyAssignment(node, contextualMapper) { - if (node.name.kind === 128) { + if (node.name.kind === 129) { checkComputedPropertyName(node.name); } return checkExpression(node.initializer, contextualMapper); } function checkObjectLiteralMethod(node, contextualMapper) { checkGrammarMethod(node); - if (node.name.kind === 128) { + if (node.name.kind === 129) { checkComputedPropertyName(node.name); } var uninstantiatedType = checkFunctionExpressionOrObjectLiteralMethod(node, contextualMapper); @@ -15307,12 +16755,8 @@ var ts; return type; } function checkExpression(node, contextualMapper) { - checkGrammarIdentifierInStrictMode(node); - return checkExpressionOrQualifiedName(node, contextualMapper); - } - function checkExpressionOrQualifiedName(node, contextualMapper) { var type; - if (node.kind == 127) { + if (node.kind === 128) { type = checkQualifiedName(node); } else { @@ -15320,9 +16764,9 @@ var ts; type = instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, contextualMapper); } if (isConstEnumObjectType(type)) { - var ok = (node.parent.kind === 156 && node.parent.expression === node) || - (node.parent.kind === 157 && node.parent.expression === node) || - ((node.kind === 65 || node.kind === 127) && isInRightSideOfImportOrExportAssignment(node)); + var ok = (node.parent.kind === 158 && node.parent.expression === node) || + (node.parent.kind === 159 && node.parent.expression === node) || + ((node.kind === 65 || node.kind === 128) && 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); } @@ -15348,61 +16792,59 @@ var ts; return booleanType; case 7: return checkNumericLiteral(node); - case 172: + case 174: return checkTemplateExpression(node); case 8: case 10: return stringType; case 9: return globalRegExpType; - case 154: - return checkArrayLiteral(node, contextualMapper); - case 155: - return checkObjectLiteral(node, contextualMapper); case 156: - return checkPropertyAccessExpression(node); + return checkArrayLiteral(node, contextualMapper); case 157: - return checkIndexedAccess(node); + return checkObjectLiteral(node, contextualMapper); case 158: + return checkPropertyAccessExpression(node); case 159: - return checkCallExpression(node); + return checkIndexedAccess(node); case 160: - return checkTaggedTemplateExpression(node); case 161: - return checkTypeAssertion(node); + return checkCallExpression(node); case 162: - return checkExpression(node.expression, contextualMapper); - case 175: - return checkClassExpression(node); + return checkTaggedTemplateExpression(node); case 163: + return checkTypeAssertion(node); case 164: - return checkFunctionExpressionOrObjectLiteralMethod(node, contextualMapper); - case 166: - return checkTypeOfExpression(node); + return checkExpression(node.expression, contextualMapper); + case 177: + return checkClassExpression(node); case 165: - return checkDeleteExpression(node); - case 167: - return checkVoidExpression(node); + case 166: + return checkFunctionExpressionOrObjectLiteralMethod(node, contextualMapper); case 168: - return checkPrefixUnaryExpression(node); + return checkTypeOfExpression(node); + case 167: + return checkDeleteExpression(node); case 169: - return checkPostfixUnaryExpression(node); + return checkVoidExpression(node); case 170: - return checkBinaryExpression(node, contextualMapper); + return checkPrefixUnaryExpression(node); case 171: - return checkConditionalExpression(node, contextualMapper); - case 174: - return checkSpreadElementExpression(node, contextualMapper); - case 176: - return undefinedType; + return checkPostfixUnaryExpression(node); + case 172: + return checkBinaryExpression(node, contextualMapper); case 173: - checkYieldExpression(node); - return unknownType; + return checkConditionalExpression(node, contextualMapper); + case 176: + return checkSpreadElementExpression(node, contextualMapper); + case 178: + return undefinedType; + case 175: + return checkYieldExpression(node); } return unknownType; } function checkTypeParameter(node) { - checkGrammarDeclarationNameInStrictMode(node); if (node.expression) { grammarErrorOnFirstToken(node.expression, ts.Diagnostics.Type_expected); } @@ -15417,14 +16859,12 @@ var ts; // 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). - // It is a SyntaxError if the identifier eval or arguments appears within a FormalParameterList of a - // strict mode FunctionLikeDeclaration or FunctionExpression(13.1) - checkGrammarDecorators(node) || checkGrammarModifiers(node) || checkGrammarEvalOrArgumentsInStrictMode(node, node.name); + checkGrammarDecorators(node) || checkGrammarModifiers(node); checkVariableLikeDeclaration(node); var func = ts.getContainingFunction(node); if (node.flags & 112) { func = ts.getContainingFunction(node); - if (!(func.kind === 136 && ts.nodeIsPresent(func.body))) { + if (!(func.kind === 137 && ts.nodeIsPresent(func.body))) { error(node, ts.Diagnostics.A_parameter_property_is_only_allowed_in_a_constructor_implementation); } } @@ -15435,37 +16875,132 @@ var ts; error(node, ts.Diagnostics.A_rest_parameter_must_be_of_an_array_type); } } + function isSyntacticallyValidGenerator(node) { + if (!node.asteriskToken || !node.body) { + return false; + } + return node.kind === 136 || + node.kind === 203 || + node.kind === 165; + } + function getTypePredicateParameterIndex(parameterList, parameter) { + if (parameterList) { + for (var i = 0; i < parameterList.length; i++) { + var param = parameterList[i]; + if (param.name.kind === 65 && + param.name.text === parameter.text) { + return i; + } + } + } + return -1; + } + function isInLegalTypePredicatePosition(node) { + switch (node.parent.kind) { + case 166: + case 140: + case 203: + case 165: + case 145: + case 136: + case 135: + return node === node.parent.type; + } + return false; + } function checkSignatureDeclaration(node) { - if (node.kind === 141) { + if (node.kind === 142) { checkGrammarIndexSignature(node); } - else if (node.kind === 143 || node.kind === 201 || node.kind === 144 || - node.kind === 139 || node.kind === 136 || - node.kind === 140) { + else if (node.kind === 145 || node.kind === 203 || node.kind === 146 || + node.kind === 140 || node.kind === 137 || + node.kind === 141) { checkGrammarFunctionLikeDeclaration(node); } checkTypeParameters(node.typeParameters); ts.forEach(node.parameters, checkParameter); if (node.type) { - checkSourceElement(node.type); + if (node.type.kind === 143) { + var typePredicate = getSignatureFromDeclaration(node).typePredicate; + var typePredicateNode = node.type; + if (isInLegalTypePredicatePosition(typePredicateNode)) { + if (typePredicate.parameterIndex >= 0) { + if (node.parameters[typePredicate.parameterIndex].dotDotDotToken) { + error(typePredicateNode.parameterName, ts.Diagnostics.A_type_predicate_cannot_reference_a_rest_parameter); + } + else { + checkTypeAssignableTo(typePredicate.type, getTypeAtLocation(node.parameters[typePredicate.parameterIndex]), typePredicateNode.type); + } + } + else if (typePredicateNode.parameterName) { + var hasReportedError = false; + for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) { + var param = _a[_i]; + if (hasReportedError) { + break; + } + if (param.name.kind === 153 || + param.name.kind === 154) { + (function checkBindingPattern(pattern) { + for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) { + var element = _a[_i]; + if (element.name.kind === 65 && + element.name.text === typePredicate.parameterName) { + error(typePredicateNode.parameterName, ts.Diagnostics.A_type_predicate_cannot_reference_element_0_in_a_binding_pattern, typePredicate.parameterName); + hasReportedError = true; + break; + } + else if (element.name.kind === 154 || + element.name.kind === 153) { + checkBindingPattern(element.name); + } + } + })(param.name); + } + } + if (!hasReportedError) { + error(typePredicateNode.parameterName, ts.Diagnostics.Cannot_find_parameter_0, typePredicate.parameterName); + } + } + } + else { + error(typePredicateNode, ts.Diagnostics.A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods); + } + } + else { + checkSourceElement(node.type); + } } if (produceDiagnostics) { checkCollisionWithArgumentsInGeneratedCode(node); if (compilerOptions.noImplicitAny && !node.type) { switch (node.kind) { - case 140: + case 141: error(node, ts.Diagnostics.Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type); break; - case 139: + case 140: error(node, ts.Diagnostics.Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type); break; } } + if (node.type) { + if (languageVersion >= 2 && isSyntacticallyValidGenerator(node)) { + var returnType = getTypeFromTypeNode(node.type); + if (returnType === voidType) { + error(node.type, ts.Diagnostics.A_generator_cannot_have_a_void_type_annotation); + } + else { + var generatorElementType = getElementTypeOfIterableIterator(returnType) || anyType; + var iterableIteratorInstantiation = createIterableIteratorType(generatorElementType); + checkTypeAssignableTo(iterableIteratorInstantiation, returnType, node.type); + } + } + } } checkSpecializedSignatureDeclaration(node); } function checkTypeForDuplicateIndexSignatures(node) { - if (node.kind === 203) { + if (node.kind === 205) { var nodeSymbol = getSymbolOfNode(node); if (nodeSymbol.declarations.length > 0 && nodeSymbol.declarations[0] !== node) { return; @@ -15480,7 +17015,7 @@ var ts; var declaration = decl; if (declaration.parameters.length === 1 && declaration.parameters[0].type) { switch (declaration.parameters[0].type.kind) { - case 122: + case 123: if (!seenStringIndexer) { seenStringIndexer = true; } @@ -15488,7 +17023,7 @@ var ts; error(declaration, ts.Diagnostics.Duplicate_string_index_signature); } break; - case 120: + case 121: if (!seenNumericIndexer) { seenNumericIndexer = true; } @@ -15525,17 +17060,17 @@ var ts; return; } function isSuperCallExpression(n) { - return n.kind === 158 && n.expression.kind === 91; + return n.kind === 160 && n.expression.kind === 91; } function containsSuperCall(n) { if (isSuperCallExpression(n)) { return true; } switch (n.kind) { - case 163: - case 201: - case 164: - case 155: return false; + case 165: + case 203: + case 166: + case 157: return false; default: return ts.forEachChild(n, containsSuperCall); } } @@ -15543,12 +17078,12 @@ var ts; if (n.kind === 93) { error(n, ts.Diagnostics.this_cannot_be_referenced_in_current_location); } - else if (n.kind !== 163 && n.kind !== 201) { + else if (n.kind !== 165 && n.kind !== 203) { ts.forEachChild(n, markThisReferencesAsErrors); } } function isInstancePropertyWithInitializer(n) { - return n.kind === 133 && + return n.kind === 134 && !(n.flags & 128) && !!n.initializer; } @@ -15558,7 +17093,7 @@ var ts; ts.forEach(node.parameters, function (p) { return p.flags & (16 | 32 | 64); }); if (superCallShouldBeFirst) { var statements = node.body.statements; - if (!statements.length || statements[0].kind !== 183 || !isSuperCallExpression(statements[0].expression)) { + if (!statements.length || statements[0].kind !== 185 || !isSuperCallExpression(statements[0].expression)) { 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 { @@ -15574,13 +17109,13 @@ var ts; function checkAccessorDeclaration(node) { if (produceDiagnostics) { checkGrammarFunctionLikeDeclaration(node) || checkGrammarAccessor(node) || checkGrammarComputedPropertyName(node.name); - if (node.kind === 137) { + if (node.kind === 138) { if (!ts.isInAmbientContext(node) && ts.nodeIsPresent(node.body) && !(bodyContainsAReturnStatement(node.body) || bodyContainsSingleThrowStatement(node.body))) { error(node.name, ts.Diagnostics.A_get_accessor_must_return_a_value_or_consist_of_a_single_throw_statement); } } if (!ts.hasDynamicName(node)) { - var otherKind = node.kind === 137 ? 138 : 137; + var otherKind = node.kind === 138 ? 139 : 138; var otherAccessor = ts.getDeclarationOfKind(node.symbol, otherKind); if (otherAccessor) { if (((node.flags & 112) !== (otherAccessor.flags & 112))) { @@ -15602,26 +17137,26 @@ var ts; function checkMissingDeclaration(node) { checkDecorators(node); } + function checkTypeArgumentConstraints(typeParameters, typeArguments) { + var result = true; + for (var i = 0; i < typeParameters.length; i++) { + var constraint = getConstraintOfTypeParameter(typeParameters[i]); + if (constraint) { + var typeArgument = typeArguments[i]; + result = result && checkTypeAssignableTo(getTypeFromTypeNode(typeArgument), constraint, typeArgument, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); + } + } + return result; + } function checkTypeReferenceNode(node) { - checkGrammarTypeReferenceInStrictMode(node.typeName); - return checkTypeReferenceOrExpressionWithTypeArguments(node); - } - function checkExpressionWithTypeArguments(node) { - checkGrammarExpressionWithTypeArgumentsInStrictMode(node.expression); - return checkTypeReferenceOrExpressionWithTypeArguments(node); - } - function checkTypeReferenceOrExpressionWithTypeArguments(node) { checkGrammarTypeArguments(node, node.typeArguments); - var type = getTypeFromTypeReferenceOrExpressionWithTypeArguments(node); + var type = getTypeFromTypeReference(node); if (type !== unknownType && node.typeArguments) { - var len = node.typeArguments.length; - for (var i = 0; i < len; i++) { - checkSourceElement(node.typeArguments[i]); - var constraint = getConstraintOfTypeParameter(type.target.typeParameters[i]); - if (produceDiagnostics && constraint) { - var typeArgument = type.typeArguments[i]; - checkTypeAssignableTo(typeArgument, constraint, node, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); - } + 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); } } } @@ -15665,9 +17200,9 @@ var ts; return; } var signaturesToCheck; - if (!signatureDeclarationNode.name && signatureDeclarationNode.parent && signatureDeclarationNode.parent.kind === 203) { - ts.Debug.assert(signatureDeclarationNode.kind === 139 || signatureDeclarationNode.kind === 140); - var signatureKind = signatureDeclarationNode.kind === 139 ? 0 : 1; + if (!signatureDeclarationNode.name && signatureDeclarationNode.parent && signatureDeclarationNode.parent.kind === 205) { + ts.Debug.assert(signatureDeclarationNode.kind === 140 || signatureDeclarationNode.kind === 141); + var signatureKind = signatureDeclarationNode.kind === 140 ? 0 : 1; var containingSymbol = getSymbolOfNode(signatureDeclarationNode.parent); var containingType = getDeclaredTypeOfSymbol(containingSymbol); signaturesToCheck = getSignaturesOfType(containingType, signatureKind); @@ -15685,7 +17220,7 @@ var ts; } function getEffectiveDeclarationFlags(n, flagsToCheck) { var flags = ts.getCombinedNodeFlags(n); - if (n.parent.kind !== 203 && ts.isInAmbientContext(n)) { + if (n.parent.kind !== 205 && ts.isInAmbientContext(n)) { if (!(flags & 2)) { flags |= 1; } @@ -15758,7 +17293,7 @@ var ts; if (subsequentNode.kind === node.kind) { var errorNode_1 = subsequentNode.name || subsequentNode; if (node.name && subsequentNode.name && node.name.text === subsequentNode.name.text) { - ts.Debug.assert(node.kind === 135 || node.kind === 134); + ts.Debug.assert(node.kind === 136 || node.kind === 135); ts.Debug.assert((node.flags & 128) !== (subsequentNode.flags & 128)); var diagnostic = node.flags & 128 ? ts.Diagnostics.Function_overload_must_be_static : ts.Diagnostics.Function_overload_must_not_be_static; error(errorNode_1, diagnostic); @@ -15785,11 +17320,11 @@ var ts; var current = declarations[_i]; var node = current; var inAmbientContext = ts.isInAmbientContext(node); - var inAmbientContextOrInterface = node.parent.kind === 203 || node.parent.kind === 146 || inAmbientContext; + var inAmbientContextOrInterface = node.parent.kind === 205 || node.parent.kind === 148 || inAmbientContext; if (inAmbientContextOrInterface) { previousDeclaration = undefined; } - if (node.kind === 201 || node.kind === 135 || node.kind === 134 || node.kind === 136) { + if (node.kind === 203 || node.kind === 136 || node.kind === 135 || node.kind === 137) { var currentNodeFlags = getEffectiveDeclarationFlags(node, flagsToCheck); someNodeFlags |= currentNodeFlags; allNodeFlags &= currentNodeFlags; @@ -15886,16 +17421,16 @@ var ts; } function getDeclarationSpaces(d) { switch (d.kind) { - case 203: + case 205: return 2097152; - case 206: + case 208: return d.name.kind === 8 || ts.getModuleInstanceState(d) !== 0 ? 4194304 | 1048576 : 4194304; - case 202: - case 205: + case 204: + case 207: return 2097152 | 1048576; - case 209: + case 211: var result = 0; var target = resolveAlias(getSymbolOfNode(d)); ts.forEach(target.declarations, function (d) { result |= getDeclarationSpaces(d); }); @@ -15909,54 +17444,54 @@ var ts; var expression = node.expression; var exprType = checkExpression(expression); switch (node.parent.kind) { - case 202: + case 204: var classSymbol = getSymbolOfNode(node.parent); var classConstructorType = getTypeOfSymbol(classSymbol); var classDecoratorType = instantiateSingleCallFunctionType(getGlobalClassDecoratorType(), [classConstructorType]); checkTypeAssignableTo(exprType, classDecoratorType, node); break; - case 133: + case 134: checkTypeAssignableTo(exprType, getGlobalPropertyDecoratorType(), node); break; - case 135: - case 137: + case 136: case 138: + case 139: var methodType = getTypeOfNode(node.parent); var methodDecoratorType = instantiateSingleCallFunctionType(getGlobalMethodDecoratorType(), [methodType]); checkTypeAssignableTo(exprType, methodDecoratorType, node); break; - case 130: + case 131: checkTypeAssignableTo(exprType, getGlobalParameterDecoratorType(), node); break; } } function checkTypeNodeAsExpression(node) { - if (node && node.kind === 142) { + if (node && node.kind === 144) { var type = getTypeFromTypeNode(node); - var shouldCheckIfUnknownType = type === unknownType && compilerOptions.separateCompilation; - if (!type || (!shouldCheckIfUnknownType && type.flags & (1048703 | 132 | 258))) { + var shouldCheckIfUnknownType = type === unknownType && compilerOptions.isolatedModules; + if (!type || (!shouldCheckIfUnknownType && type.flags & (2097279 | 132 | 258))) { return; } if (shouldCheckIfUnknownType || type.symbol.valueDeclaration) { - checkExpressionOrQualifiedName(node.typeName); + checkExpression(node.typeName); } } } function checkTypeAnnotationAsExpression(node) { switch (node.kind) { - case 133: + case 134: checkTypeNodeAsExpression(node.type); break; - case 130: + case 131: checkTypeNodeAsExpression(node.type); break; - case 135: - checkTypeNodeAsExpression(node.type); - break; - case 137: + case 136: checkTypeNodeAsExpression(node.type); break; case 138: + checkTypeNodeAsExpression(node.type); + break; + case 139: checkTypeNodeAsExpression(getSetAccessorTypeAnnotationNode(node)); break; } @@ -15974,46 +17509,45 @@ var ts; 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_Specify_experimentalDecorators_to_remove_this_warning); + } if (compilerOptions.emitDecoratorMetadata) { switch (node.kind) { - case 202: + case 204: var constructor = ts.getFirstConstructorWithBody(node); if (constructor) { checkParameterTypeAnnotationsAsExpressions(constructor); } break; - case 135: + case 136: checkParameterTypeAnnotationsAsExpressions(node); + case 139: case 138: - case 137: - case 133: - case 130: + case 134: + case 131: checkTypeAnnotationAsExpression(node); break; } } emitDecorate = true; - if (node.kind === 130) { + if (node.kind === 131) { emitParam = true; } ts.forEach(node.decorators, checkDecorator); } function checkFunctionDeclaration(node) { if (produceDiagnostics) { - checkFunctionLikeDeclaration(node) || - checkGrammarDisallowedModifiersInBlockOrObjectLiteralExpression(node) || - checkGrammarFunctionName(node.name) || - checkGrammarForGenerator(node); + checkFunctionLikeDeclaration(node) || checkGrammarForGenerator(node); checkCollisionWithCapturedSuperVariable(node, node.name); checkCollisionWithCapturedThisVariable(node, node.name); checkCollisionWithRequireExportsInGeneratedCode(node, node.name); } } function checkFunctionLikeDeclaration(node) { - checkGrammarDeclarationNameInStrictMode(node); checkDecorators(node); checkSignatureDeclaration(node); - if (node.name && node.name.kind === 128) { + if (node.name && node.name.kind === 129) { checkComputedPropertyName(node.name); } if (!ts.hasDynamicName(node)) { @@ -16033,21 +17567,26 @@ var ts; if (node.type && !isAccessor(node.kind) && !node.asteriskToken) { checkIfNonVoidFunctionHasReturnExpressionsOrSingleThrowStatment(node, getTypeFromTypeNode(node.type)); } - if (compilerOptions.noImplicitAny && ts.nodeIsMissing(node.body) && !node.type && !isPrivateWithinAmbient(node)) { - reportImplicitAnyError(node, anyType); + if (produceDiagnostics && !node.type) { + if (compilerOptions.noImplicitAny && ts.nodeIsMissing(node.body) && !isPrivateWithinAmbient(node)) { + reportImplicitAnyError(node, anyType); + } + if (node.asteriskToken && ts.nodeIsPresent(node.body)) { + getReturnTypeOfSignature(getSignatureFromDeclaration(node)); + } } } function checkBlock(node) { - if (node.kind === 180) { + if (node.kind === 182) { checkGrammarStatementInAmbientContext(node); } ts.forEach(node.statements, checkSourceElement); - if (ts.isFunctionBlock(node) || node.kind === 207) { + if (ts.isFunctionBlock(node) || node.kind === 209) { checkFunctionExpressionBodies(node); } } function checkCollisionWithArgumentsInGeneratedCode(node) { - if (!ts.hasRestParameters(node) || ts.isInAmbientContext(node) || ts.nodeIsMissing(node.body)) { + if (!ts.hasRestParameter(node) || ts.isInAmbientContext(node) || ts.nodeIsMissing(node.body)) { return; } ts.forEach(node.parameters, function (p) { @@ -16060,19 +17599,19 @@ var ts; if (!(identifier && identifier.text === name)) { return false; } - if (node.kind === 133 || - node.kind === 132 || + if (node.kind === 134 || + node.kind === 133 || + node.kind === 136 || node.kind === 135 || - node.kind === 134 || - node.kind === 137 || - node.kind === 138) { + node.kind === 138 || + node.kind === 139) { return false; } if (ts.isInAmbientContext(node)) { return false; } var root = ts.getRootDeclaration(node); - if (root.kind === 130 && ts.nodeIsMissing(root.parent.body)) { + if (root.kind === 131 && ts.nodeIsMissing(root.parent.body)) { return false; } return true; @@ -16102,7 +17641,7 @@ var ts; if (!needCollisionCheckForIdentifier(node, name, "_super")) { return; } - var enclosingClass = ts.getAncestor(node, 202); + var enclosingClass = ts.getAncestor(node, 204); if (!enclosingClass || ts.isInAmbientContext(enclosingClass)) { return; } @@ -16120,11 +17659,11 @@ var ts; if (!needCollisionCheckForIdentifier(node, name, "require") && !needCollisionCheckForIdentifier(node, name, "exports")) { return; } - if (node.kind === 206 && ts.getModuleInstanceState(node) !== 1) { + if (node.kind === 208 && ts.getModuleInstanceState(node) !== 1) { return; } var parent = getDeclarationContainer(node); - if (parent.kind === 228 && ts.isExternalModule(parent)) { + if (parent.kind === 230 && ts.isExternalModule(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)); } } @@ -16135,7 +17674,7 @@ var ts; if ((ts.getCombinedNodeFlags(node) & 12288) !== 0 || ts.isParameterDeclaration(node)) { return; } - if (node.kind === 199 && !node.initializer) { + if (node.kind === 201 && !node.initializer) { return; } var symbol = getSymbolOfNode(node); @@ -16145,25 +17684,25 @@ var ts; localDeclarationSymbol !== symbol && localDeclarationSymbol.flags & 2) { if (getDeclarationFlagsFromSymbol(localDeclarationSymbol) & 12288) { - var varDeclList = ts.getAncestor(localDeclarationSymbol.valueDeclaration, 200); - var container = varDeclList.parent.kind === 181 && varDeclList.parent.parent + var varDeclList = ts.getAncestor(localDeclarationSymbol.valueDeclaration, 202); + var container = varDeclList.parent.kind === 183 && varDeclList.parent.parent ? varDeclList.parent.parent : undefined; var namesShareScope = container && - (container.kind === 180 && ts.isFunctionLike(container.parent) || - container.kind === 207 || - container.kind === 206 || - container.kind === 228); + (container.kind === 182 && ts.isFunctionLike(container.parent) || + container.kind === 209 || + container.kind === 208 || + container.kind === 230); if (!namesShareScope) { - var name_9 = symbolToString(localDeclarationSymbol); - error(node, ts.Diagnostics.Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1, name_9, name_9); + var name_13 = symbolToString(localDeclarationSymbol); + error(node, ts.Diagnostics.Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1, name_13, name_13); } } } } } function checkParameterInitializer(node) { - if (ts.getRootDeclaration(node).kind !== 130) { + if (ts.getRootDeclaration(node).kind !== 131) { return; } var func = ts.getContainingFunction(node); @@ -16172,7 +17711,7 @@ var ts; if (n.kind === 65) { var referencedSymbol = getNodeLinks(n).resolvedSymbol; if (referencedSymbol && referencedSymbol !== unknownSymbol && getSymbol(func.locals, referencedSymbol.name, 107455) === referencedSymbol) { - if (referencedSymbol.valueDeclaration.kind === 130) { + if (referencedSymbol.valueDeclaration.kind === 131) { if (referencedSymbol.valueDeclaration === node) { error(n, ts.Diagnostics.Parameter_0_cannot_be_referenced_in_its_initializer, ts.declarationNameToString(node.name)); return; @@ -16190,10 +17729,9 @@ var ts; } } function checkVariableLikeDeclaration(node) { - checkGrammarDeclarationNameInStrictMode(node); checkDecorators(node); checkSourceElement(node.type); - if (node.name.kind === 128) { + if (node.name.kind === 129) { checkComputedPropertyName(node.name); if (node.initializer) { checkExpressionCached(node.initializer); @@ -16202,7 +17740,7 @@ var ts; if (ts.isBindingPattern(node.name)) { ts.forEach(node.name.elements, checkSourceElement); } - if (node.initializer && ts.getRootDeclaration(node).kind === 130 && ts.nodeIsMissing(ts.getContainingFunction(node).body)) { + if (node.initializer && ts.getRootDeclaration(node).kind === 131 && ts.nodeIsMissing(ts.getContainingFunction(node).body)) { error(node, ts.Diagnostics.A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation); return; } @@ -16230,9 +17768,9 @@ var ts; checkTypeAssignableTo(checkExpressionCached(node.initializer), declarationType, node, undefined); } } - if (node.kind !== 133 && node.kind !== 132) { + if (node.kind !== 134 && node.kind !== 133) { checkExportsOnMergedDeclarations(node); - if (node.kind === 199 || node.kind === 153) { + if (node.kind === 201 || node.kind === 155) { checkVarDeclaredNamesNotShadowed(node); } checkCollisionWithCapturedSuperVariable(node, node.name); @@ -16249,7 +17787,7 @@ var ts; return checkVariableLikeDeclaration(node); } function checkVariableStatement(node) { - checkGrammarDecorators(node) || checkGrammarDisallowedModifiersInBlockOrObjectLiteralExpression(node) || checkGrammarModifiers(node) || checkGrammarVariableDeclarationList(node.declarationList) || checkGrammarForDisallowedLetOrConstStatement(node); + checkGrammarDecorators(node) || checkGrammarModifiers(node) || checkGrammarVariableDeclarationList(node.declarationList) || checkGrammarForDisallowedLetOrConstStatement(node); ts.forEach(node.declarationList.declarations, checkSourceElement); } function checkGrammarDisallowedModifiersInBlockOrObjectLiteralExpression(node) { @@ -16261,7 +17799,7 @@ var ts; } function inBlockOrObjectLiteralExpression(node) { while (node) { - if (node.kind === 180 || node.kind === 155) { + if (node.kind === 182 || node.kind === 157) { return true; } node = node.parent; @@ -16289,12 +17827,12 @@ var ts; } function checkForStatement(node) { if (!checkGrammarStatementInAmbientContext(node)) { - if (node.initializer && node.initializer.kind == 200) { + if (node.initializer && node.initializer.kind === 202) { checkGrammarVariableDeclarationList(node.initializer); } } if (node.initializer) { - if (node.initializer.kind === 200) { + if (node.initializer.kind === 202) { ts.forEach(node.initializer.declarations, checkVariableDeclaration); } else { @@ -16309,13 +17847,13 @@ var ts; } function checkForOfStatement(node) { checkGrammarForInOrForOfStatement(node); - if (node.initializer.kind === 200) { + if (node.initializer.kind === 202) { checkForInOrForOfVariableDeclaration(node); } else { var varExpr = node.initializer; var iteratedType = checkRightHandSideOfForOf(node.expression); - if (varExpr.kind === 154 || varExpr.kind === 155) { + if (varExpr.kind === 156 || varExpr.kind === 157) { checkDestructuringAssignment(varExpr, iteratedType || unknownType); } else { @@ -16330,7 +17868,7 @@ var ts; } function checkForInStatement(node) { checkGrammarForInOrForOfStatement(node); - if (node.initializer.kind === 200) { + if (node.initializer.kind === 202) { 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); @@ -16340,10 +17878,10 @@ var ts; else { var varExpr = node.initializer; var leftType = checkExpression(varExpr); - if (varExpr.kind === 154 || varExpr.kind === 155) { + if (varExpr.kind === 156 || varExpr.kind === 157) { error(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern); } - else if (!allConstituentTypesHaveKind(leftType, 1 | 258)) { + else if (!isTypeAnyOrAllConstituentTypesHaveKind(leftType, 258)) { error(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any); } else { @@ -16351,7 +17889,7 @@ var ts; } } var rightType = checkExpression(node.expression); - if (!allConstituentTypesHaveKind(rightType, 1 | 48128 | 512)) { + if (!isTypeAnyOrAllConstituentTypesHaveKind(rightType, 48128 | 512)) { 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); @@ -16368,11 +17906,11 @@ var ts; return checkIteratedTypeOrElementType(expressionType, rhsExpression, true); } function checkIteratedTypeOrElementType(inputType, errorNode, allowStringInput) { - if (inputType.flags & 1) { + if (isTypeAny(inputType)) { return inputType; } if (languageVersion >= 2) { - return checkIteratedType(inputType, errorNode) || anyType; + return checkElementTypeOfIterable(inputType, errorNode); } if (allowStringInput) { return checkElementTypeOfArrayOrString(inputType, errorNode); @@ -16386,84 +17924,85 @@ var ts; error(errorNode, ts.Diagnostics.Type_0_is_not_an_array_type, typeToString(inputType)); return unknownType; } - function checkIteratedType(iterable, errorNode) { - ts.Debug.assert(languageVersion >= 2); - var iteratedType = getIteratedType(iterable, errorNode); - if (errorNode && iteratedType) { - checkTypeAssignableTo(iterable, createIterableType(iteratedType), errorNode); + function checkElementTypeOfIterable(iterable, errorNode) { + var elementType = getElementTypeOfIterable(iterable, errorNode); + if (errorNode && elementType) { + checkTypeAssignableTo(iterable, createIterableType(elementType), errorNode); } - return iteratedType; - function getIteratedType(iterable, errorNode) { - // 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]: { // iteratorFunction - // (): { // iterator - // next: { // iteratorNextFunction - // (): { // iteratorNextResult - // value: T // iteratorNextValue - // } - // } - // } - // } - // } - // - // 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'. - if (allConstituentTypesHaveKind(iterable, 1)) { - return undefined; - } - if ((iterable.flags & 4096) && iterable.target === globalIterableType) { - return iterable.typeArguments[0]; - } - var iteratorFunction = getTypeOfPropertyOfType(iterable, ts.getPropertyNameForKnownSymbolName("iterator")); - if (iteratorFunction && allConstituentTypesHaveKind(iteratorFunction, 1)) { - return undefined; - } - var iteratorFunctionSignatures = iteratorFunction ? getSignaturesOfType(iteratorFunction, 0) : emptyArray; - if (iteratorFunctionSignatures.length === 0) { - if (errorNode) { - error(errorNode, ts.Diagnostics.Type_must_have_a_Symbol_iterator_method_that_returns_an_iterator); - } - return undefined; - } - var iterator = getUnionType(ts.map(iteratorFunctionSignatures, getReturnTypeOfSignature)); - if (allConstituentTypesHaveKind(iterator, 1)) { - return undefined; - } - var iteratorNextFunction = getTypeOfPropertyOfType(iterator, "next"); - if (iteratorNextFunction && allConstituentTypesHaveKind(iteratorNextFunction, 1)) { - return undefined; - } - var iteratorNextFunctionSignatures = iteratorNextFunction ? getSignaturesOfType(iteratorNextFunction, 0) : emptyArray; - if (iteratorNextFunctionSignatures.length === 0) { - if (errorNode) { - error(errorNode, ts.Diagnostics.An_iterator_must_have_a_next_method); - } - return undefined; - } - var iteratorNextResult = getUnionType(ts.map(iteratorNextFunctionSignatures, getReturnTypeOfSignature)); - if (allConstituentTypesHaveKind(iteratorNextResult, 1)) { - return undefined; - } - var iteratorNextValue = getTypeOfPropertyOfType(iteratorNextResult, "value"); - if (!iteratorNextValue) { - if (errorNode) { - error(errorNode, ts.Diagnostics.The_type_returned_by_the_next_method_of_an_iterator_must_have_a_value_property); - } - return undefined; - } - return iteratorNextValue; + return elementType || anyType; + } + function getElementTypeOfIterable(type, errorNode) { + if (isTypeAny(type)) { + return undefined; } + var typeAsIterable = type; + if (!typeAsIterable.iterableElementType) { + if ((type.flags & 4096) && type.target === globalIterableType) { + typeAsIterable.iterableElementType = type.typeArguments[0]; + } + else { + var iteratorFunction = getTypeOfPropertyOfType(type, ts.getPropertyNameForKnownSymbolName("iterator")); + if (isTypeAny(iteratorFunction)) { + return undefined; + } + var iteratorFunctionSignatures = iteratorFunction ? getSignaturesOfType(iteratorFunction, 0) : emptyArray; + if (iteratorFunctionSignatures.length === 0) { + if (errorNode) { + error(errorNode, ts.Diagnostics.Type_must_have_a_Symbol_iterator_method_that_returns_an_iterator); + } + return undefined; + } + typeAsIterable.iterableElementType = getElementTypeOfIterator(getUnionType(ts.map(iteratorFunctionSignatures, getReturnTypeOfSignature)), errorNode); + } + } + return typeAsIterable.iterableElementType; + } + function getElementTypeOfIterator(type, errorNode) { + if (isTypeAny(type)) { + return undefined; + } + var typeAsIterator = type; + if (!typeAsIterator.iteratorElementType) { + if ((type.flags & 4096) && type.target === globalIteratorType) { + typeAsIterator.iteratorElementType = type.typeArguments[0]; + } + else { + var iteratorNextFunction = getTypeOfPropertyOfType(type, "next"); + if (isTypeAny(iteratorNextFunction)) { + return undefined; + } + var iteratorNextFunctionSignatures = iteratorNextFunction ? getSignaturesOfType(iteratorNextFunction, 0) : emptyArray; + if (iteratorNextFunctionSignatures.length === 0) { + if (errorNode) { + error(errorNode, ts.Diagnostics.An_iterator_must_have_a_next_method); + } + return undefined; + } + var iteratorNextResult = getUnionType(ts.map(iteratorNextFunctionSignatures, getReturnTypeOfSignature)); + if (isTypeAny(iteratorNextResult)) { + return undefined; + } + var iteratorNextValue = getTypeOfPropertyOfType(iteratorNextResult, "value"); + if (!iteratorNextValue) { + if (errorNode) { + error(errorNode, ts.Diagnostics.The_type_returned_by_the_next_method_of_an_iterator_must_have_a_value_property); + } + return undefined; + } + typeAsIterator.iteratorElementType = iteratorNextValue; + } + } + return typeAsIterator.iteratorElementType; + } + function getElementTypeOfIterableIterator(type) { + if (isTypeAny(type)) { + return undefined; + } + if ((type.flags & 4096) && type.target === globalIterableIteratorType) { + return type.typeArguments[0]; + } + return getElementTypeOfIterable(type, undefined) || + getElementTypeOfIterator(type, undefined); } function checkElementTypeOfArrayOrString(arrayOrStringType, errorNode) { ts.Debug.assert(languageVersion < 2); @@ -16501,7 +18040,7 @@ var ts; checkGrammarStatementInAmbientContext(node) || checkGrammarBreakOrContinueStatement(node); } function isGetAccessorWithAnnotatatedSetAccessor(node) { - return !!(node.kind === 137 && getSetAccessorTypeAnnotationNode(ts.getDeclarationOfKind(node.symbol, 138))); + return !!(node.kind === 138 && getSetAccessorTypeAnnotationNode(ts.getDeclarationOfKind(node.symbol, 139))); } function checkReturnStatement(node) { if (!checkGrammarStatementInAmbientContext(node)) { @@ -16513,30 +18052,28 @@ var ts; if (node.expression) { var func = ts.getContainingFunction(node); if (func) { - var returnType = getReturnTypeOfSignature(getSignatureFromDeclaration(func)); + var signature = getSignatureFromDeclaration(func); + var returnType = getReturnTypeOfSignature(signature); var exprType = checkExpressionCached(node.expression); - if (func.kind === 138) { + if (func.asteriskToken) { + return; + } + if (func.kind === 139) { error(node.expression, ts.Diagnostics.Setters_cannot_return_a_value); } - else { - if (func.kind === 136) { - if (!isTypeAssignableTo(exprType, returnType)) { - error(node.expression, ts.Diagnostics.Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class); - } - } - else if (func.type || isGetAccessorWithAnnotatatedSetAccessor(func)) { - checkTypeAssignableTo(exprType, returnType, node.expression, undefined); + else if (func.kind === 137) { + if (!isTypeAssignableTo(exprType, returnType)) { + error(node.expression, ts.Diagnostics.Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class); } } + else if (func.type || isGetAccessorWithAnnotatatedSetAccessor(func) || signature.typePredicate) { + checkTypeAssignableTo(exprType, returnType, node.expression, undefined); + } } } } function checkWithStatement(node) { - if (!checkGrammarStatementInAmbientContext(node)) { - if (node.parserContextFlags & 1) { - grammarErrorOnFirstToken(node, ts.Diagnostics.with_statements_are_not_allowed_in_strict_mode); - } - } + checkGrammarStatementInAmbientContext(node); checkExpression(node.expression); error(node.expression, ts.Diagnostics.All_symbols_within_a_with_block_will_be_resolved_to_any); } @@ -16546,7 +18083,7 @@ var ts; var hasDuplicateDefaultClause = false; var expressionType = checkExpression(node.expression); ts.forEach(node.caseBlock.clauses, function (clause) { - if (clause.kind === 222 && !hasDuplicateDefaultClause) { + if (clause.kind === 224 && !hasDuplicateDefaultClause) { if (firstDefaultClause === undefined) { firstDefaultClause = clause; } @@ -16558,7 +18095,7 @@ var ts; hasDuplicateDefaultClause = true; } } - if (produceDiagnostics && clause.kind === 221) { + if (produceDiagnostics && clause.kind === 223) { var caseClause = clause; var caseType = checkExpression(caseClause.expression); if (!isTypeAssignableTo(expressionType, caseType)) { @@ -16575,7 +18112,7 @@ var ts; if (ts.isFunctionLike(current)) { break; } - if (current.kind === 195 && current.label.text === node.label.text) { + if (current.kind === 197 && 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)); break; @@ -16619,7 +18156,6 @@ var ts; grammarErrorOnNode(localSymbol.valueDeclaration, ts.Diagnostics.Cannot_redeclare_identifier_0_in_catch_clause, identifierName); } } - checkGrammarEvalOrArgumentsInStrictMode(node, catchClause.variableDeclaration.name); } } checkBlock(catchClause.block); @@ -16639,7 +18175,7 @@ var ts; checkIndexConstraintForProperty(prop, propType, type, declaredStringIndexer, stringIndexType, 0); checkIndexConstraintForProperty(prop, propType, type, declaredNumberIndexer, numberIndexType, 1); }); - if (type.flags & 1024 && type.symbol.valueDeclaration.kind === 202) { + if (type.flags & 1024 && type.symbol.valueDeclaration.kind === 204) { var classDeclaration = type.symbol.valueDeclaration; for (var _i = 0, _a = classDeclaration.members; _i < _a.length; _i++) { var member = _a[_i]; @@ -16670,7 +18206,7 @@ var ts; return; } var errorNode; - if (prop.valueDeclaration.name.kind === 128 || prop.parent === containingType.symbol) { + if (prop.valueDeclaration.name.kind === 129 || prop.parent === containingType.symbol) { errorNode = prop.valueDeclaration; } else if (indexDeclaration) { @@ -16720,10 +18256,6 @@ var ts; return unknownType; } function checkClassDeclaration(node) { - checkGrammarDeclarationNameInStrictMode(node); - if (node.parent.kind !== 207 && node.parent.kind !== 228) { - grammarErrorOnNode(node, ts.Diagnostics.class_declarations_are_only_supported_directly_inside_a_module_or_as_a_top_level_declaration); - } if (!node.name && !(node.flags & 256)) { grammarErrorOnFirstToken(node, ts.Diagnostics.A_class_declaration_without_the_default_modifier_must_have_a_name); } @@ -16741,35 +18273,38 @@ var ts; var staticType = getTypeOfSymbol(symbol); var baseTypeNode = ts.getClassExtendsHeritageClauseElement(node); if (baseTypeNode) { - if (!ts.isSupportedExpressionWithTypeArguments(baseTypeNode)) { - error(baseTypeNode.expression, ts.Diagnostics.Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_class_extends_clauses); - } emitExtends = emitExtends || !ts.isInAmbientContext(node); - checkExpressionWithTypeArguments(baseTypeNode); - } - var baseTypes = getBaseTypes(type); - if (baseTypes.length) { - if (produceDiagnostics) { + var baseTypes = getBaseTypes(type); + if (baseTypes.length && produceDiagnostics) { var baseType = baseTypes[0]; + var staticBaseType = getBaseConstructorTypeOfClass(type); + if (baseTypeNode.typeArguments) { + ts.forEach(baseTypeNode.typeArguments, checkSourceElement); + for (var _i = 0, _a = getConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments); _i < _a.length; _i++) { + var constructor = _a[_i]; + if (!checkTypeArgumentConstraints(constructor.typeParameters, baseTypeNode.typeArguments)) { + break; + } + } + } checkTypeAssignableTo(type, baseType, node.name || node, ts.Diagnostics.Class_0_incorrectly_extends_base_class_1); - var staticBaseType = getTypeOfSymbol(baseType.symbol); - checkTypeAssignableTo(staticType, getTypeWithoutConstructors(staticBaseType), node.name || node, ts.Diagnostics.Class_static_side_0_incorrectly_extends_base_class_static_side_1); - if (baseType.symbol !== resolveEntityName(baseTypeNode.expression, 107455)) { - error(baseTypeNode, ts.Diagnostics.Type_name_0_in_extends_clause_does_not_reference_constructor_function_for_0, typeToString(baseType)); + checkTypeAssignableTo(staticType, getTypeWithoutSignatures(staticBaseType), node.name || node, ts.Diagnostics.Class_static_side_0_incorrectly_extends_base_class_static_side_1); + if (!(staticBaseType.symbol && staticBaseType.symbol.flags & 32)) { + var constructors = getInstantiatedConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments); + if (ts.forEach(constructors, function (sig) { return getReturnTypeOfSignature(sig) !== baseType; })) { + error(baseTypeNode.expression, ts.Diagnostics.Base_constructors_must_all_have_the_same_return_type); + } } checkKindsOfPropertyMemberOverrides(type, baseType); } } - if (baseTypes.length || (baseTypeNode && compilerOptions.separateCompilation)) { - checkExpressionOrQualifiedName(baseTypeNode.expression); - } var implementedTypeNodes = ts.getClassImplementsHeritageClauseElements(node); if (implementedTypeNodes) { ts.forEach(implementedTypeNodes, function (typeRefNode) { if (!ts.isSupportedExpressionWithTypeArguments(typeRefNode)) { error(typeRefNode.expression, ts.Diagnostics.A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments); } - checkExpressionWithTypeArguments(typeRefNode); + checkTypeReferenceNode(typeRefNode); if (produceDiagnostics) { var t = getTypeFromTypeNode(typeRefNode); if (t !== unknownType) { @@ -16851,7 +18386,7 @@ var ts; } } function isAccessor(kind) { - return kind === 137 || kind === 138; + return kind === 138 || kind === 139; } function areTypeParametersIdentical(list1, list2) { if (!list1 && !list2) { @@ -16911,13 +18446,13 @@ var ts; return ok; } function checkInterfaceDeclaration(node) { - checkGrammarDeclarationNameInStrictMode(node) || checkGrammarDecorators(node) || checkGrammarModifiers(node) || checkGrammarInterfaceDeclaration(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); - var firstInterfaceDecl = ts.getDeclarationOfKind(symbol, 203); + var firstInterfaceDecl = ts.getDeclarationOfKind(symbol, 205); if (symbol.declarations.length > 1) { if (node !== firstInterfaceDecl && !areTypeParametersIdentical(firstInterfaceDecl.typeParameters, node.typeParameters)) { error(node.name, ts.Diagnostics.All_declarations_of_an_interface_must_have_identical_type_parameters); @@ -16937,7 +18472,7 @@ var ts; if (!ts.isSupportedExpressionWithTypeArguments(heritageElement)) { error(heritageElement.expression, ts.Diagnostics.An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments); } - checkExpressionWithTypeArguments(heritageElement); + checkTypeReferenceNode(heritageElement); }); ts.forEach(node.members, checkSourceElement); if (produceDiagnostics) { @@ -16958,7 +18493,7 @@ var ts; var ambient = ts.isInAmbientContext(node); var enumIsConst = ts.isConst(node); ts.forEach(node.members, function (member) { - if (member.name.kind !== 128 && isNumericLiteralName(member.name.text)) { + if (member.name.kind !== 129 && isNumericLiteralName(member.name.text)) { error(member.name, ts.Diagnostics.An_enum_member_cannot_have_a_numeric_name); } var initializer = member.initializer; @@ -16994,7 +18529,7 @@ var ts; return evalConstant(initializer); function evalConstant(e) { switch (e.kind) { - case 168: + case 170: var value = evalConstant(e.operand); if (value === undefined) { return undefined; @@ -17005,7 +18540,7 @@ var ts; case 47: return ~value; } return undefined; - case 170: + case 172: var left = evalConstant(e.left); if (left === undefined) { return undefined; @@ -17030,11 +18565,11 @@ var ts; return undefined; case 7: return +e.text; - case 162: + case 164: return evalConstant(e.expression); case 65: - case 157: - case 156: + case 159: + case 158: var member = initializer.parent; var currentType = getTypeOfSymbol(getSymbolOfNode(member.parent)); var enumType; @@ -17045,7 +18580,7 @@ var ts; } else { var expression; - if (e.kind === 157) { + if (e.kind === 159) { if (e.argumentExpression === undefined || e.argumentExpression.kind !== 8) { return undefined; @@ -17062,7 +18597,7 @@ var ts; if (current.kind === 65) { break; } - else if (current.kind === 156) { + else if (current.kind === 158) { current = current.expression; } else { @@ -17097,15 +18632,15 @@ var ts; if (!produceDiagnostics) { return; } - checkGrammarDeclarationNameInStrictMode(node) || checkGrammarDecorators(node) || checkGrammarModifiers(node) || checkGrammarEnumDeclaration(node); + checkGrammarDecorators(node) || checkGrammarModifiers(node) || checkGrammarEnumDeclaration(node); checkTypeNameIsReserved(node.name, ts.Diagnostics.Enum_name_cannot_be_0); checkCollisionWithCapturedThisVariable(node, node.name); checkCollisionWithRequireExportsInGeneratedCode(node, node.name); checkExportsOnMergedDeclarations(node); computeEnumMemberValues(node); var enumIsConst = ts.isConst(node); - if (compilerOptions.separateCompilation && enumIsConst && ts.isInAmbientContext(node)) { - error(node.name, ts.Diagnostics.Ambient_const_enums_are_not_allowed_when_the_separateCompilation_flag_is_provided); + 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); @@ -17119,7 +18654,7 @@ var ts; } var seenEnumMissingInitialInitializer = false; ts.forEach(enumSymbol.declarations, function (declaration) { - if (declaration.kind !== 205) { + if (declaration.kind !== 207) { return false; } var enumDeclaration = declaration; @@ -17142,8 +18677,8 @@ var ts; var declarations = symbol.declarations; for (var _i = 0; _i < declarations.length; _i++) { var declaration = declarations[_i]; - if ((declaration.kind === 202 || - (declaration.kind === 201 && ts.nodeIsPresent(declaration.body))) && + if ((declaration.kind === 204 || + (declaration.kind === 203 && ts.nodeIsPresent(declaration.body))) && !ts.isInAmbientContext(declaration)) { return declaration; } @@ -17165,7 +18700,14 @@ var ts; } function checkModuleDeclaration(node) { if (produceDiagnostics) { - if (!checkGrammarDeclarationNameInStrictMode(node) && !checkGrammarDecorators(node) && !checkGrammarModifiers(node)) { + var isAmbientExternalModule = node.name.kind === 8; + 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 (!ts.isInAmbientContext(node) && node.name.kind === 8) { grammarErrorOnNode(node.name, ts.Diagnostics.Only_ambient_modules_can_use_quoted_names); } @@ -17177,7 +18719,7 @@ var ts; if (symbol.flags & 512 && symbol.declarations.length > 1 && !ts.isInAmbientContext(node) - && ts.isInstantiatedModule(node, compilerOptions.preserveConstEnums || compilerOptions.separateCompilation)) { + && ts.isInstantiatedModule(node, compilerOptions.preserveConstEnums || compilerOptions.isolatedModules)) { var firstNonAmbientClassOrFunc = getFirstNonAmbientClassOrFunctionDeclaration(symbol); if (firstNonAmbientClassOrFunc) { if (ts.getSourceFileOfNode(node) !== ts.getSourceFileOfNode(firstNonAmbientClassOrFunc)) { @@ -17187,13 +18729,13 @@ var ts; 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, 202); + var mergedClass = ts.getDeclarationOfKind(symbol, 204); if (mergedClass && inSameLexicalScope(node, mergedClass)) { getNodeLinks(node).flags |= 2048; } } - if (node.name.kind === 8) { + if (isAmbientExternalModule) { if (!isGlobalSourceFile(node.parent)) { error(node.name, ts.Diagnostics.Ambient_modules_cannot_be_nested_in_other_modules); } @@ -17206,10 +18748,10 @@ var ts; } function getFirstIdentifier(node) { while (true) { - if (node.kind === 127) { + if (node.kind === 128) { node = node.left; } - else if (node.kind === 156) { + else if (node.kind === 158) { node = node.expression; } else { @@ -17225,9 +18767,9 @@ var ts; error(moduleName, ts.Diagnostics.String_literal_expected); return false; } - var inAmbientExternalModule = node.parent.kind === 207 && node.parent.parent.name.kind === 8; - if (node.parent.kind !== 228 && !inAmbientExternalModule) { - error(moduleName, node.kind === 216 ? + var inAmbientExternalModule = node.parent.kind === 209 && node.parent.parent.name.kind === 8; + if (node.parent.kind !== 230 && !inAmbientExternalModule) { + error(moduleName, node.kind === 218 ? ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace : ts.Diagnostics.Import_declarations_in_a_namespace_cannot_reference_a_module); return false; @@ -17246,7 +18788,7 @@ var ts; (symbol.flags & 793056 ? 793056 : 0) | (symbol.flags & 1536 ? 1536 : 0); if (target.flags & excludedMeanings) { - var message = node.kind === 218 ? + var message = node.kind === 220 ? 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)); @@ -17259,7 +18801,10 @@ var ts; checkAliasSymbol(node); } function checkImportDeclaration(node) { - if (!checkGrammarImportDeclarationNameInStrictMode(node) && !checkGrammarDecorators(node) && !checkGrammarModifiers(node) && (node.flags & 499)) { + if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_import_declaration_can_only_be_used_in_a_namespace_or_module)) { + return; + } + if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && (node.flags & 499)) { grammarErrorOnFirstToken(node, ts.Diagnostics.An_import_declaration_cannot_have_modifiers); } if (checkExternalImportOrExportDeclaration(node)) { @@ -17269,7 +18814,7 @@ var ts; checkImportBinding(importClause); } if (importClause.namedBindings) { - if (importClause.namedBindings.kind === 212) { + if (importClause.namedBindings.kind === 214) { checkImportBinding(importClause.namedBindings); } else { @@ -17280,7 +18825,10 @@ var ts; } } function checkImportEqualsDeclaration(node) { - checkGrammarDeclarationNameInStrictMode(node) || checkGrammarDecorators(node) || checkGrammarModifiers(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 (node.flags & 1) { @@ -17308,14 +18856,17 @@ var ts; } } function checkExportDeclaration(node) { + if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_export_declaration_can_only_be_used_in_a_module)) { + return; + } if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && (node.flags & 499)) { 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 === 207 && node.parent.parent.name.kind === 8; - if (node.parent.kind !== 228 && !inAmbientExternalModule) { + var inAmbientExternalModule = node.parent.kind === 209 && node.parent.parent.name.kind === 8; + if (node.parent.kind !== 230 && !inAmbientExternalModule) { error(node, ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace); } } @@ -17327,6 +18878,11 @@ var ts; } } } + function checkGrammarModuleElementContext(node, errorMessage) { + if (node.parent.kind !== 230 && node.parent.kind !== 209 && node.parent.kind !== 208) { + return grammarErrorOnFirstToken(node, errorMessage); + } + } function checkExportSpecifier(node) { checkAliasSymbol(node); if (!node.parent.parent.moduleSpecifier) { @@ -17334,8 +18890,11 @@ var ts; } } function checkExportAssignment(node) { - var container = node.parent.kind === 228 ? node.parent : node.parent.parent; - if (container.kind === 206 && container.name.kind === 65) { + if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_export_assignment_can_only_be_used_in_a_module)) { + return; + } + var container = node.parent.kind === 230 ? node.parent : node.parent.parent; + if (container.kind === 208 && container.name.kind === 65) { error(node, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_namespace); return; } @@ -17359,10 +18918,10 @@ var ts; } } function getModuleStatements(node) { - if (node.kind === 228) { + if (node.kind === 230) { return node.statements; } - if (node.kind === 206 && node.body.kind === 207) { + if (node.kind === 208 && node.body.kind === 209) { return node.body.statements; } return emptyArray; @@ -17387,168 +18946,175 @@ var ts; links.exportsChecked = true; } } + function checkTypePredicate(node) { + if (!isInLegalTypePredicatePosition(node)) { + error(node, ts.Diagnostics.A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods); + } + } function checkSourceElement(node) { if (!node) return; switch (node.kind) { - case 129: - return checkTypeParameter(node); case 130: + return checkTypeParameter(node); + case 131: return checkParameter(node); + case 134: case 133: - case 132: return checkPropertyDeclaration(node); - case 143: - case 144: - case 139: + case 145: + case 146: case 140: - return checkSignatureDeclaration(node); case 141: return checkSignatureDeclaration(node); - case 135: - case 134: - return checkMethodDeclaration(node); - case 136: - return checkConstructorDeclaration(node); - case 137: - case 138: - return checkAccessorDeclaration(node); case 142: + return checkSignatureDeclaration(node); + case 136: + case 135: + return checkMethodDeclaration(node); + case 137: + return checkConstructorDeclaration(node); + case 138: + case 139: + return checkAccessorDeclaration(node); + case 144: return checkTypeReferenceNode(node); - case 145: - return checkTypeQuery(node); - case 146: - return checkTypeLiteral(node); + case 143: + return checkTypePredicate(node); case 147: - return checkArrayType(node); + return checkTypeQuery(node); case 148: - return checkTupleType(node); + return checkTypeLiteral(node); case 149: - return checkUnionType(node); + return checkArrayType(node); case 150: + return checkTupleType(node); + case 151: + return checkUnionType(node); + case 152: return checkSourceElement(node.type); - case 201: - return checkFunctionDeclaration(node); - case 180: - case 207: - return checkBlock(node); - case 181: - return checkVariableStatement(node); - case 183: - return checkExpressionStatement(node); - case 184: - return checkIfStatement(node); - case 185: - return checkDoStatement(node); - case 186: - return checkWhileStatement(node); - case 187: - return checkForStatement(node); - case 188: - return checkForInStatement(node); - case 189: - return checkForOfStatement(node); - case 190: - case 191: - return checkBreakOrContinueStatement(node); - case 192: - return checkReturnStatement(node); - case 193: - return checkWithStatement(node); - case 194: - return checkSwitchStatement(node); - case 195: - return checkLabeledStatement(node); - case 196: - return checkThrowStatement(node); - case 197: - return checkTryStatement(node); - case 199: - return checkVariableDeclaration(node); - case 153: - return checkBindingElement(node); - case 202: - return checkClassDeclaration(node); case 203: - return checkInterfaceDeclaration(node); - case 204: - return checkTypeAliasDeclaration(node); - case 205: - return checkEnumDeclaration(node); - case 206: - return checkModuleDeclaration(node); - case 210: - return checkImportDeclaration(node); - case 209: - return checkImportEqualsDeclaration(node); - case 216: - return checkExportDeclaration(node); - case 215: - return checkExportAssignment(node); + return checkFunctionDeclaration(node); case 182: - checkGrammarStatementInAmbientContext(node); - return; + case 209: + return checkBlock(node); + case 183: + return checkVariableStatement(node); + case 185: + return checkExpressionStatement(node); + case 186: + return checkIfStatement(node); + case 187: + return checkDoStatement(node); + case 188: + return checkWhileStatement(node); + case 189: + return checkForStatement(node); + case 190: + return checkForInStatement(node); + case 191: + return checkForOfStatement(node); + case 192: + case 193: + return checkBreakOrContinueStatement(node); + case 194: + return checkReturnStatement(node); + case 195: + return checkWithStatement(node); + case 196: + return checkSwitchStatement(node); + case 197: + return checkLabeledStatement(node); case 198: + return checkThrowStatement(node); + case 199: + return checkTryStatement(node); + case 201: + return checkVariableDeclaration(node); + case 155: + return checkBindingElement(node); + case 204: + return checkClassDeclaration(node); + case 205: + return checkInterfaceDeclaration(node); + case 206: + return checkTypeAliasDeclaration(node); + case 207: + return checkEnumDeclaration(node); + case 208: + return checkModuleDeclaration(node); + case 212: + return checkImportDeclaration(node); + case 211: + return checkImportEqualsDeclaration(node); + case 218: + return checkExportDeclaration(node); + case 217: + return checkExportAssignment(node); + case 184: checkGrammarStatementInAmbientContext(node); return; - case 219: + case 200: + checkGrammarStatementInAmbientContext(node); + return; + case 221: return checkMissingDeclaration(node); } } function checkFunctionExpressionBodies(node) { switch (node.kind) { - case 163: - case 164: + case 165: + case 166: ts.forEach(node.parameters, checkFunctionExpressionBodies); checkFunctionExpressionOrObjectLiteralMethodBody(node); break; + case 136: case 135: - case 134: + ts.forEach(node.decorators, checkFunctionExpressionBodies); ts.forEach(node.parameters, checkFunctionExpressionBodies); if (ts.isObjectLiteralMethod(node)) { checkFunctionExpressionOrObjectLiteralMethodBody(node); } break; - case 136: case 137: case 138: - case 201: + case 139: + case 203: ts.forEach(node.parameters, checkFunctionExpressionBodies); break; - case 193: + case 195: checkFunctionExpressionBodies(node.expression); break; - case 130: - case 133: case 132: - case 151: - case 152: + case 131: + case 134: + case 133: case 153: case 154: case 155: - case 225: case 156: case 157: + case 227: case 158: case 159: case 160: - case 172: - case 178: case 161: case 162: - case 166: - case 167: - case 165: - case 168: - case 169: - case 170: - case 171: case 174: case 180: - case 207: - case 181: + case 163: + case 164: + case 168: + case 169: + case 167: + case 170: + case 171: + case 172: + case 173: + case 176: + case 182: + case 209: case 183: - case 184: case 185: case 186: case 187: @@ -17557,21 +19123,23 @@ var ts; case 190: case 191: case 192: + case 193: case 194: - case 208: - case 221: - case 222: - case 195: case 196: - case 197: + case 210: + case 223: case 224: + case 197: + case 198: case 199: - case 200: + case 226: + case 201: case 202: - case 205: - case 227: - case 215: - case 228: + case 204: + case 207: + case 229: + case 217: + case 230: ts.forEachChild(node, checkFunctionExpressionBodies); break; } @@ -17584,6 +19152,9 @@ var ts; function checkSourceFileWorker(node) { var links = getNodeLinks(node); if (!(links.flags & 1)) { + if (node.isDefaultLib && compilerOptions.skipDefaultLibCheck) { + return; + } checkGrammarSourceFile(node); emitExtends = false; emitDecorate = false; @@ -17631,7 +19202,7 @@ var ts; function isInsideWithStatementBody(node) { if (node) { while (node.parent) { - if (node.parent.kind === 193 && node.parent.statement === node) { + if (node.parent.kind === 195 && node.parent.statement === node) { return true; } node = node.parent; @@ -17653,23 +19224,23 @@ var ts; copySymbols(location.locals, meaning); } switch (location.kind) { - case 228: + case 230: if (!ts.isExternalModule(location)) { break; } - case 206: + case 208: copySymbols(getSymbolOfNode(location).exports, meaning & 8914931); break; - case 205: + case 207: copySymbols(getSymbolOfNode(location).exports, meaning & 8); break; - case 202: - case 203: + case 204: + case 205: if (!(memberFlags & 128)) { copySymbols(getSymbolOfNode(location).members, meaning & 793056); } break; - case 163: + case 165: if (location.name) { copySymbol(location.symbol, meaning); } @@ -17705,22 +19276,22 @@ var ts; copySymbols(location.locals, meaning); } switch (location.kind) { - case 228: + case 230: if (!ts.isExternalModule(location)) break; - case 206: + case 208: copySymbols(getSymbolOfNode(location).exports, meaning & 8914931); break; - case 205: + case 207: copySymbols(getSymbolOfNode(location).exports, meaning & 8); break; - case 202: - case 203: + case 204: + case 205: if (!(memberFlags & 128)) { copySymbols(getSymbolOfNode(location).members, meaning & 793056); } break; - case 163: + case 165: if (location.name) { copySymbol(location.symbol, meaning); } @@ -17733,110 +19304,42 @@ var ts; return symbolsToArray(symbols); } function isTypeDeclarationName(name) { - return name.kind == 65 && + return name.kind === 65 && isTypeDeclaration(name.parent) && name.parent.name === name; } function isTypeDeclaration(node) { switch (node.kind) { - case 129: - case 202: - case 203: + case 130: case 204: case 205: + case 206: + case 207: return true; } } function isTypeReferenceIdentifier(entityName) { var node = entityName; - while (node.parent && node.parent.kind === 127) { + while (node.parent && node.parent.kind === 128) { node = node.parent; } - return node.parent && node.parent.kind === 142; + return node.parent && node.parent.kind === 144; } function isHeritageClauseElementIdentifier(entityName) { var node = entityName; - while (node.parent && node.parent.kind === 156) { + while (node.parent && node.parent.kind === 158) { node = node.parent; } - return node.parent && node.parent.kind === 177; - } - function isTypeNode(node) { - if (142 <= node.kind && node.kind <= 150) { - return true; - } - switch (node.kind) { - case 112: - case 120: - case 122: - case 113: - case 123: - return true; - case 99: - return node.parent.kind !== 167; - case 8: - return node.parent.kind === 130; - case 177: - return true; - case 65: - if (node.parent.kind === 127 && node.parent.right === node) { - node = node.parent; - } - else if (node.parent.kind === 156 && node.parent.name === node) { - node = node.parent; - } - case 127: - case 156: - ts.Debug.assert(node.kind === 65 || node.kind === 127 || node.kind === 156, "'node' was expected to be a qualified name, identifier or property access in 'isTypeNode'."); - var parent_5 = node.parent; - if (parent_5.kind === 145) { - return false; - } - if (142 <= parent_5.kind && parent_5.kind <= 150) { - return true; - } - switch (parent_5.kind) { - case 177: - return true; - case 129: - return node === parent_5.constraint; - case 133: - case 132: - case 130: - case 199: - return node === parent_5.type; - case 201: - case 163: - case 164: - case 136: - case 135: - case 134: - case 137: - case 138: - return node === parent_5.type; - case 139: - case 140: - case 141: - return node === parent_5.type; - case 161: - return node === parent_5.type; - case 158: - case 159: - return parent_5.typeArguments && ts.indexOf(parent_5.typeArguments, node) >= 0; - case 160: - return false; - } - } - return false; + return node.parent && node.parent.kind === 179; } function getLeftSideOfImportEqualsOrExportAssignment(nodeOnRightSide) { - while (nodeOnRightSide.parent.kind === 127) { + while (nodeOnRightSide.parent.kind === 128) { nodeOnRightSide = nodeOnRightSide.parent; } - if (nodeOnRightSide.parent.kind === 209) { + if (nodeOnRightSide.parent.kind === 211) { return nodeOnRightSide.parent.moduleReference === nodeOnRightSide && nodeOnRightSide.parent; } - if (nodeOnRightSide.parent.kind === 215) { + if (nodeOnRightSide.parent.kind === 217) { return nodeOnRightSide.parent.expression === nodeOnRightSide && nodeOnRightSide.parent; } return undefined; @@ -17848,10 +19351,10 @@ var ts; if (ts.isDeclarationName(entityName)) { return getSymbolOfNode(entityName.parent); } - if (entityName.parent.kind === 215) { + if (entityName.parent.kind === 217) { return resolveEntityName(entityName, 107455 | 793056 | 1536 | 8388608); } - if (entityName.kind !== 156) { + if (entityName.kind !== 158) { if (isInRightSideOfImportOrExportAssignment(entityName)) { return getSymbolOfPartOfRightHandSideOfImportEquals(entityName); } @@ -17860,7 +19363,7 @@ var ts; entityName = entityName.parent; } if (isHeritageClauseElementIdentifier(entityName)) { - var meaning = entityName.parent.kind === 177 ? 793056 : 1536; + var meaning = entityName.parent.kind === 179 ? 793056 : 1536; meaning |= 8388608; return resolveEntityName(entityName, meaning); } @@ -17872,14 +19375,14 @@ var ts; var meaning = 107455 | 8388608; return resolveEntityName(entityName, meaning); } - else if (entityName.kind === 156) { + else if (entityName.kind === 158) { var symbol = getNodeLinks(entityName).resolvedSymbol; if (!symbol) { checkPropertyAccessExpression(entityName); } return getNodeLinks(entityName).resolvedSymbol; } - else if (entityName.kind === 127) { + else if (entityName.kind === 128) { var symbol = getNodeLinks(entityName).resolvedSymbol; if (!symbol) { checkQualifiedName(entityName); @@ -17888,7 +19391,7 @@ var ts; } } else if (isTypeReferenceIdentifier(entityName)) { - var meaning = entityName.parent.kind === 142 ? 793056 : 1536; + var meaning = entityName.parent.kind === 144 ? 793056 : 1536; meaning |= 8388608; return resolveEntityName(entityName, meaning); } @@ -17902,14 +19405,14 @@ var ts; return getSymbolOfNode(node.parent); } if (node.kind === 65 && isInRightSideOfImportOrExportAssignment(node)) { - return node.parent.kind === 215 + return node.parent.kind === 217 ? getSymbolOfEntityNameOrPropertyAccessExpression(node) : getSymbolOfPartOfRightHandSideOfImportEquals(node); } switch (node.kind) { case 65: - case 156: - case 127: + case 158: + case 128: return getSymbolOfEntityNameOrPropertyAccessExpression(node); case 93: case 91: @@ -17917,7 +19420,7 @@ var ts; return type.symbol; case 114: var constructorDeclaration = node.parent; - if (constructorDeclaration && constructorDeclaration.kind === 136) { + if (constructorDeclaration && constructorDeclaration.kind === 137) { return constructorDeclaration.parent.symbol; } return undefined; @@ -17925,12 +19428,12 @@ var ts; var moduleName; if ((ts.isExternalModuleImportEqualsDeclaration(node.parent.parent) && ts.getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node) || - ((node.parent.kind === 210 || node.parent.kind === 216) && + ((node.parent.kind === 212 || node.parent.kind === 218) && node.parent.moduleSpecifier === node)) { return resolveExternalModuleName(node, node); } case 7: - if (node.parent.kind == 157 && node.parent.argumentExpression === node) { + if (node.parent.kind === 159 && node.parent.argumentExpression === node) { var objectType = checkExpression(node.parent.expression); if (objectType === unknownType) return undefined; @@ -17944,7 +19447,7 @@ var ts; return undefined; } function getShorthandAssignmentValueSymbol(location) { - if (location && location.kind === 226) { + if (location && location.kind === 228) { return resolveEntityName(location.name, 107455); } return undefined; @@ -17953,12 +19456,15 @@ var ts; if (isInsideWithStatementBody(node)) { return unknownType; } - if (isTypeNode(node)) { + if (ts.isTypeNode(node)) { return getTypeFromTypeNode(node); } if (ts.isExpression(node)) { return getTypeOfExpression(node); } + if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(node)) { + return getBaseTypes(getDeclaredTypeOfSymbol(getSymbolOfNode(node.parent.parent)))[0]; + } if (isTypeDeclaration(node)) { var symbol = getSymbolOfNode(node); return getDeclaredTypeOfSymbol(symbol); @@ -18003,9 +19509,9 @@ var ts; function getRootSymbols(symbol) { if (symbol.flags & 268435456) { var symbols = []; - var name_10 = symbol.name; + var name_14 = symbol.name; ts.forEach(getSymbolLinks(symbol).unionType.types, function (t) { - symbols.push(getPropertyOfType(t, name_10)); + symbols.push(getPropertyOfType(t, name_14)); }); return symbols; } @@ -18017,81 +19523,81 @@ var ts; } return [symbol]; } - function isExternalModuleSymbol(symbol) { - return symbol.flags & 512 && symbol.declarations.length === 1 && symbol.declarations[0].kind === 228; - } - function getAliasNameSubstitution(symbol, getGeneratedNameForNode) { - if (languageVersion >= 2) { - return undefined; - } - var node = getDeclarationOfAliasSymbol(symbol); - if (node) { - if (node.kind === 211) { - var defaultKeyword; - if (languageVersion === 0) { - defaultKeyword = "[\"default\"]"; - } - else { - defaultKeyword = ".default"; - } - return getGeneratedNameForNode(node.parent) + defaultKeyword; - } - if (node.kind === 214) { - var moduleName = getGeneratedNameForNode(node.parent.parent.parent); - var propertyName = node.propertyName || node.name; - return moduleName + "." + ts.unescapeIdentifier(propertyName.text); - } - } - } - function getExportNameSubstitution(symbol, location, getGeneratedNameForNode) { - if (isExternalModuleSymbol(symbol.parent)) { - if (languageVersion >= 2 || compilerOptions.module === 4) { - return undefined; - } - return "exports." + ts.unescapeIdentifier(symbol.name); - } - var node = location; - var containerSymbol = getParentOfSymbol(symbol); - while (node) { - if ((node.kind === 206 || node.kind === 205) && getSymbolOfNode(node) === containerSymbol) { - return getGeneratedNameForNode(node) + "." + ts.unescapeIdentifier(symbol.name); - } - node = node.parent; - } - } - function getExpressionNameSubstitution(node, getGeneratedNameForNode) { - var symbol = getNodeLinks(node).resolvedSymbol || (ts.isDeclarationName(node) ? getSymbolOfNode(node.parent) : undefined); + function getReferencedExportContainer(node) { + var symbol = getReferencedValueSymbol(node); if (symbol) { - if (symbol.parent) { - return getExportNameSubstitution(symbol, node.parent, getGeneratedNameForNode); + if (symbol.flags & 1048576) { + var exportSymbol = getMergedSymbol(symbol.exportSymbol); + if (exportSymbol.flags & 944) { + return undefined; + } + symbol = exportSymbol; } - var exportSymbol = getExportSymbolOfValueSymbolIfExported(symbol); - if (symbol !== exportSymbol && !(exportSymbol.flags & 944)) { - return getExportNameSubstitution(exportSymbol, node.parent, getGeneratedNameForNode); - } - if (symbol.flags & 8388608) { - return getAliasNameSubstitution(symbol, getGeneratedNameForNode); + var parentSymbol = getParentOfSymbol(symbol); + if (parentSymbol) { + if (parentSymbol.flags & 512 && parentSymbol.valueDeclaration.kind === 230) { + return parentSymbol.valueDeclaration; + } + for (var n = node.parent; n; n = n.parent) { + if ((n.kind === 208 || n.kind === 207) && getSymbolOfNode(n) === parentSymbol) { + return n; + } + } } } } + function getReferencedImportDeclaration(node) { + var symbol = getReferencedValueSymbol(node); + return symbol && symbol.flags & 8388608 ? getDeclarationOfAliasSymbol(symbol) : undefined; + } + function isStatementWithLocals(node) { + switch (node.kind) { + case 182: + case 210: + case 189: + case 190: + case 191: + return true; + } + return false; + } + function isNestedRedeclarationSymbol(symbol) { + if (symbol.flags & 418) { + var links = getSymbolLinks(symbol); + if (links.isNestedRedeclaration === undefined) { + var container = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration); + links.isNestedRedeclaration = isStatementWithLocals(container) && + !!resolveName(container.parent, symbol.name, 107455, undefined, undefined); + } + return links.isNestedRedeclaration; + } + return false; + } + function getReferencedNestedRedeclaration(node) { + var symbol = getReferencedValueSymbol(node); + return symbol && isNestedRedeclarationSymbol(symbol) ? symbol.valueDeclaration : undefined; + } + function isNestedRedeclaration(node) { + return isNestedRedeclarationSymbol(getSymbolOfNode(node)); + } function isValueAliasDeclaration(node) { switch (node.kind) { - case 209: case 211: - case 212: + case 213: case 214: - case 218: - return isAliasResolvedToValue(getSymbolOfNode(node)); case 216: + case 220: + return isAliasResolvedToValue(getSymbolOfNode(node)); + case 218: var exportClause = node.exportClause; return exportClause && ts.forEach(exportClause.elements, isValueAliasDeclaration); - case 215: + case 217: return node.expression && node.expression.kind === 65 ? isAliasResolvedToValue(getSymbolOfNode(node)) : true; } return false; } function isTopLevelValueImportEqualsWithEntityName(node) { - if (node.parent.kind !== 228 || !ts.isInternalModuleImportEqualsDeclaration(node)) { + if (node.parent.kind !== 230 || !ts.isInternalModuleImportEqualsDeclaration(node)) { return false; } var isValue = isAliasResolvedToValue(getSymbolOfNode(node)); @@ -18099,7 +19605,7 @@ var ts; } function isAliasResolvedToValue(symbol) { var target = resolveAlias(symbol); - if (target === unknownSymbol && compilerOptions.separateCompilation) { + if (target === unknownSymbol && compilerOptions.isolatedModules) { return true; } return target !== unknownSymbol && target && target.flags & 107455 && !isConstEnumOrConstEnumOnlyModule(target); @@ -18136,7 +19642,7 @@ var ts; return getNodeLinks(node).enumMemberValue; } function getConstantValue(node) { - if (node.kind === 227) { + if (node.kind === 229) { return getEnumMemberValue(node); } var symbol = getNodeLinks(node).resolvedSymbol; @@ -18147,10 +19653,9 @@ var ts; } return undefined; } - function serializeEntityName(node, getGeneratedNameForNode, fallbackPath) { + function serializeEntityName(node, fallbackPath) { if (node.kind === 65) { - var substitution = getExpressionNameSubstitution(node, getGeneratedNameForNode); - var text = substitution || node.text; + var text = node.text; if (fallbackPath) { fallbackPath.push(text); } @@ -18159,14 +19664,14 @@ var ts; } } else { - var left = serializeEntityName(node.left, getGeneratedNameForNode, fallbackPath); - var right = serializeEntityName(node.right, getGeneratedNameForNode, fallbackPath); + var left = serializeEntityName(node.left, fallbackPath); + var right = serializeEntityName(node.right, fallbackPath); if (!fallbackPath) { return left + "." + right; } } } - function serializeTypeReferenceNode(node, getGeneratedNameForNode) { + function serializeTypeReferenceNode(node) { var type = getTypeFromTypeNode(node); if (type.flags & 16) { return "void 0"; @@ -18183,47 +19688,47 @@ var ts; else if (type.flags & 8192) { return "Array"; } - else if (type.flags & 1048576) { + else if (type.flags & 2097152) { return "Symbol"; } else if (type === unknownType) { var fallbackPath = []; - serializeEntityName(node.typeName, getGeneratedNameForNode, fallbackPath); + serializeEntityName(node.typeName, fallbackPath); return fallbackPath; } else if (type.symbol && type.symbol.valueDeclaration) { - return serializeEntityName(node.typeName, getGeneratedNameForNode); + return serializeEntityName(node.typeName); } else if (typeHasCallOrConstructSignatures(type)) { return "Function"; } return "Object"; } - function serializeTypeNode(node, getGeneratedNameForNode) { + function serializeTypeNode(node) { if (node) { switch (node.kind) { case 99: return "void 0"; - case 150: - return serializeTypeNode(node.type, getGeneratedNameForNode); - case 143: - case 144: + case 152: + return serializeTypeNode(node.type); + case 145: + case 146: return "Function"; - case 147: - case 148: + case 149: + case 150: return "Array"; case 113: return "Boolean"; - case 122: + case 123: case 8: return "String"; - case 120: + case 121: return "Number"; - case 142: - return serializeTypeReferenceNode(node, getGeneratedNameForNode); - case 145: - case 146: - case 149: + case 144: + return serializeTypeReferenceNode(node); + case 147: + case 148: + case 151: case 112: break; default: @@ -18233,23 +19738,23 @@ var ts; } return "Object"; } - function serializeTypeOfNode(node, getGeneratedNameForNode) { + function serializeTypeOfNode(node) { switch (node.kind) { - case 202: return "Function"; - case 133: return serializeTypeNode(node.type, getGeneratedNameForNode); - case 130: return serializeTypeNode(node.type, getGeneratedNameForNode); - case 137: return serializeTypeNode(node.type, getGeneratedNameForNode); - case 138: return serializeTypeNode(getSetAccessorTypeAnnotationNode(node), getGeneratedNameForNode); + case 204: return "Function"; + case 134: return serializeTypeNode(node.type); + case 131: return serializeTypeNode(node.type); + case 138: return serializeTypeNode(node.type); + case 139: return serializeTypeNode(getSetAccessorTypeAnnotationNode(node)); } if (ts.isFunctionLike(node)) { return "Function"; } return "void 0"; } - function serializeParameterTypesOfNode(node, getGeneratedNameForNode) { + function serializeParameterTypesOfNode(node) { if (node) { var valueDeclaration; - if (node.kind === 202) { + if (node.kind === 204) { valueDeclaration = ts.getFirstConstructorWithBody(node); } else if (ts.isFunctionLike(node) && ts.nodeIsPresent(node.body)) { @@ -18264,19 +19769,19 @@ var ts; for (var i = 0; i < parameterCount; i++) { if (parameters[i].dotDotDotToken) { var parameterType = parameters[i].type; - if (parameterType.kind === 147) { + if (parameterType.kind === 149) { parameterType = parameterType.elementType; } - else if (parameterType.kind === 142 && parameterType.typeArguments && parameterType.typeArguments.length === 1) { + else if (parameterType.kind === 144 && parameterType.typeArguments && parameterType.typeArguments.length === 1) { parameterType = parameterType.typeArguments[0]; } else { parameterType = undefined; } - result[i] = serializeTypeNode(parameterType, getGeneratedNameForNode); + result[i] = serializeTypeNode(parameterType); } else { - result[i] = serializeTypeOfNode(parameters[i], getGeneratedNameForNode); + result[i] = serializeTypeOfNode(parameters[i]); } } return result; @@ -18285,9 +19790,9 @@ var ts; } return emptyArray; } - function serializeReturnTypeOfNode(node, getGeneratedNameForNode) { + function serializeReturnTypeOfNode(node) { if (node && ts.isFunctionLike(node)) { - return serializeTypeNode(node.type, getGeneratedNameForNode); + return serializeTypeNode(node.type); } return "void 0"; } @@ -18309,25 +19814,24 @@ var ts; function hasGlobalName(name) { return ts.hasProperty(globals, name); } - function resolvesToSomeValue(location, name) { - ts.Debug.assert(!ts.nodeIsSynthesized(location), "resolvesToSomeValue called with a synthesized location"); - return !!resolveName(location, name, 107455, undefined, undefined); + function getReferencedValueSymbol(reference) { + return getNodeLinks(reference).resolvedSymbol || + resolveName(reference, reference.text, 107455 | 1048576 | 8388608, undefined, undefined); } function getReferencedValueDeclaration(reference) { ts.Debug.assert(!ts.nodeIsSynthesized(reference)); - var symbol = getNodeLinks(reference).resolvedSymbol || - resolveName(reference, reference.text, 107455 | 8388608, undefined, undefined); + var symbol = getReferencedValueSymbol(reference); return symbol && getExportSymbolOfValueSymbolIfExported(symbol).valueDeclaration; } function getBlockScopedVariableId(n) { ts.Debug.assert(!ts.nodeIsSynthesized(n)); - var isVariableDeclarationOrBindingElement = n.parent.kind === 153 || (n.parent.kind === 199 && n.parent.name === n); + var isVariableDeclarationOrBindingElement = n.parent.kind === 155 || (n.parent.kind === 201 && n.parent.name === n); var symbol = (isVariableDeclarationOrBindingElement ? getSymbolOfNode(n.parent) : undefined) || getNodeLinks(n).resolvedSymbol || resolveName(n, n.text, 107455 | 8388608, undefined, undefined); var isLetOrConst = symbol && (symbol.flags & 2) && - symbol.valueDeclaration.parent.kind !== 224; + symbol.valueDeclaration.parent.kind !== 226; if (isLetOrConst) { getSymbolLinks(symbol); return symbol.id; @@ -18347,7 +19851,10 @@ var ts; } function createResolver() { return { - getExpressionNameSubstitution: getExpressionNameSubstitution, + getReferencedExportContainer: getReferencedExportContainer, + getReferencedImportDeclaration: getReferencedImportDeclaration, + getReferencedNestedRedeclaration: getReferencedNestedRedeclaration, + isNestedRedeclaration: isNestedRedeclaration, isValueAliasDeclaration: isValueAliasDeclaration, hasGlobalName: hasGlobalName, isReferencedAliasDeclaration: isReferencedAliasDeclaration, @@ -18361,7 +19868,6 @@ var ts; isSymbolAccessible: isSymbolAccessible, isEntityNameVisible: isEntityNameVisible, getConstantValue: getConstantValue, - resolvesToSomeValue: resolvesToSomeValue, collectLinkedAliases: collectLinkedAliases, getBlockScopedVariableId: getBlockScopedVariableId, getReferencedValueDeclaration: getReferencedValueDeclaration, @@ -18383,8 +19889,7 @@ var ts; getSymbolLinks(argumentsSymbol).type = getGlobalType("IArguments"); getSymbolLinks(unknownSymbol).type = unknownType; globals[undefinedSymbol.name] = undefinedSymbol; - globalArraySymbol = getGlobalTypeSymbol("Array"); - globalArrayType = getTypeOfGlobalSymbol(globalArraySymbol, 1); + globalArrayType = getGlobalType("Array", 1); globalObjectType = getGlobalType("Object"); globalFunctionType = getGlobalType("Function"); globalStringType = getGlobalType("String"); @@ -18400,113 +19905,19 @@ var ts; globalESSymbolType = getGlobalType("Symbol"); globalESSymbolConstructorSymbol = getGlobalValueSymbol("Symbol"); globalIterableType = getGlobalType("Iterable", 1); + globalIteratorType = getGlobalType("Iterator", 1); + globalIterableIteratorType = getGlobalType("IterableIterator", 1); } else { globalTemplateStringsArrayType = unknownType; globalESSymbolType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); globalESSymbolConstructorSymbol = undefined; + globalIterableType = emptyGenericType; + globalIteratorType = emptyGenericType; + globalIterableIteratorType = emptyGenericType; } anyArrayType = createArrayType(anyType); } - function isReservedWordInStrictMode(node) { - return (node.parserContextFlags & 1) && - (102 <= node.originalKeywordKind && node.originalKeywordKind <= 110); - } - function reportStrictModeGrammarErrorInClassDeclaration(identifier, message, arg0, arg1, arg2) { - if (ts.getAncestor(identifier, 202) || ts.getAncestor(identifier, 175)) { - return grammarErrorOnNode(identifier, message, arg0); - } - return false; - } - function checkGrammarImportDeclarationNameInStrictMode(node) { - if (node.importClause) { - var impotClause = node.importClause; - if (impotClause.namedBindings) { - var nameBindings = impotClause.namedBindings; - if (nameBindings.kind === 212) { - var name_11 = nameBindings.name; - if (isReservedWordInStrictMode(name_11)) { - var nameText = ts.declarationNameToString(name_11); - return grammarErrorOnNode(name_11, ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode, nameText); - } - } - else if (nameBindings.kind === 213) { - var reportError = false; - for (var _i = 0, _a = nameBindings.elements; _i < _a.length; _i++) { - var element = _a[_i]; - var name_12 = element.name; - if (isReservedWordInStrictMode(name_12)) { - var nameText = ts.declarationNameToString(name_12); - reportError = reportError || grammarErrorOnNode(name_12, ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode, nameText); - } - } - return reportError; - } - } - } - return false; - } - function checkGrammarDeclarationNameInStrictMode(node) { - var name = node.name; - if (name && name.kind === 65 && isReservedWordInStrictMode(name)) { - var nameText = ts.declarationNameToString(name); - switch (node.kind) { - case 130: - case 199: - case 201: - case 129: - case 153: - case 203: - case 204: - case 205: - return checkGrammarIdentifierInStrictMode(name); - case 202: - return grammarErrorOnNode(name, ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_strict_mode, nameText); - case 206: - return grammarErrorOnNode(name, ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode, nameText); - case 209: - return grammarErrorOnNode(name, ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode, nameText); - } - } - return false; - } - function checkGrammarTypeReferenceInStrictMode(typeName) { - if (typeName.kind === 65) { - checkGrammarTypeNameInStrictMode(typeName); - } - else if (typeName.kind === 127) { - checkGrammarTypeNameInStrictMode(typeName.right); - checkGrammarTypeReferenceInStrictMode(typeName.left); - } - } - function checkGrammarExpressionWithTypeArgumentsInStrictMode(expression) { - if (expression && expression.kind === 65) { - return checkGrammarIdentifierInStrictMode(expression); - } - else if (expression && expression.kind === 156) { - checkGrammarExpressionWithTypeArgumentsInStrictMode(expression.expression); - } - } - function checkGrammarIdentifierInStrictMode(node, nameText) { - if (node && node.kind === 65 && isReservedWordInStrictMode(node)) { - if (!nameText) { - nameText = ts.declarationNameToString(node); - } - var errorReport = reportStrictModeGrammarErrorInClassDeclaration(node, ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_strict_mode, nameText) || - grammarErrorOnNode(node, ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode, nameText); - return errorReport; - } - return false; - } - function checkGrammarTypeNameInStrictMode(node) { - if (node && node.kind === 65 && isReservedWordInStrictMode(node)) { - var nameText = ts.declarationNameToString(node); - var errorReport = reportStrictModeGrammarErrorInClassDeclaration(node, ts.Diagnostics.Type_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_strict_mode, nameText) || - grammarErrorOnNode(node, ts.Diagnostics.Type_expected_0_is_a_reserved_word_in_strict_mode, nameText); - return errorReport; - } - return false; - } function checkGrammarDecorators(node) { if (!node.decorators) { return false; @@ -18517,7 +19928,7 @@ var ts; else if (languageVersion < 1) { return grammarErrorOnFirstToken(node, ts.Diagnostics.Decorators_are_only_available_when_targeting_ECMAScript_5_and_higher); } - else if (node.kind === 137 || node.kind === 138) { + else if (node.kind === 138 || node.kind === 139) { 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); @@ -18527,26 +19938,35 @@ var ts; } function checkGrammarModifiers(node) { switch (node.kind) { - case 137: case 138: - case 136: - case 133: - case 132: - case 135: + case 139: + case 137: case 134: - case 141: - case 202: + case 133: + case 136: + case 135: + case 142: + case 208: + case 212: + case 211: + case 218: + case 217: + case 131: + break; + case 204: + case 205: + case 183: case 203: case 206: - case 205: - case 181: - case 201: - case 204: - case 210: - case 209: - case 216: - case 215: - case 130: + if (node.modifiers && node.parent.kind !== 209 && node.parent.kind !== 230) { + return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here); + } + break; + case 207: + if (node.modifiers && (node.modifiers.length > 1 || node.modifiers[0].kind !== 70) && + node.parent.kind !== 209 && node.parent.kind !== 230) { + return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here); + } break; default: return false; @@ -18580,7 +20000,7 @@ var ts; else if (flags & 128) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "static"); } - else if (node.parent.kind === 207 || node.parent.kind === 228) { + else if (node.parent.kind === 209 || node.parent.kind === 230) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_element, text); } flags |= ts.modifierToFlag(modifier.kind); @@ -18589,10 +20009,10 @@ var ts; if (flags & 128) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "static"); } - else if (node.parent.kind === 207 || node.parent.kind === 228) { + else if (node.parent.kind === 209 || node.parent.kind === 230) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_element, "static"); } - else if (node.kind === 130) { + else if (node.kind === 131) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "static"); } flags |= 128; @@ -18605,10 +20025,10 @@ var ts; else if (flags & 2) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "export", "declare"); } - else if (node.parent.kind === 202) { + else if (node.parent.kind === 204) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_class_element, "export"); } - else if (node.kind === 130) { + else if (node.kind === 131) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "export"); } flags |= 1; @@ -18617,13 +20037,13 @@ var ts; if (flags & 2) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "declare"); } - else if (node.parent.kind === 202) { + else if (node.parent.kind === 204) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_class_element, "declare"); } - else if (node.kind === 130) { + else if (node.kind === 131) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "declare"); } - else if (ts.isInAmbientContext(node.parent) && node.parent.kind === 207) { + else if (ts.isInAmbientContext(node.parent) && node.parent.kind === 209) { return grammarErrorOnNode(modifier, ts.Diagnostics.A_declare_modifier_cannot_be_used_in_an_already_ambient_context); } flags |= 2; @@ -18631,7 +20051,7 @@ var ts; break; } } - if (node.kind === 136) { + if (node.kind === 137) { if (flags & 128) { return grammarErrorOnNode(lastStatic, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "static"); } @@ -18642,13 +20062,10 @@ var ts; return grammarErrorOnNode(lastPrivate, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "private"); } } - else if ((node.kind === 210 || node.kind === 209) && flags & 2) { + else if ((node.kind === 212 || node.kind === 211) && flags & 2) { return grammarErrorOnNode(lastDeclare, ts.Diagnostics.A_declare_modifier_cannot_be_used_with_an_import_declaration, "declare"); } - else if (node.kind === 203 && flags & 2) { - return grammarErrorOnNode(lastDeclare, ts.Diagnostics.A_declare_modifier_cannot_be_used_with_an_interface_declaration, "declare"); - } - else if (node.kind === 130 && (flags & 112) && ts.isBindingPattern(node.name)) { + else if (node.kind === 131 && (flags & 112) && ts.isBindingPattern(node.name)) { return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_may_not_be_a_binding_pattern); } } @@ -18711,7 +20128,7 @@ var ts; checkGrammarParameterList(node.parameters) || checkGrammarArrowFunction(node, file); } function checkGrammarArrowFunction(node, file) { - if (node.kind === 164) { + if (node.kind === 166) { var arrowFunction = node; var startLine = ts.getLineAndCharacterOfPosition(file, arrowFunction.equalsGreaterThanToken.pos).line; var endLine = ts.getLineAndCharacterOfPosition(file, arrowFunction.equalsGreaterThanToken.end).line; @@ -18746,7 +20163,7 @@ var ts; if (!parameter.type) { return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_must_have_a_type_annotation); } - if (parameter.type.kind !== 122 && parameter.type.kind !== 120) { + if (parameter.type.kind !== 123 && parameter.type.kind !== 121) { return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_must_be_string_or_number); } if (!node.type) { @@ -18778,7 +20195,7 @@ var ts; var sourceFile = ts.getSourceFileOfNode(node); for (var _i = 0; _i < arguments.length; _i++) { var arg = arguments[_i]; - if (arg.kind === 176) { + if (arg.kind === 178) { return grammarErrorAtPos(sourceFile, arg.pos, 0, ts.Diagnostics.Argument_expression_expected); } } @@ -18849,22 +20266,30 @@ var ts; return false; } function checkGrammarComputedPropertyName(node) { - if (node.kind !== 128) { + if (node.kind !== 129) { return false; } var computedPropertyName = node; - if (computedPropertyName.expression.kind === 170 && computedPropertyName.expression.operatorToken.kind === 23) { + if (computedPropertyName.expression.kind === 172 && computedPropertyName.expression.operatorToken.kind === 23) { return grammarErrorOnNode(computedPropertyName.expression, ts.Diagnostics.A_comma_expression_is_not_allowed_in_a_computed_property_name); } } function checkGrammarForGenerator(node) { if (node.asteriskToken) { - return grammarErrorOnNode(node.asteriskToken, ts.Diagnostics.Generators_are_not_currently_supported); + ts.Debug.assert(node.kind === 203 || + node.kind === 165 || + node.kind === 136); + 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); + } + if (languageVersion < 2) { + return grammarErrorOnNode(node.asteriskToken, ts.Diagnostics.Generators_are_only_available_when_targeting_ECMAScript_6_or_higher); + } } } - function checkGrammarFunctionName(name) { - return checkGrammarEvalOrArgumentsInStrictMode(name, name); - } function checkGrammarForInvalidQuestionMark(node, questionToken, message) { if (questionToken) { return grammarErrorOnNode(questionToken, message); @@ -18876,55 +20301,52 @@ var ts; var GetAccessor = 2; var SetAccesor = 4; var GetOrSetAccessor = GetAccessor | SetAccesor; - var inStrictMode = (node.parserContextFlags & 1) !== 0; for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { var prop = _a[_i]; - var name_13 = prop.name; - if (prop.kind === 176 || - name_13.kind === 128) { - checkGrammarComputedPropertyName(name_13); + var name_15 = prop.name; + if (prop.kind === 178 || + name_15.kind === 129) { + checkGrammarComputedPropertyName(name_15); continue; } var currentKind = void 0; - if (prop.kind === 225 || prop.kind === 226) { + if (prop.kind === 227 || prop.kind === 228) { checkGrammarForInvalidQuestionMark(prop, prop.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional); - if (name_13.kind === 7) { - checkGrammarNumericLiteral(name_13); + if (name_15.kind === 7) { + checkGrammarNumericLiteral(name_15); } currentKind = Property; } - else if (prop.kind === 135) { + else if (prop.kind === 136) { currentKind = Property; } - else if (prop.kind === 137) { + else if (prop.kind === 138) { currentKind = GetAccessor; } - else if (prop.kind === 138) { + else if (prop.kind === 139) { currentKind = SetAccesor; } else { ts.Debug.fail("Unexpected syntax kind:" + prop.kind); } - if (!ts.hasProperty(seen, name_13.text)) { - seen[name_13.text] = currentKind; + if (!ts.hasProperty(seen, name_15.text)) { + seen[name_15.text] = currentKind; } else { - var existingKind = seen[name_13.text]; + var existingKind = seen[name_15.text]; if (currentKind === Property && existingKind === Property) { - if (inStrictMode) { - grammarErrorOnNode(name_13, ts.Diagnostics.An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode); - } + continue; } else if ((currentKind & GetOrSetAccessor) && (existingKind & GetOrSetAccessor)) { if (existingKind !== GetOrSetAccessor && currentKind !== existingKind) { - seen[name_13.text] = currentKind | existingKind; + seen[name_15.text] = currentKind | existingKind; } else { - return grammarErrorOnNode(name_13, ts.Diagnostics.An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name); + return grammarErrorOnNode(name_15, ts.Diagnostics.An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name); } } else { - return grammarErrorOnNode(name_13, ts.Diagnostics.An_object_literal_cannot_have_property_and_accessor_with_the_same_name); + return grammarErrorOnNode(name_15, ts.Diagnostics.An_object_literal_cannot_have_property_and_accessor_with_the_same_name); } } } @@ -18933,24 +20355,24 @@ var ts; if (checkGrammarStatementInAmbientContext(forInOrOfStatement)) { return true; } - if (forInOrOfStatement.initializer.kind === 200) { + if (forInOrOfStatement.initializer.kind === 202) { var variableList = forInOrOfStatement.initializer; if (!checkGrammarVariableDeclarationList(variableList)) { if (variableList.declarations.length > 1) { - var diagnostic = forInOrOfStatement.kind === 188 + var diagnostic = forInOrOfStatement.kind === 190 ? 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 = variableList.declarations[0]; if (firstDeclaration.initializer) { - var diagnostic = forInOrOfStatement.kind === 188 + var diagnostic = forInOrOfStatement.kind === 190 ? 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 === 188 + var diagnostic = forInOrOfStatement.kind === 190 ? 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); @@ -18973,10 +20395,10 @@ var ts; else if (accessor.typeParameters) { return grammarErrorOnNode(accessor.name, ts.Diagnostics.An_accessor_cannot_have_type_parameters); } - else if (kind === 137 && accessor.parameters.length) { + else if (kind === 138 && accessor.parameters.length) { return grammarErrorOnNode(accessor.name, ts.Diagnostics.A_get_accessor_cannot_have_parameters); } - else if (kind === 138) { + else if (kind === 139) { if (accessor.type) { return grammarErrorOnNode(accessor.name, ts.Diagnostics.A_set_accessor_cannot_have_a_return_type_annotation); } @@ -19001,7 +20423,7 @@ var ts; } } function checkGrammarForNonSymbolComputedProperty(node, message) { - if (node.kind === 128 && !ts.isWellKnownSymbolSyntactically(node.expression)) { + if (node.kind === 129 && !ts.isWellKnownSymbolSyntactically(node.expression)) { return grammarErrorOnNode(node, message); } } @@ -19011,7 +20433,7 @@ var ts; checkGrammarForGenerator(node)) { return true; } - if (node.parent.kind === 155) { + if (node.parent.kind === 157) { if (checkGrammarForInvalidQuestionMark(node, node.questionToken, ts.Diagnostics.A_class_member_cannot_be_declared_optional)) { return true; } @@ -19019,7 +20441,7 @@ var ts; return grammarErrorAtPos(getSourceFile(node), node.end - 1, ";".length, ts.Diagnostics._0_expected, "{"); } } - if (node.parent.kind === 202) { + if (node.parent.kind === 204) { if (checkGrammarForInvalidQuestionMark(node, node.questionToken, ts.Diagnostics.A_class_member_cannot_be_declared_optional)) { return true; } @@ -19030,22 +20452,22 @@ var ts; 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 === 203) { + else if (node.parent.kind === 205) { 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 === 146) { + else if (node.parent.kind === 148) { return checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_a_type_literal_must_directly_refer_to_a_built_in_symbol); } } function isIterationStatement(node, lookInLabeledStatements) { switch (node.kind) { + case 189: + case 190: + case 191: case 187: case 188: - case 189: - case 185: - case 186: return true; - case 195: + case 197: return lookInLabeledStatements && isIterationStatement(node.statement, lookInLabeledStatements); } return false; @@ -19057,9 +20479,9 @@ var ts; return grammarErrorOnNode(node, ts.Diagnostics.Jump_target_cannot_cross_function_boundary); } switch (current.kind) { - case 195: + case 197: if (node.label && current.label.text === node.label.text) { - var isMisplacedContinueLabel = node.kind === 190 + var isMisplacedContinueLabel = node.kind === 192 && !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); @@ -19067,8 +20489,8 @@ var ts; return false; } break; - case 194: - if (node.kind === 191 && !node.label) { + case 196: + if (node.kind === 193 && !node.label) { return false; } break; @@ -19081,13 +20503,13 @@ var ts; current = current.parent; } if (node.label) { - var message = node.kind === 191 + var message = node.kind === 193 ? 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 === 191 + var message = node.kind === 193 ? 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); @@ -19099,17 +20521,16 @@ var ts; if (node !== ts.lastOrUndefined(elements)) { return grammarErrorOnNode(node, ts.Diagnostics.A_rest_element_must_be_last_in_an_array_destructuring_pattern); } - if (node.name.kind === 152 || node.name.kind === 151) { + if (node.name.kind === 154 || node.name.kind === 153) { 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); } } - return checkGrammarEvalOrArgumentsInStrictMode(node, node.name); } function checkGrammarVariableDeclaration(node) { - if (node.parent.parent.kind !== 188 && node.parent.parent.kind !== 189) { + if (node.parent.parent.kind !== 190 && node.parent.parent.kind !== 191) { if (ts.isInAmbientContext(node)) { if (node.initializer) { var equalsTokenLength = "=".length; @@ -19126,8 +20547,7 @@ var ts; } } var checkLetConstNames = languageVersion >= 2 && (ts.isLet(node) || ts.isConst(node)); - return (checkLetConstNames && checkGrammarNameInLetOrConstDeclarations(node.name)) || - checkGrammarEvalOrArgumentsInStrictMode(node, node.name); + return checkLetConstNames && checkGrammarNameInLetOrConstDeclarations(node.name); } function checkGrammarNameInLetOrConstDeclarations(name) { if (name.kind === 65) { @@ -19139,7 +20559,7 @@ var ts; var elements = name.elements; for (var _i = 0; _i < elements.length; _i++) { var element = elements[_i]; - if (element.kind !== 176) { + if (element.kind !== 178) { checkGrammarNameInLetOrConstDeclarations(element.name); } } @@ -19156,15 +20576,15 @@ var ts; } function allowLetAndConstDeclarations(parent) { switch (parent.kind) { - case 184: - case 185: case 186: - case 193: case 187: case 188: - case 189: - return false; case 195: + case 189: + case 190: + case 191: + return false; + case 197: return allowLetAndConstDeclarations(parent.parent); } return true; @@ -19180,7 +20600,7 @@ var ts; } } function isIntegerLiteral(expression) { - if (expression.kind === 168) { + if (expression.kind === 170) { var unaryExpression = expression; if (unaryExpression.operator === 33 || unaryExpression.operator === 34) { expression = unaryExpression.operand; @@ -19199,7 +20619,7 @@ var ts; var inAmbientContext = ts.isInAmbientContext(enumDecl); for (var _i = 0, _a = enumDecl.members; _i < _a.length; _i++) { var node = _a[_i]; - if (node.name.kind === 128) { + if (node.name.kind === 129) { hasError = grammarErrorOnNode(node.name, ts.Diagnostics.Computed_property_names_are_not_allowed_in_enums); } else if (inAmbientContext) { @@ -19241,23 +20661,6 @@ var ts; return true; } } - function checkGrammarEvalOrArgumentsInStrictMode(contextNode, name) { - if (name && name.kind === 65) { - var identifier = name; - if (contextNode && (contextNode.parserContextFlags & 1) && isEvalOrArgumentsIdentifier(identifier)) { - var nameText = ts.declarationNameToString(identifier); - var reportErrorInClassDeclaration = reportStrictModeGrammarErrorInClassDeclaration(identifier, ts.Diagnostics.Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode, nameText); - if (!reportErrorInClassDeclaration) { - return grammarErrorOnNode(identifier, ts.Diagnostics.Invalid_use_of_0_in_strict_mode, nameText); - } - return reportErrorInClassDeclaration; - } - } - } - function isEvalOrArgumentsIdentifier(node) { - return node.kind === 65 && - (node.text === "eval" || node.text === "arguments"); - } 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); @@ -19269,18 +20672,18 @@ var ts; } } function checkGrammarProperty(node) { - if (node.parent.kind === 202) { + if (node.parent.kind === 204) { if (checkGrammarForInvalidQuestionMark(node, node.questionToken, ts.Diagnostics.A_class_member_cannot_be_declared_optional) || 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 === 203) { + else if (node.parent.kind === 205) { if (checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_an_interface_must_directly_refer_to_a_built_in_symbol)) { return true; } } - else if (node.parent.kind === 146) { + else if (node.parent.kind === 148) { if (checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_a_type_literal_must_directly_refer_to_a_built_in_symbol)) { return true; } @@ -19290,11 +20693,11 @@ var ts; } } function checkGrammarTopLevelElementForRequiredDeclareModifier(node) { - if (node.kind === 203 || - node.kind === 210 || - node.kind === 209 || - node.kind === 216 || - node.kind === 215 || + if (node.kind === 205 || + node.kind === 212 || + node.kind === 211 || + node.kind === 218 || + node.kind === 217 || (node.flags & 2) || (node.flags & (1 | 256))) { return false; @@ -19304,7 +20707,7 @@ var ts; function checkGrammarTopLevelElementsForRequiredDeclareModifier(file) { for (var _i = 0, _a = file.statements; _i < _a.length; _i++) { var decl = _a[_i]; - if (ts.isDeclaration(decl) || decl.kind === 181) { + if (ts.isDeclaration(decl) || decl.kind === 183) { if (checkGrammarTopLevelElementForRequiredDeclareModifier(decl)) { return true; } @@ -19323,7 +20726,7 @@ var ts; 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 === 180 || node.parent.kind === 207 || node.parent.kind === 228) { + if (node.parent.kind === 182 || node.parent.kind === 209 || node.parent.kind === 230) { 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); @@ -19334,13 +20737,8 @@ var ts; } } function checkGrammarNumericLiteral(node) { - if (node.flags & 16384) { - if (node.parserContextFlags & 1) { - return grammarErrorOnNode(node, ts.Diagnostics.Octal_literals_are_not_allowed_in_strict_mode); - } - else if (languageVersion >= 1) { - return grammarErrorOnNode(node, ts.Diagnostics.Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher); - } + if (node.flags & 16384 && languageVersion >= 1) { + return grammarErrorOnNode(node, ts.Diagnostics.Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher); } } function grammarErrorAfterFirstToken(node, message, arg0, arg1, arg2) { @@ -19351,8 +20749,6 @@ var ts; return true; } } - initializeTypeChecker(); - return checker; } ts.createTypeChecker = createTypeChecker; })(ts || (ts = {})); @@ -19404,7 +20800,7 @@ var ts; var oldWriter = writer; ts.forEach(moduleElementDeclarationEmitInfo, function (aliasEmitInfo) { if (aliasEmitInfo.isVisible) { - ts.Debug.assert(aliasEmitInfo.node.kind === 210); + ts.Debug.assert(aliasEmitInfo.node.kind === 212); createAndSetNewTextWriterWithSymbolWriter(); ts.Debug.assert(aliasEmitInfo.indent === 0); writeImportDeclaration(aliasEmitInfo.node); @@ -19477,10 +20873,10 @@ var ts; var oldWriter = writer; ts.forEach(nodes, function (declaration) { var nodeToCheck; - if (declaration.kind === 199) { + if (declaration.kind === 201) { nodeToCheck = declaration.parent.parent; } - else if (declaration.kind === 213 || declaration.kind === 214 || declaration.kind === 211) { + else if (declaration.kind === 215 || declaration.kind === 216 || declaration.kind === 213) { ts.Debug.fail("We should be getting ImportDeclaration instead to write"); } else { @@ -19491,7 +20887,7 @@ var ts; moduleElementEmitInfo = ts.forEach(asynchronousSubModuleDeclarationEmitInfo, function (declEmitInfo) { return declEmitInfo.node === nodeToCheck ? declEmitInfo : undefined; }); } if (moduleElementEmitInfo) { - if (moduleElementEmitInfo.node.kind === 210) { + if (moduleElementEmitInfo.node.kind === 212) { moduleElementEmitInfo.isVisible = true; } else { @@ -19499,12 +20895,12 @@ var ts; for (var declarationIndent = moduleElementEmitInfo.indent; declarationIndent; declarationIndent--) { increaseIndent(); } - if (nodeToCheck.kind === 206) { + if (nodeToCheck.kind === 208) { ts.Debug.assert(asynchronousSubModuleDeclarationEmitInfo === undefined); asynchronousSubModuleDeclarationEmitInfo = []; } writeModuleElement(nodeToCheck); - if (nodeToCheck.kind === 206) { + if (nodeToCheck.kind === 208) { moduleElementEmitInfo.subModuleElementDeclarationEmitInfo = asynchronousSubModuleDeclarationEmitInfo; asynchronousSubModuleDeclarationEmitInfo = undefined; } @@ -19592,39 +20988,39 @@ var ts; function emitType(type) { switch (type.kind) { case 112: - case 122: - case 120: - case 113: case 123: + case 121: + case 113: + case 124: case 99: case 8: return writeTextOfNode(currentSourceFile, type); - case 177: + case 179: return emitExpressionWithTypeArguments(type); - case 142: - return emitTypeReference(type); - case 145: - return emitTypeQuery(type); - case 147: - return emitArrayType(type); - case 148: - return emitTupleType(type); - case 149: - return emitUnionType(type); - case 150: - return emitParenType(type); - case 143: case 144: - return emitSignatureDeclarationWithJsDocComments(type); + return emitTypeReference(type); + case 147: + return emitTypeQuery(type); + case 149: + return emitArrayType(type); + case 150: + return emitTupleType(type); + case 151: + return emitUnionType(type); + case 152: + return emitParenType(type); + case 145: case 146: + return emitSignatureDeclarationWithJsDocComments(type); + case 148: return emitTypeLiteral(type); case 65: return emitEntityName(type); - case 127: + case 128: return emitEntityName(type); } function emitEntityName(entityName) { - var visibilityResult = resolver.isEntityNameVisible(entityName, entityName.parent.kind === 209 ? entityName.parent : enclosingDeclaration); + var visibilityResult = resolver.isEntityNameVisible(entityName, entityName.parent.kind === 211 ? entityName.parent : enclosingDeclaration); handleSymbolAccessibilityError(visibilityResult); writeEntityName(entityName); function writeEntityName(entityName) { @@ -19632,8 +21028,8 @@ var ts; writeTextOfNode(currentSourceFile, entityName); } else { - var left = entityName.kind === 127 ? entityName.left : entityName.expression; - var right = entityName.kind === 127 ? entityName.right : entityName.name; + var left = entityName.kind === 128 ? entityName.left : entityName.expression; + var right = entityName.kind === 128 ? entityName.right : entityName.name; writeEntityName(left); write("."); writeTextOfNode(currentSourceFile, right); @@ -19642,7 +21038,7 @@ var ts; } function emitExpressionWithTypeArguments(node) { if (ts.isSupportedExpressionWithTypeArguments(node)) { - ts.Debug.assert(node.expression.kind === 65 || node.expression.kind === 156); + ts.Debug.assert(node.expression.kind === 65 || node.expression.kind === 158); emitEntityName(node.expression); if (node.typeArguments) { write("<"); @@ -19703,9 +21099,9 @@ var ts; } var count = 0; while (true) { - var name_14 = baseName + "_" + (++count); - if (!ts.hasProperty(currentSourceFile.identifiers, name_14)) { - return name_14; + var name_16 = baseName + "_" + (++count); + if (!ts.hasProperty(currentSourceFile.identifiers, name_16)) { + return name_16; } } } @@ -19746,10 +21142,10 @@ var ts; if (isModuleElementVisible) { writeModuleElement(node); } - else if (node.kind === 209 || - (node.parent.kind === 228 && ts.isExternalModule(currentSourceFile))) { + else if (node.kind === 211 || + (node.parent.kind === 230 && ts.isExternalModule(currentSourceFile))) { var isVisible; - if (asynchronousSubModuleDeclarationEmitInfo && node.parent.kind !== 228) { + if (asynchronousSubModuleDeclarationEmitInfo && node.parent.kind !== 230) { asynchronousSubModuleDeclarationEmitInfo.push({ node: node, outputPos: writer.getTextPos(), @@ -19758,7 +21154,7 @@ var ts; }); } else { - if (node.kind === 210) { + if (node.kind === 212) { var importDeclaration = node; if (importDeclaration.importClause) { isVisible = (importDeclaration.importClause.name && resolver.isDeclarationVisible(importDeclaration.importClause)) || @@ -19776,23 +21172,23 @@ var ts; } function writeModuleElement(node) { switch (node.kind) { - case 201: - return writeFunctionDeclaration(node); - case 181: - return writeVariableStatement(node); case 203: - return writeInterfaceDeclaration(node); - case 202: - return writeClassDeclaration(node); - case 204: - return writeTypeAliasDeclaration(node); + return writeFunctionDeclaration(node); + case 183: + return writeVariableStatement(node); case 205: - return writeEnumDeclaration(node); + return writeInterfaceDeclaration(node); + case 204: + return writeClassDeclaration(node); case 206: + return writeTypeAliasDeclaration(node); + case 207: + return writeEnumDeclaration(node); + case 208: return writeModuleDeclaration(node); - case 209: + case 211: return writeImportEqualsDeclaration(node); - case 210: + case 212: return writeImportDeclaration(node); default: ts.Debug.fail("Unknown symbol kind"); @@ -19806,7 +21202,7 @@ var ts; if (node.flags & 256) { write("default "); } - else if (node.kind !== 203) { + else if (node.kind !== 205) { write("declare "); } } @@ -19850,7 +21246,7 @@ var ts; } function isVisibleNamedBinding(namedBindings) { if (namedBindings) { - if (namedBindings.kind === 212) { + if (namedBindings.kind === 214) { return resolver.isDeclarationVisible(namedBindings); } else { @@ -19876,7 +21272,7 @@ var ts; if (currentWriterPos !== writer.getTextPos()) { write(", "); } - if (node.importClause.namedBindings.kind === 212) { + if (node.importClause.namedBindings.kind === 214) { write("* as "); writeTextOfNode(currentSourceFile, node.importClause.namedBindings.name); } @@ -19925,9 +21321,14 @@ var ts; function writeModuleDeclaration(node) { emitJsDocComments(node); emitModuleElementDeclarationFlags(node); - write("module "); + if (node.flags & 32768) { + write("namespace "); + } + else { + write("module "); + } writeTextOfNode(currentSourceFile, node.name); - while (node.body.kind !== 207) { + while (node.body.kind !== 209) { node = node.body; write("."); writeTextOfNode(currentSourceFile, node.name); @@ -19988,7 +21389,7 @@ var ts; writeLine(); } function isPrivateMethodTypeParameter(node) { - return node.parent.kind === 135 && (node.parent.flags & 32); + return node.parent.kind === 136 && (node.parent.flags & 32); } function emitTypeParameters(typeParameters) { function emitTypeParameter(node) { @@ -19998,15 +21399,15 @@ var ts; writeTextOfNode(currentSourceFile, node.name); if (node.constraint && !isPrivateMethodTypeParameter(node)) { write(" extends "); - if (node.parent.kind === 143 || - node.parent.kind === 144 || - (node.parent.parent && node.parent.parent.kind === 146)) { - ts.Debug.assert(node.parent.kind === 135 || - node.parent.kind === 134 || - node.parent.kind === 143 || - node.parent.kind === 144 || - node.parent.kind === 139 || - node.parent.kind === 140); + if (node.parent.kind === 145 || + node.parent.kind === 146 || + (node.parent.parent && node.parent.parent.kind === 148)) { + ts.Debug.assert(node.parent.kind === 136 || + node.parent.kind === 135 || + node.parent.kind === 145 || + node.parent.kind === 146 || + node.parent.kind === 140 || + node.parent.kind === 141); emitType(node.constraint); } else { @@ -20016,31 +21417,31 @@ var ts; function getTypeParameterConstraintVisibilityError(symbolAccesibilityResult) { var diagnosticMessage; switch (node.parent.kind) { - case 202: + case 204: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_class_has_or_is_using_private_name_1; break; - case 203: + case 205: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1; break; - case 140: + case 141: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1; break; - case 139: + case 140: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1; break; + case 136: case 135: - case 134: if (node.parent.flags & 128) { diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1; } - else if (node.parent.parent.kind === 202) { + else if (node.parent.parent.kind === 204) { diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1; } else { diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1; } break; - case 201: + case 203: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_function_has_or_is_using_private_name_1; break; default: @@ -20070,7 +21471,7 @@ var ts; } function getHeritageClauseVisibilityError(symbolAccesibilityResult) { var diagnosticMessage; - if (node.parent.parent.kind === 202) { + if (node.parent.parent.kind === 204) { diagnosticMessage = isImplementsList ? ts.Diagnostics.Implements_clause_of_exported_class_0_has_or_is_using_private_name_1 : ts.Diagnostics.Extends_clause_of_exported_class_0_has_or_is_using_private_name_1; @@ -20147,16 +21548,16 @@ var ts; writeLine(); } function emitVariableDeclaration(node) { - if (node.kind !== 199 || resolver.isDeclarationVisible(node)) { + if (node.kind !== 201 || resolver.isDeclarationVisible(node)) { if (ts.isBindingPattern(node.name)) { emitBindingPattern(node.name); } else { writeTextOfNode(currentSourceFile, node.name); - if ((node.kind === 133 || node.kind === 132) && ts.hasQuestionToken(node)) { + if ((node.kind === 134 || node.kind === 133) && ts.hasQuestionToken(node)) { write("?"); } - if ((node.kind === 133 || node.kind === 132) && node.parent.kind === 146) { + if ((node.kind === 134 || node.kind === 133) && node.parent.kind === 148) { emitTypeOfVariableDeclarationFromTypeLiteral(node); } else if (!(node.flags & 32)) { @@ -20165,14 +21566,14 @@ var ts; } } function getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccesibilityResult) { - if (node.kind === 199) { + if (node.kind === 201) { return symbolAccesibilityResult.errorModuleName ? symbolAccesibilityResult.accessibility === 2 ? ts.Diagnostics.Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : ts.Diagnostics.Exported_variable_0_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Exported_variable_0_has_or_is_using_private_name_1; } - else if (node.kind === 133 || node.kind === 132) { + else if (node.kind === 134 || node.kind === 133) { if (node.flags & 128) { return symbolAccesibilityResult.errorModuleName ? symbolAccesibilityResult.accessibility === 2 ? @@ -20180,7 +21581,7 @@ var ts; ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_private_name_1; } - else if (node.parent.kind === 202) { + else if (node.parent.kind === 204) { return symbolAccesibilityResult.errorModuleName ? symbolAccesibilityResult.accessibility === 2 ? ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : @@ -20206,7 +21607,7 @@ var ts; var elements = []; for (var _i = 0, _a = bindingPattern.elements; _i < _a.length; _i++) { var element = _a[_i]; - if (element.kind !== 176) { + if (element.kind !== 178) { elements.push(element); } } @@ -20272,7 +21673,7 @@ var ts; accessorWithTypeAnnotation = node; var type = getTypeAnnotationFromAccessor(node); if (!type) { - var anotherAccessor = node.kind === 137 ? accessors.setAccessor : accessors.getAccessor; + var anotherAccessor = node.kind === 138 ? accessors.setAccessor : accessors.getAccessor; type = getTypeAnnotationFromAccessor(anotherAccessor); if (type) { accessorWithTypeAnnotation = anotherAccessor; @@ -20285,7 +21686,7 @@ var ts; } function getTypeAnnotationFromAccessor(accessor) { if (accessor) { - return accessor.kind === 137 + return accessor.kind === 138 ? accessor.type : accessor.parameters.length > 0 ? accessor.parameters[0].type @@ -20294,7 +21695,7 @@ var ts; } function getAccessorDeclarationTypeVisibilityError(symbolAccesibilityResult) { var diagnosticMessage; - if (accessorWithTypeAnnotation.kind === 138) { + if (accessorWithTypeAnnotation.kind === 139) { if (accessorWithTypeAnnotation.parent.flags & 128) { diagnosticMessage = symbolAccesibilityResult.errorModuleName ? ts.Diagnostics.Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_name_1_from_private_module_2 : @@ -20340,17 +21741,17 @@ var ts; } if (!resolver.isImplementationOfOverload(node)) { emitJsDocComments(node); - if (node.kind === 201) { + if (node.kind === 203) { emitModuleElementDeclarationFlags(node); } - else if (node.kind === 135) { + else if (node.kind === 136) { emitClassMemberDeclarationFlags(node); } - if (node.kind === 201) { + if (node.kind === 203) { write("function "); writeTextOfNode(currentSourceFile, node.name); } - else if (node.kind === 136) { + else if (node.kind === 137) { write("constructor"); } else { @@ -20367,11 +21768,11 @@ var ts; emitSignatureDeclaration(node); } function emitSignatureDeclaration(node) { - if (node.kind === 140 || node.kind === 144) { + if (node.kind === 141 || node.kind === 146) { write("new "); } emitTypeParameters(node.typeParameters); - if (node.kind === 141) { + if (node.kind === 142) { write("["); } else { @@ -20380,20 +21781,20 @@ var ts; var prevEnclosingDeclaration = enclosingDeclaration; enclosingDeclaration = node; emitCommaList(node.parameters, emitParameterDeclaration); - if (node.kind === 141) { + if (node.kind === 142) { write("]"); } else { write(")"); } - var isFunctionTypeOrConstructorType = node.kind === 143 || node.kind === 144; - if (isFunctionTypeOrConstructorType || node.parent.kind === 146) { + var isFunctionTypeOrConstructorType = node.kind === 145 || node.kind === 146; + if (isFunctionTypeOrConstructorType || node.parent.kind === 148) { if (node.type) { write(isFunctionTypeOrConstructorType ? " => " : ": "); emitType(node.type); } } - else if (node.kind !== 136 && !(node.flags & 32)) { + else if (node.kind !== 137 && !(node.flags & 32)) { writeReturnTypeAtSignature(node, getReturnTypeVisibilityError); } enclosingDeclaration = prevEnclosingDeclaration; @@ -20404,23 +21805,23 @@ var ts; function getReturnTypeVisibilityError(symbolAccesibilityResult) { var diagnosticMessage; switch (node.kind) { - case 140: + case 141: diagnosticMessage = symbolAccesibilityResult.errorModuleName ? ts.Diagnostics.Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0; break; - case 139: + case 140: diagnosticMessage = symbolAccesibilityResult.errorModuleName ? ts.Diagnostics.Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0; break; - case 141: + case 142: diagnosticMessage = symbolAccesibilityResult.errorModuleName ? ts.Diagnostics.Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0; break; + case 136: case 135: - case 134: if (node.flags & 128) { diagnosticMessage = symbolAccesibilityResult.errorModuleName ? symbolAccesibilityResult.accessibility === 2 ? @@ -20428,7 +21829,7 @@ var ts; ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0; } - else if (node.parent.kind === 202) { + else if (node.parent.kind === 204) { diagnosticMessage = symbolAccesibilityResult.errorModuleName ? symbolAccesibilityResult.accessibility === 2 ? ts.Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : @@ -20441,7 +21842,7 @@ var ts; ts.Diagnostics.Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0; } break; - case 201: + case 203: diagnosticMessage = symbolAccesibilityResult.errorModuleName ? symbolAccesibilityResult.accessibility === 2 ? ts.Diagnostics.Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : @@ -20473,9 +21874,9 @@ var ts; write("?"); } decreaseIndent(); - if (node.parent.kind === 143 || - node.parent.kind === 144 || - node.parent.parent.kind === 146) { + if (node.parent.kind === 145 || + node.parent.kind === 146 || + node.parent.parent.kind === 148) { emitTypeOfVariableDeclarationFromTypeLiteral(node); } else if (!(node.parent.flags & 32)) { @@ -20491,22 +21892,22 @@ var ts; } function getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccesibilityResult) { switch (node.parent.kind) { - case 136: + case 137: return symbolAccesibilityResult.errorModuleName ? symbolAccesibilityResult.accessibility === 2 ? ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1; - case 140: + case 141: return symbolAccesibilityResult.errorModuleName ? ts.Diagnostics.Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1; - case 139: + case 140: return symbolAccesibilityResult.errorModuleName ? ts.Diagnostics.Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1; + case 136: case 135: - case 134: if (node.parent.flags & 128) { return symbolAccesibilityResult.errorModuleName ? symbolAccesibilityResult.accessibility === 2 ? @@ -20514,7 +21915,7 @@ var ts; ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1; } - else if (node.parent.parent.kind === 202) { + else if (node.parent.parent.kind === 204) { return symbolAccesibilityResult.errorModuleName ? symbolAccesibilityResult.accessibility === 2 ? ts.Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : @@ -20526,7 +21927,7 @@ var ts; ts.Diagnostics.Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1; } - case 201: + case 203: return symbolAccesibilityResult.errorModuleName ? symbolAccesibilityResult.accessibility === 2 ? ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : @@ -20537,12 +21938,12 @@ var ts; } } function emitBindingPattern(bindingPattern) { - if (bindingPattern.kind === 151) { + if (bindingPattern.kind === 153) { write("{"); emitCommaList(bindingPattern.elements, emitBindingElement); write("}"); } - else if (bindingPattern.kind === 152) { + else if (bindingPattern.kind === 154) { write("["); var elements = bindingPattern.elements; emitCommaList(elements, emitBindingElement); @@ -20561,10 +21962,10 @@ var ts; typeName: bindingElement.name } : undefined; } - if (bindingElement.kind === 176) { + if (bindingElement.kind === 178) { write(" "); } - else if (bindingElement.kind === 153) { + else if (bindingElement.kind === 155) { if (bindingElement.propertyName) { writeTextOfNode(currentSourceFile, bindingElement.propertyName); write(": "); @@ -20587,39 +21988,39 @@ var ts; } function emitNode(node) { switch (node.kind) { - case 201: - case 206: - case 209: case 203: - case 202: - case 204: + case 208: + case 211: case 205: + case 204: + case 206: + case 207: return emitModuleElement(node, isModuleElementVisible(node)); - case 181: + case 183: return emitModuleElement(node, isVariableStatementVisible(node)); - case 210: + case 212: return emitModuleElement(node, !node.importClause); - case 216: + case 218: return emitExportDeclaration(node); + case 137: case 136: case 135: - case 134: return writeFunctionDeclaration(node); - case 140: - case 139: case 141: + case 140: + case 142: return emitSignatureDeclarationWithJsDocComments(node); - case 137: case 138: + case 139: return emitAccessorDeclaration(node); + case 134: case 133: - case 132: return emitPropertyDeclaration(node); - case 227: + case 229: return emitEnumMemberDeclaration(node); - case 215: + case 217: return emitExportAssignment(node); - case 228: + case 230: return emitSourceFile(node); } } @@ -20665,7 +22066,7 @@ var ts; } ts.isExternalModuleOrDeclarationFile = isExternalModuleOrDeclarationFile; function emitFiles(resolver, host, targetSourceFile) { - var extendsHelper = "\nvar __extends = (this && this.__extends) || function (d, b) {\n for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];\n function __() { this.constructor = d; }\n __.prototype = b.prototype;\n d.prototype = new __();\n};"; + var extendsHelper = "\nvar __extends = (this && this.__extends) || function (d, b) {\n for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n};"; var decorateHelper = "\nvar __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") return Reflect.decorate(decorators, target, key, desc);\n switch (arguments.length) {\n case 2: return decorators.reduceRight(function(o, d) { return (d && d(o)) || o; }, target);\n case 3: return decorators.reduceRight(function(o, d) { return (d && d(target, key)), void 0; }, void 0);\n case 4: return decorators.reduceRight(function(o, d) { return (d && d(target, key, o)) || o; }, desc);\n }\n};"; var metadataHelper = "\nvar __metadata = (this && this.__metadata) || function (k, v) {\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(k, v);\n};"; var paramHelper = "\nvar __param = (this && this.__param) || function (paramIndex, decorator) {\n return function (target, key) { decorator(target, key, paramIndex); }\n};"; @@ -20729,7 +22130,6 @@ var ts; var exportFunctionForFile; var generatedNameSet = {}; var nodeToGeneratedName = []; - var blockScopedVariableToGeneratedName; var computedPropertyNamesToGeneratedNames; var extendsEmitted = false; var decorateEmitted = false; @@ -20789,9 +22189,9 @@ var ts; var count = tempFlags & 268435455; tempFlags++; if (count !== 8 && count !== 13) { - var name_15 = count < 26 ? "_" + String.fromCharCode(97 + count) : "_" + (count - 26); - if (isUniqueName(name_15)) { - return name_15; + var name_17 = count < 26 ? "_" + String.fromCharCode(97 + count) : "_" + (count - 26); + if (isUniqueName(name_17)) { + return name_17; } } } @@ -20809,72 +22209,39 @@ var ts; i++; } } - function assignGeneratedName(node, name) { - nodeToGeneratedName[ts.getNodeId(node)] = ts.unescapeIdentifier(name); - } - function generateNameForFunctionOrClassDeclaration(node) { - if (!node.name) { - assignGeneratedName(node, makeUniqueName("default")); - } - } function generateNameForModuleOrEnum(node) { - if (node.name.kind === 65) { - var name_16 = node.name.text; - assignGeneratedName(node, isUniqueLocalName(name_16, node) ? name_16 : makeUniqueName(name_16)); - } + var name = node.name.text; + return isUniqueLocalName(name, node) ? name : makeUniqueName(name); } function generateNameForImportOrExportDeclaration(node) { var expr = ts.getExternalModuleName(node); var baseName = expr.kind === 8 ? ts.escapeIdentifier(ts.makeIdentifierFromModuleName(expr.text)) : "module"; - assignGeneratedName(node, makeUniqueName(baseName)); + return makeUniqueName(baseName); } - function generateNameForImportDeclaration(node) { - if (node.importClause) { - generateNameForImportOrExportDeclaration(node); - } - } - function generateNameForExportDeclaration(node) { - if (node.moduleSpecifier) { - generateNameForImportOrExportDeclaration(node); - } - } - function generateNameForExportAssignment(node) { - if (node.expression && node.expression.kind !== 65) { - assignGeneratedName(node, makeUniqueName("default")); - } + function generateNameForExportDefault() { + return makeUniqueName("default"); } function generateNameForNode(node) { switch (node.kind) { - case 201: - case 202: - case 175: - generateNameForFunctionOrClassDeclaration(node); - break; - case 206: - generateNameForModuleOrEnum(node); - generateNameForNode(node.body); - break; - case 205: - generateNameForModuleOrEnum(node); - break; - case 210: - generateNameForImportDeclaration(node); - break; - case 216: - generateNameForExportDeclaration(node); - break; - case 215: - generateNameForExportAssignment(node); - break; + case 65: + return makeUniqueName(node.text); + case 208: + case 207: + return generateNameForModuleOrEnum(node); + case 212: + case 218: + return generateNameForImportOrExportDeclaration(node); + case 203: + case 204: + case 177: + case 217: + return generateNameForExportDefault(); } } function getGeneratedNameForNode(node) { - var nodeId = ts.getNodeId(node); - if (!nodeToGeneratedName[nodeId]) { - generateNameForNode(node); - } - return nodeToGeneratedName[nodeId]; + var id = ts.getNodeId(node); + return nodeToGeneratedName[id] || (nodeToGeneratedName[id] = ts.unescapeIdentifier(generateNameForNode(node))); } function initializeEmitterWithSourceMaps() { var sourceMapDir; @@ -20898,7 +22265,7 @@ var ts; return; } var prevEncodedEmittedColumn = lastEncodedSourceMapSpan.emittedColumn; - if (lastEncodedSourceMapSpan.emittedLine == lastRecordedSourceMapSpan.emittedLine) { + if (lastEncodedSourceMapSpan.emittedLine === lastRecordedSourceMapSpan.emittedLine) { if (sourceMapData.sourceMapMappings) { sourceMapData.sourceMapMappings += ","; } @@ -20951,8 +22318,8 @@ var ts; var emittedLine = writer.getLine(); var emittedColumn = writer.getColumn(); if (!lastRecordedSourceMapSpan || - lastRecordedSourceMapSpan.emittedLine != emittedLine || - lastRecordedSourceMapSpan.emittedColumn != emittedColumn || + lastRecordedSourceMapSpan.emittedLine !== emittedLine || + lastRecordedSourceMapSpan.emittedColumn !== emittedColumn || (lastRecordedSourceMapSpan.sourceIndex === sourceMapSourceIndex && (lastRecordedSourceMapSpan.sourceLine > sourceLinePos.line || (lastRecordedSourceMapSpan.sourceLine === sourceLinePos.line && lastRecordedSourceMapSpan.sourceColumn > sourceLinePos.character)))) { @@ -21006,8 +22373,8 @@ var ts; if (scopeName) { var parentIndex = getSourceMapNameIndex(); if (parentIndex !== -1) { - var name_17 = node.name; - if (!name_17 || name_17.kind !== 128) { + var name_18 = node.name; + if (!name_18 || name_18.kind !== 129) { scopeName = "." + scopeName; } scopeName = sourceMapData.sourceMapNames[parentIndex] + scopeName; @@ -21024,19 +22391,19 @@ var ts; if (scopeName) { recordScopeNameStart(scopeName); } - else if (node.kind === 201 || - node.kind === 163 || + else if (node.kind === 203 || + node.kind === 165 || + node.kind === 136 || node.kind === 135 || - node.kind === 134 || - node.kind === 137 || node.kind === 138 || - node.kind === 206 || - node.kind === 202 || - node.kind === 205) { + node.kind === 139 || + node.kind === 208 || + node.kind === 204 || + node.kind === 207) { if (node.name) { - var name_18 = node.name; - scopeName = name_18.kind === 128 - ? ts.getTextOfNode(name_18) + var name_19 = node.name; + scopeName = name_19.kind === 129 + ? ts.getTextOfNode(name_19) : node.name.text; } recordScopeNameStart(scopeName); @@ -21129,19 +22496,19 @@ var ts; else { sourceMapDir = ts.getDirectoryPath(ts.normalizePath(jsFilePath)); } - function emitNodeWithSourceMap(node, allowGeneratedIdentifiers) { + function emitNodeWithSourceMap(node) { if (node) { if (ts.nodeIsSynthesized(node)) { - return emitNodeWithoutSourceMap(node, false); + return emitNodeWithoutSourceMap(node); } - if (node.kind != 228) { + if (node.kind !== 230) { recordEmitNodeStartSpan(node); - emitNodeWithoutSourceMap(node, allowGeneratedIdentifiers); + emitNodeWithoutSourceMap(node); recordEmitNodeEndSpan(node); } else { recordNewSourceFileStart(node); - emitNodeWithoutSourceMap(node, false); + emitNodeWithoutSourceMap(node); } } } @@ -21379,10 +22746,10 @@ var ts; emitParenthesizedIf(node.tag, needsParenthesisForPropertyAccessOrInvocation(node.tag)); write("("); emit(tempVariable); - if (node.template.kind === 172) { + if (node.template.kind === 174) { ts.forEach(node.template.templateSpans, function (templateSpan) { write(", "); - var needsParens = templateSpan.expression.kind === 170 + var needsParens = templateSpan.expression.kind === 172 && templateSpan.expression.operatorToken.kind === 23; emitParenthesizedIf(templateSpan.expression, needsParens); }); @@ -21406,7 +22773,7 @@ var ts; } for (var i = 0, n = node.templateSpans.length; i < n; i++) { var templateSpan = node.templateSpans[i]; - var needsParens = templateSpan.expression.kind !== 162 + var needsParens = templateSpan.expression.kind !== 164 && comparePrecedenceToBinaryPlus(templateSpan.expression) !== 1; if (i > 0 || headEmitted) { write(" + "); @@ -21439,11 +22806,11 @@ var ts; } function templateNeedsParens(template, parent) { switch (parent.kind) { - case 158: - case 159: - return parent.expression === template; case 160: + case 161: + return parent.expression === template; case 162: + case 164: return false; default: return comparePrecedenceToBinaryPlus(parent) !== -1; @@ -21451,7 +22818,7 @@ var ts; } function comparePrecedenceToBinaryPlus(expression) { switch (expression.kind) { - case 170: + case 172: switch (expression.operatorToken.kind) { case 35: case 36: @@ -21463,8 +22830,8 @@ var ts; default: return -1; } + case 175: case 173: - case 171: return -1; default: return 1; @@ -21476,11 +22843,11 @@ var ts; emit(span.literal); } function emitExpressionForPropertyName(node) { - ts.Debug.assert(node.kind !== 153); + ts.Debug.assert(node.kind !== 155); if (node.kind === 8) { emitLiteral(node); } - else if (node.kind === 128) { + else if (node.kind === 129) { if (ts.nodeIsDecorated(node.parent)) { if (!computedPropertyNamesToGeneratedNames) { computedPropertyNamesToGeneratedNames = []; @@ -21508,75 +22875,122 @@ var ts; write("\""); } } - function isNotExpressionIdentifier(node) { + function isExpressionIdentifier(node) { var parent = node.parent; switch (parent.kind) { - case 130: - case 199: - case 153: - case 133: + case 156: + case 172: + case 160: + case 223: + case 129: + case 173: case 132: - case 225: - case 226: + case 167: + case 187: + case 159: + case 217: + case 185: + case 179: + case 189: + case 190: + case 191: + case 186: + case 161: + case 164: + case 171: + case 170: + case 194: + case 228: + case 176: + case 196: + case 162: + case 180: + case 198: + case 163: + case 168: + case 169: + case 188: + case 195: + case 175: + return true; + case 155: + case 229: + case 131: case 227: - case 135: case 134: case 201: - case 137: - case 138: - case 163: - case 202: - case 203: - case 205: - case 206: - case 209: + return parent.initializer === node; + case 158: + return parent.expression === node; + case 166: + case 165: + return parent.body === node; case 211: - case 212: - return parent.name === node; - case 214: - case 218: - return parent.name === node || parent.propertyName === node; - case 191: - case 190: - case 215: - return false; - case 195: - return node.parent.label === node; + return parent.moduleReference === node; + case 128: + return parent.left === node; } + return false; } function emitExpressionIdentifier(node) { - var substitution = resolver.getExpressionNameSubstitution(node, getGeneratedNameForNode); - if (substitution) { - write(substitution); + var container = resolver.getReferencedExportContainer(node); + if (container) { + if (container.kind === 230) { + if (languageVersion < 2 && compilerOptions.module !== 4) { + write("exports."); + } + } + else { + write(getGeneratedNameForNode(container)); + write("."); + } } - else { - writeTextOfNode(currentSourceFile, node); - } - } - function getGeneratedNameForIdentifier(node) { - if (ts.nodeIsSynthesized(node) || !blockScopedVariableToGeneratedName) { - return undefined; - } - var variableId = resolver.getBlockScopedVariableId(node); - if (variableId === undefined) { - return undefined; - } - return blockScopedVariableToGeneratedName[variableId]; - } - function emitIdentifier(node, allowGeneratedIdentifiers) { - if (allowGeneratedIdentifiers) { - var generatedName = getGeneratedNameForIdentifier(node); - if (generatedName) { - write(generatedName); + else if (languageVersion < 2) { + var declaration = resolver.getReferencedImportDeclaration(node); + if (declaration) { + if (declaration.kind === 213) { + write(getGeneratedNameForNode(declaration.parent)); + write(languageVersion === 0 ? '["default"]' : ".default"); + return; + } + else if (declaration.kind === 216) { + write(getGeneratedNameForNode(declaration.parent.parent.parent)); + write("."); + writeTextOfNode(currentSourceFile, declaration.propertyName || declaration.name); + return; + } + } + declaration = resolver.getReferencedNestedRedeclaration(node); + if (declaration) { + write(getGeneratedNameForNode(declaration.name)); return; } } + writeTextOfNode(currentSourceFile, node); + } + function isNameOfNestedRedeclaration(node) { + if (languageVersion < 2) { + var parent_7 = node.parent; + switch (parent_7.kind) { + case 155: + case 204: + case 207: + case 201: + return parent_7.name === node && resolver.isNestedRedeclaration(parent_7); + } + } + return false; + } + function emitIdentifier(node) { if (!node.parent) { write(node.text); } - else if (!isNotExpressionIdentifier(node)) { + else if (isExpressionIdentifier(node)) { emitExpressionIdentifier(node); } + else if (isNameOfNestedRedeclaration(node)) { + write(getGeneratedNameForNode(node)); + } else { writeTextOfNode(currentSourceFile, node); } @@ -21617,7 +23031,7 @@ var ts; } function emitBindingElement(node) { if (node.propertyName) { - emit(node.propertyName, false); + emit(node.propertyName); write(": "); } if (node.dotDotDotToken) { @@ -21648,38 +23062,38 @@ var ts; function needsParenthesisForPropertyAccessOrInvocation(node) { switch (node.kind) { case 65: - case 154: case 156: - case 157: case 158: - case 162: + case 159: + case 160: + case 164: return false; } return true; } - function emitListWithSpread(elements, alwaysCopy, multiLine, trailingComma) { + function emitListWithSpread(elements, needsUniqueCopy, multiLine, trailingComma, useConcat) { var pos = 0; var group = 0; var length = elements.length; while (pos < length) { - if (group === 1) { + if (group === 1 && useConcat) { write(".concat("); } - else if (group > 1) { + else if (group > 0) { write(", "); } var e = elements[pos]; - if (e.kind === 174) { + if (e.kind === 176) { e = e.expression; emitParenthesizedIf(e, group === 0 && needsParenthesisForPropertyAccessOrInvocation(e)); pos++; - if (pos === length && group === 0 && alwaysCopy && e.kind !== 154) { + if (pos === length && group === 0 && needsUniqueCopy && e.kind !== 156) { write(".slice()"); } } else { var i = pos; - while (i < length && elements[i].kind !== 174) { + while (i < length && elements[i].kind !== 176) { i++; } write("["); @@ -21696,11 +23110,13 @@ var ts; group++; } if (group > 1) { - write(")"); + if (useConcat) { + write(")"); + } } } function isSpreadElementExpression(node) { - return node.kind === 174; + return node.kind === 176; } function emitArrayLiteral(node) { var elements = node.elements; @@ -21713,7 +23129,7 @@ var ts; write("]"); } else { - emitListWithSpread(elements, true, (node.flags & 512) !== 0, elements.hasTrailingComma); + emitListWithSpread(elements, true, (node.flags & 512) !== 0, elements.hasTrailingComma, true); } } function emitObjectLiteralBody(node, numElements) { @@ -21761,7 +23177,7 @@ var ts; writeComma(); var property = properties[i]; emitStart(property); - if (property.kind === 137 || property.kind === 138) { + if (property.kind === 138 || property.kind === 139) { var accessors = ts.getAllAccessorDeclarations(node.properties, property); if (property !== accessors.firstAccessor) { continue; @@ -21812,13 +23228,13 @@ var ts; emitMemberAccessForPropertyName(property.name); emitEnd(property.name); write(" = "); - if (property.kind === 225) { + if (property.kind === 227) { emit(property.initializer); } - else if (property.kind === 226) { + else if (property.kind === 228) { emitExpressionIdentifier(property.name); } - else if (property.kind === 135) { + else if (property.kind === 136) { emitFunctionDeclaration(property); } else { @@ -21850,7 +23266,7 @@ var ts; var numProperties = properties.length; var numInitialNonComputedProperties = numProperties; for (var i = 0, n = properties.length; i < n; i++) { - if (properties[i].name.kind === 128) { + if (properties[i].name.kind === 129) { numInitialNonComputedProperties = i; break; } @@ -21864,30 +23280,35 @@ var ts; emitObjectLiteralBody(node, properties.length); } function createBinaryExpression(left, operator, right, startsOnNewLine) { - var result = ts.createSynthesizedNode(170, startsOnNewLine); + var result = ts.createSynthesizedNode(172, startsOnNewLine); result.operatorToken = ts.createSynthesizedNode(operator); result.left = left; result.right = right; return result; } function createPropertyAccessExpression(expression, name) { - var result = ts.createSynthesizedNode(156); + var result = ts.createSynthesizedNode(158); result.expression = parenthesizeForAccess(expression); result.dotToken = ts.createSynthesizedNode(20); result.name = name; return result; } function createElementAccessExpression(expression, argumentExpression) { - var result = ts.createSynthesizedNode(157); + var result = ts.createSynthesizedNode(159); result.expression = parenthesizeForAccess(expression); result.argumentExpression = argumentExpression; return result; } function parenthesizeForAccess(expr) { - if (ts.isLeftHandSideExpression(expr) && expr.kind !== 159 && expr.kind !== 7) { + while (expr.kind === 163) { + expr = expr.expression; + } + if (ts.isLeftHandSideExpression(expr) && + expr.kind !== 161 && + expr.kind !== 7) { return expr; } - var node = ts.createSynthesizedNode(162); + var node = ts.createSynthesizedNode(164); node.expression = expr; return node; } @@ -21900,43 +23321,37 @@ var ts; if (languageVersion >= 2 && node.asteriskToken) { write("*"); } - emit(node.name, false); + emit(node.name); if (languageVersion < 2) { write(": function "); } emitSignatureAndBody(node); } function emitPropertyAssignment(node) { - emit(node.name, false); + emit(node.name); write(": "); emit(node.initializer); } + function isNamespaceExportReference(node) { + var container = resolver.getReferencedExportContainer(node); + return container && container.kind !== 230; + } function emitShorthandPropertyAssignment(node) { - emit(node.name, false); - if (languageVersion < 2) { + writeTextOfNode(currentSourceFile, node.name); + if (languageVersion < 2 || isNamespaceExportReference(node.name)) { write(": "); - var generatedName = getGeneratedNameForIdentifier(node.name); - if (generatedName) { - write(generatedName); - } - else { - emitExpressionIdentifier(node.name); - } - } - else if (resolver.getExpressionNameSubstitution(node.name, getGeneratedNameForNode)) { - write(": "); - emitExpressionIdentifier(node.name); + emit(node.name); } } function tryEmitConstantValue(node) { - if (compilerOptions.separateCompilation) { + if (compilerOptions.isolatedModules) { return false; } var constantValue = resolver.getConstantValue(node); if (constantValue !== undefined) { write(constantValue.toString()); if (!compilerOptions.removeComments) { - var propertyName = node.kind === 156 ? ts.declarationNameToString(node.name) : ts.getTextOfNode(node.argumentExpression); + var propertyName = node.kind === 158 ? ts.declarationNameToString(node.name) : ts.getTextOfNode(node.argumentExpression); write(" /* " + propertyName + " */"); } return true; @@ -21966,7 +23381,7 @@ var ts; var indentedBeforeDot = indentIfOnDifferentLines(node, node.expression, node.dotToken); write("."); var indentedAfterDot = indentIfOnDifferentLines(node, node.dotToken, node.name); - emit(node.name, false); + emit(node.name); decreaseIndentIf(indentedBeforeDot, indentedAfterDot); } function emitQualifiedName(node) { @@ -21984,10 +23399,10 @@ var ts; write("]"); } function hasSpreadElement(elements) { - return ts.forEach(elements, function (e) { return e.kind === 174; }); + return ts.forEach(elements, function (e) { return e.kind === 176; }); } function skipParentheses(node) { - while (node.kind === 162 || node.kind === 161) { + while (node.kind === 164 || node.kind === 163) { node = node.expression; } return node; @@ -22008,12 +23423,12 @@ var ts; function emitCallWithSpread(node) { var target; var expr = skipParentheses(node.expression); - if (expr.kind === 156) { + if (expr.kind === 158) { target = emitCallTarget(expr.expression); write("."); emit(expr.name); } - else if (expr.kind === 157) { + else if (expr.kind === 159) { target = emitCallTarget(expr.expression); write("["); emit(expr.argumentExpression); @@ -22039,7 +23454,7 @@ var ts; write("void 0"); } write(", "); - emitListWithSpread(node.arguments, false, false, false); + emitListWithSpread(node.arguments, false, false, false, true); write(")"); } function emitCallExpression(node) { @@ -22054,7 +23469,7 @@ var ts; } else { emit(node.expression); - superCall = node.expression.kind === 156 && node.expression.expression.kind === 91; + superCall = node.expression.kind === 158 && node.expression.expression.kind === 91; } if (superCall && languageVersion < 2) { write(".call("); @@ -22073,11 +23488,25 @@ var ts; } function emitNewExpression(node) { write("new "); - emit(node.expression); - if (node.arguments) { + if (languageVersion === 1 && + node.arguments && + hasSpreadElement(node.arguments)) { write("("); - emitCommaList(node.arguments); - write(")"); + var target = emitCallTarget(node.expression); + write(".bind.apply("); + emit(target); + write(", [void 0].concat("); + emitListWithSpread(node.arguments, false, false, false, false); + write(")))"); + write("()"); + } + else { + emit(node.expression); + if (node.arguments) { + write("("); + emitCommaList(node.arguments); + write(")"); + } } } function emitTaggedTemplateExpression(node) { @@ -22091,20 +23520,20 @@ var ts; } } function emitParenExpression(node) { - if (!node.parent || node.parent.kind !== 164) { - if (node.expression.kind === 161) { + if (!ts.nodeIsSynthesized(node) && node.parent.kind !== 166) { + if (node.expression.kind === 163) { var operand = node.expression.expression; - while (operand.kind == 161) { + while (operand.kind === 163) { operand = operand.expression; } - if (operand.kind !== 168 && - operand.kind !== 167 && - operand.kind !== 166 && - operand.kind !== 165 && + if (operand.kind !== 170 && operand.kind !== 169 && - operand.kind !== 159 && - !(operand.kind === 158 && node.parent.kind === 159) && - !(operand.kind === 163 && node.parent.kind === 158)) { + operand.kind !== 168 && + operand.kind !== 167 && + operand.kind !== 171 && + operand.kind !== 161 && + !(operand.kind === 160 && node.parent.kind === 161) && + !(operand.kind === 165 && node.parent.kind === 160)) { emit(operand); return; } @@ -22133,7 +23562,7 @@ var ts; if (!isCurrentFileSystemExternalModule() || node.kind !== 65 || ts.nodeIsSynthesized(node)) { return false; } - var isVariableDeclarationOrBindingElement = node.parent && (node.parent.kind === 199 || node.parent.kind === 153); + var isVariableDeclarationOrBindingElement = node.parent && (node.parent.kind === 201 || node.parent.kind === 155); var targetDeclaration = isVariableDeclarationOrBindingElement ? node.parent : resolver.getReferencedValueDeclaration(node); @@ -22147,7 +23576,7 @@ var ts; write("\", "); } write(ts.tokenToString(node.operator)); - if (node.operand.kind === 168) { + if (node.operand.kind === 170) { var operand = node.operand; if (node.operator === 33 && (operand.operator === 33 || operand.operator === 38)) { write(" "); @@ -22190,10 +23619,10 @@ var ts; } var current = node; while (current) { - if (current.kind === 228) { + if (current.kind === 230) { return !isExported || ((ts.getCombinedNodeFlags(node) & 1) !== 0); } - else if (ts.isFunctionLike(current) || current.kind === 207) { + else if (ts.isFunctionLike(current) || current.kind === 209) { return false; } else { @@ -22203,8 +23632,8 @@ var ts; } function emitBinaryExpression(node) { if (languageVersion < 2 && node.operatorToken.kind === 53 && - (node.left.kind === 155 || node.left.kind === 154)) { - emitDestructuring(node, node.parent.kind === 183); + (node.left.kind === 157 || node.left.kind === 156)) { + emitDestructuring(node, node.parent.kind === 185); } else { var exportChanged = node.operatorToken.kind >= 53 && @@ -22251,7 +23680,7 @@ var ts; } } function isSingleLineEmptyBlock(node) { - if (node && node.kind === 180) { + if (node && node.kind === 182) { var block = node; return block.statements.length === 0 && nodeEndIsOnSameLineAsNodeStart(block, block); } @@ -22266,12 +23695,12 @@ var ts; emitToken(14, node.pos); increaseIndent(); scopeEmitStart(node.parent); - if (node.kind === 207) { - ts.Debug.assert(node.parent.kind === 206); + if (node.kind === 209) { + ts.Debug.assert(node.parent.kind === 208); emitCaptureThisForNodeIfNecessary(node.parent); } emitLines(node.statements); - if (node.kind === 207) { + if (node.kind === 209) { emitTempDeclarations(true); } decreaseIndent(); @@ -22280,7 +23709,7 @@ var ts; scopeEmitEnd(); } function emitEmbeddedStatement(node) { - if (node.kind === 180) { + if (node.kind === 182) { write(" "); emit(node); } @@ -22292,7 +23721,7 @@ var ts; } } function emitExpressionStatement(node) { - emitParenthesizedIf(node.expression, node.expression.kind === 164); + emitParenthesizedIf(node.expression, node.expression.kind === 166); write(";"); } function emitIfStatement(node) { @@ -22305,7 +23734,7 @@ var ts; if (node.elseStatement) { writeLine(); emitToken(76, node.thenStatement.end); - if (node.elseStatement.kind === 184) { + if (node.elseStatement.kind === 186) { write(" "); emit(node.elseStatement); } @@ -22317,7 +23746,7 @@ var ts; function emitDoStatement(node) { write("do"); emitEmbeddedStatement(node.statement); - if (node.statement.kind === 180) { + if (node.statement.kind === 182) { write(" "); } else { @@ -22386,7 +23815,7 @@ var ts; var endPos = emitToken(82, node.pos); write(" "); endPos = emitToken(16, endPos); - if (node.initializer && node.initializer.kind === 200) { + if (node.initializer && node.initializer.kind === 202) { var variableDeclarationList = node.initializer; var startIsEmitted = tryEmitStartOfVariableDeclarationList(variableDeclarationList, endPos); if (startIsEmitted) { @@ -22407,13 +23836,13 @@ var ts; emitEmbeddedStatement(node.statement); } function emitForInOrForOfStatement(node) { - if (languageVersion < 2 && node.kind === 189) { + if (languageVersion < 2 && node.kind === 191) { return emitDownLevelForOfStatement(node); } var endPos = emitToken(82, node.pos); write(" "); endPos = emitToken(16, endPos); - if (node.initializer.kind === 200) { + if (node.initializer.kind === 202) { var variableDeclarationList = node.initializer; if (variableDeclarationList.declarations.length >= 1) { tryEmitStartOfVariableDeclarationList(variableDeclarationList, endPos); @@ -22423,7 +23852,7 @@ var ts; else { emit(node.initializer); } - if (node.kind === 188) { + if (node.kind === 190) { write(" in "); } else { @@ -22491,7 +23920,7 @@ var ts; increaseIndent(); var rhsIterationValue = createElementAccessExpression(rhsReference, counter); emitStart(node.initializer); - if (node.initializer.kind === 200) { + if (node.initializer.kind === 202) { write("var "); var variableDeclarationList = node.initializer; if (variableDeclarationList.declarations.length > 0) { @@ -22513,7 +23942,7 @@ var ts; } else { var assignmentExpression = createBinaryExpression(node.initializer, 53, rhsIterationValue, false); - if (node.initializer.kind === 154 || node.initializer.kind === 155) { + if (node.initializer.kind === 156 || node.initializer.kind === 157) { emitDestructuring(assignmentExpression, true, undefined); } else { @@ -22522,7 +23951,7 @@ var ts; } emitEnd(node.initializer); write(";"); - if (node.statement.kind === 180) { + if (node.statement.kind === 182) { emitLines(node.statement.statements); } else { @@ -22534,7 +23963,7 @@ var ts; write("}"); } function emitBreakOrContinueStatement(node) { - emitToken(node.kind === 191 ? 66 : 71, node.pos); + emitToken(node.kind === 193 ? 66 : 71, node.pos); emitOptional(" ", node.label); write(";"); } @@ -22579,7 +24008,7 @@ var ts; ts.getLineOfLocalPosition(currentSourceFile, ts.skipTrivia(currentSourceFile.text, node2.pos)); } function emitCaseOrDefaultClause(node) { - if (node.kind === 221) { + if (node.kind === 223) { write("case "); emit(node.expression); write(":"); @@ -22634,7 +24063,7 @@ var ts; function getContainingModule(node) { do { node = node.parent; - } while (node && node.kind !== 206); + } while (node && node.kind !== 208); return node; } function emitContainingModuleName(node) { @@ -22659,7 +24088,7 @@ var ts; function createVoidZero() { var zero = ts.createSynthesizedNode(7); zero.text = "0"; - var result = ts.createSynthesizedNode(167); + var result = ts.createSynthesizedNode(169); result.expression = zero; return result; } @@ -22728,15 +24157,15 @@ var ts; function emitDestructuring(root, isAssignmentExpressionStatement, value) { var emitCount = 0; var canDefineTempVariablesInPlace = false; - if (root.kind === 199) { + if (root.kind === 201) { var isExported = ts.getCombinedNodeFlags(root) & 1; var isSourceLevelForSystemModuleKind = shouldHoistDeclarationInSystemJsModule(root); canDefineTempVariablesInPlace = !isExported && !isSourceLevelForSystemModuleKind; } - else if (root.kind === 130) { + else if (root.kind === 131) { canDefineTempVariablesInPlace = true; } - if (root.kind === 170) { + if (root.kind === 172) { emitAssignmentExpression(root); } else { @@ -22747,8 +24176,7 @@ var ts; if (emitCount++) { write(", "); } - renameNonTopLevelLetAndConst(name); - var isVariableDeclarationOrBindingElement = name.parent && (name.parent.kind === 199 || name.parent.kind === 153); + var isVariableDeclarationOrBindingElement = name.parent && (name.parent.kind === 201 || name.parent.kind === 155); var exportChanged = isNameOfExportedSourceLevelDeclarationInSystemExternalModule(name); if (exportChanged) { write(exportFunctionForFile + "(\""); @@ -22780,14 +24208,14 @@ var ts; } function createDefaultValueCheck(value, defaultValue) { value = ensureIdentifier(value); - var equals = ts.createSynthesizedNode(170); + var equals = ts.createSynthesizedNode(172); equals.left = value; equals.operatorToken = ts.createSynthesizedNode(30); equals.right = createVoidZero(); return createConditionalExpression(equals, defaultValue, value); } function createConditionalExpression(condition, whenTrue, whenFalse) { - var cond = ts.createSynthesizedNode(171); + var cond = ts.createSynthesizedNode(173); cond.condition = condition; cond.questionToken = ts.createSynthesizedNode(50); cond.whenTrue = whenTrue; @@ -22801,13 +24229,15 @@ var ts; return node; } function createPropertyAccessForDestructuringProperty(object, propName) { - if (propName.kind !== 65) { - return createElementAccessExpression(object, propName); + var syntheticName = ts.createSynthesizedNode(propName.kind); + syntheticName.text = propName.text; + if (syntheticName.kind !== 65) { + return createElementAccessExpression(object, syntheticName); } - return createPropertyAccessExpression(object, propName); + return createPropertyAccessExpression(object, syntheticName); } function createSliceCall(value, sliceIndex) { - var call = ts.createSynthesizedNode(158); + var call = ts.createSynthesizedNode(160); var sliceIdentifier = ts.createSynthesizedNode(65); sliceIdentifier.text = "slice"; call.expression = createPropertyAccessExpression(value, sliceIdentifier); @@ -22822,8 +24252,8 @@ var ts; } for (var _a = 0; _a < properties.length; _a++) { var p = properties[_a]; - if (p.kind === 225 || p.kind === 226) { - var propName = (p.name); + if (p.kind === 227 || p.kind === 228) { + var propName = p.name; emitDestructuringAssignment(p.initializer || propName, createPropertyAccessForDestructuringProperty(value, propName)); } } @@ -22835,8 +24265,8 @@ var ts; } for (var i = 0; i < elements.length; i++) { var e = elements[i]; - if (e.kind !== 176) { - if (e.kind !== 174) { + if (e.kind !== 178) { + if (e.kind !== 176) { emitDestructuringAssignment(e, createElementAccessExpression(value, createNumericLiteral(i))); } else if (i === elements.length - 1) { @@ -22846,14 +24276,14 @@ var ts; } } function emitDestructuringAssignment(target, value) { - if (target.kind === 170 && target.operatorToken.kind === 53) { + if (target.kind === 172 && target.operatorToken.kind === 53) { value = createDefaultValueCheck(value, target.right); target = target.left; } - if (target.kind === 155) { + if (target.kind === 157) { emitObjectLiteralAssignment(target, value); } - else if (target.kind === 154) { + else if (target.kind === 156) { emitArrayLiteralAssignment(target, value); } else { @@ -22867,14 +24297,14 @@ var ts; emitDestructuringAssignment(target, value); } else { - if (root.parent.kind !== 162) { + if (root.parent.kind !== 164) { write("("); } value = ensureIdentifier(value); emitDestructuringAssignment(target, value); write(", "); emit(value); - if (root.parent.kind !== 162) { + if (root.parent.kind !== 164) { write(")"); } } @@ -22894,11 +24324,11 @@ var ts; } for (var i = 0; i < elements.length; i++) { var element = elements[i]; - if (pattern.kind === 151) { + if (pattern.kind === 153) { var propName = element.propertyName || element.name; emitBindingElement(element, createPropertyAccessForDestructuringProperty(value, propName)); } - else if (element.kind !== 176) { + else if (element.kind !== 178) { if (!element.dotDotDotToken) { emitBindingElement(element, createElementAccessExpression(value, createNumericLiteral(i))); } @@ -22924,14 +24354,13 @@ var ts; } } else { - renameNonTopLevelLetAndConst(node.name); var initializer = node.initializer; if (!initializer && languageVersion < 2) { var isUninitializedLet = (resolver.getNodeCheckFlags(node) & 256) && (getCombinedFlagsForIdentifier(node.name) & 4096); if (isUninitializedLet && - node.parent.parent.kind !== 188 && - node.parent.parent.kind !== 189) { + node.parent.parent.kind !== 190 && + node.parent.parent.kind !== 191) { initializer = createVoidZero(); } } @@ -22949,7 +24378,7 @@ var ts; } } function emitExportVariableAssignments(node) { - if (node.kind === 176) { + if (node.kind === 178) { return; } var name = node.name; @@ -22961,48 +24390,15 @@ var ts; } } function getCombinedFlagsForIdentifier(node) { - if (!node.parent || (node.parent.kind !== 199 && node.parent.kind !== 153)) { + if (!node.parent || (node.parent.kind !== 201 && node.parent.kind !== 155)) { return 0; } return ts.getCombinedNodeFlags(node.parent); } - function renameNonTopLevelLetAndConst(node) { - if (languageVersion >= 2 || - ts.nodeIsSynthesized(node) || - node.kind !== 65 || - (node.parent.kind !== 199 && node.parent.kind !== 153)) { - return; - } - var combinedFlags = getCombinedFlagsForIdentifier(node); - if (((combinedFlags & 12288) === 0) || combinedFlags & 1) { - return; - } - var list = ts.getAncestor(node, 200); - if (list.parent.kind === 181) { - var isSourceFileLevelBinding = list.parent.parent.kind === 228; - var isModuleLevelBinding = list.parent.parent.kind === 207; - var isFunctionLevelBinding = list.parent.parent.kind === 180 && ts.isFunctionLike(list.parent.parent.parent); - if (isSourceFileLevelBinding || isModuleLevelBinding || isFunctionLevelBinding) { - return; - } - } - var blockScopeContainer = ts.getEnclosingBlockScopeContainer(node); - var parent = blockScopeContainer.kind === 228 - ? blockScopeContainer - : blockScopeContainer.parent; - if (resolver.resolvesToSomeValue(parent, node.text)) { - var variableId = resolver.getBlockScopedVariableId(node); - if (!blockScopedVariableToGeneratedName) { - blockScopedVariableToGeneratedName = []; - } - var generatedName = makeUniqueName(node.text); - blockScopedVariableToGeneratedName[variableId] = generatedName; - } - } function isES6ExportedDeclaration(node) { return !!(node.flags & 1) && languageVersion >= 2 && - node.parent.kind === 228; + node.parent.kind === 230; } function emitVariableStatement(node) { var startIsEmitted = false; @@ -23029,15 +24425,30 @@ var ts; ts.forEach(node.declarationList.declarations, emitExportVariableAssignments); } } + function shouldEmitLeadingAndTrailingCommentsForVariableStatement(node) { + if (!(node.flags & 1)) { + return true; + } + if (isES6ExportedDeclaration(node)) { + return true; + } + for (var _a = 0, _b = node.declarationList.declarations; _a < _b.length; _a++) { + var declaration = _b[_a]; + if (declaration.initializer) { + return true; + } + } + return false; + } function emitParameter(node) { if (languageVersion < 2) { if (ts.isBindingPattern(node.name)) { - var name_19 = createTempVariable(0); + var name_20 = createTempVariable(0); if (!tempParameters) { tempParameters = []; } - tempParameters.push(name_19); - emit(name_19); + tempParameters.push(name_20); + emit(name_20); } else { emit(node.name); @@ -23084,7 +24495,7 @@ var ts; } } function emitRestParameter(node) { - if (languageVersion < 2 && ts.hasRestParameters(node)) { + if (languageVersion < 2 && ts.hasRestParameter(node)) { var restIndex = node.parameters.length - 1; var restParam = node.parameters[restIndex]; if (ts.isBindingPattern(restParam.name)) { @@ -23125,12 +24536,12 @@ var ts; } } function emitAccessor(node) { - write(node.kind === 137 ? "get " : "set "); - emit(node.name, false); + write(node.kind === 138 ? "get " : "set "); + emit(node.name); emitSignatureAndBody(node); } function shouldEmitAsArrowFunction(node) { - return node.kind === 164 && languageVersion >= 2; + return node.kind === 166 && languageVersion >= 2; } function emitDeclarationName(node) { if (node.name) { @@ -23141,10 +24552,10 @@ var ts; } } function shouldEmitFunctionName(node) { - if (node.kind === 163) { + if (node.kind === 165) { return !!node.name; } - if (node.kind === 201) { + if (node.kind === 203) { return !!node.name || languageVersion < 2; } } @@ -23152,7 +24563,7 @@ var ts; if (ts.nodeIsMissing(node.body)) { return emitOnlyPinnedOrTripleSlashComments(node); } - if (node.kind !== 135 && node.kind !== 134) { + if (node.kind !== 136 && node.kind !== 135) { emitLeadingComments(node); } if (!shouldEmitAsArrowFunction(node)) { @@ -23172,10 +24583,10 @@ var ts; emitDeclarationName(node); } emitSignatureAndBody(node); - if (languageVersion < 2 && node.kind === 201 && node.parent === currentSourceFile && node.name) { + if (languageVersion < 2 && node.kind === 203 && node.parent === currentSourceFile && node.name) { emitExportMemberAssignments(node.name); } - if (node.kind !== 135 && node.kind !== 134) { + if (node.kind !== 136 && node.kind !== 135) { emitTrailingComments(node); } } @@ -23192,7 +24603,7 @@ var ts; write("("); if (node) { var parameters = node.parameters; - var omitCount = languageVersion < 2 && ts.hasRestParameters(node) ? 1 : 0; + var omitCount = languageVersion < 2 && ts.hasRestParameter(node) ? 1 : 0; emitList(parameters, 0, parameters.length - omitCount, false, false); } write(")"); @@ -23222,7 +24633,7 @@ var ts; if (!node.body) { write(" { }"); } - else if (node.body.kind === 180) { + else if (node.body.kind === 182) { emitBlockFunctionBody(node, node.body); } else { @@ -23247,10 +24658,10 @@ var ts; } write(" "); var current = body; - while (current.kind === 161) { + while (current.kind === 163) { current = current.expression; } - emitParenthesizedIf(body, current.kind === 155); + emitParenthesizedIf(body, current.kind === 157); } function emitDownLevelExpressionFunctionBody(node, body) { write(" {"); @@ -23322,9 +24733,9 @@ var ts; function findInitialSuperCall(ctor) { if (ctor.body) { var statement = ctor.body.statements[0]; - if (statement && statement.kind === 183) { + if (statement && statement.kind === 185) { var expr = statement.expression; - if (expr && expr.kind === 158) { + if (expr && expr.kind === 160) { var func = expr.expression; if (func && func.kind === 91) { return statement; @@ -23355,7 +24766,7 @@ var ts; emitNodeWithoutSourceMap(memberName); write("]"); } - else if (memberName.kind === 128) { + else if (memberName.kind === 129) { emitComputedPropertyName(memberName); } else { @@ -23367,7 +24778,7 @@ var ts; var properties = []; for (var _a = 0, _b = node.members; _a < _b.length; _a++) { var member = _b[_a]; - if (member.kind === 133 && isStatic === ((member.flags & 128) !== 0) && member.initializer) { + if (member.kind === 134 && isStatic === ((member.flags & 128) !== 0) && member.initializer) { properties.push(member); } } @@ -23407,11 +24818,11 @@ var ts; } function emitMemberFunctionsForES5AndLower(node) { ts.forEach(node.members, function (member) { - if (member.kind === 179) { + if (member.kind === 181) { writeLine(); write(";"); } - else if (member.kind === 135 || node.kind === 134) { + else if (member.kind === 136 || node.kind === 135) { if (!member.body) { return emitOnlyPinnedOrTripleSlashComments(member); } @@ -23430,7 +24841,7 @@ var ts; write(";"); emitTrailingComments(member); } - else if (member.kind === 137 || member.kind === 138) { + else if (member.kind === 138 || member.kind === 139) { var accessors = ts.getAllAccessorDeclarations(node.members, member); if (member === accessors.firstAccessor) { writeLine(); @@ -23480,22 +24891,22 @@ var ts; function emitMemberFunctionsForES6AndHigher(node) { for (var _a = 0, _b = node.members; _a < _b.length; _a++) { var member = _b[_a]; - if ((member.kind === 135 || node.kind === 134) && !member.body) { + if ((member.kind === 136 || node.kind === 135) && !member.body) { emitOnlyPinnedOrTripleSlashComments(member); } - else if (member.kind === 135 || - member.kind === 137 || - member.kind === 138) { + else if (member.kind === 136 || + member.kind === 138 || + member.kind === 139) { writeLine(); emitLeadingComments(member); emitStart(member); if (member.flags & 128) { write("static "); } - if (member.kind === 137) { + if (member.kind === 138) { write("get "); } - else if (member.kind === 138) { + else if (member.kind === 139) { write("set "); } if (member.asteriskToken) { @@ -23506,7 +24917,7 @@ var ts; emitEnd(member); emitTrailingComments(member); } - else if (member.kind === 179) { + else if (member.kind === 181) { writeLine(); write(";"); } @@ -23527,10 +24938,10 @@ var ts; function emitConstructorWorker(node, baseTypeElement) { var hasInstancePropertyWithInitializer = false; ts.forEach(node.members, function (member) { - if (member.kind === 136 && !member.body) { + if (member.kind === 137 && !member.body) { emitOnlyPinnedOrTripleSlashComments(member); } - if (member.kind === 133 && member.initializer && (member.flags & 128) === 0) { + if (member.kind === 134 && member.initializer && (member.flags & 128) === 0) { hasInstancePropertyWithInitializer = true; } }); @@ -23630,7 +25041,7 @@ var ts; } function emitClassLikeDeclarationForES6AndHigher(node) { var thisNodeIsDecorated = ts.nodeIsDecorated(node); - if (node.kind === 202) { + if (node.kind === 204) { if (thisNodeIsDecorated) { if (isES6ExportedDeclaration(node) && !(node.flags & 256)) { write("export "); @@ -23647,7 +25058,7 @@ var ts; } } var staticProperties = getInitializedProperties(node, true); - var isClassExpressionWithStaticProperties = staticProperties.length > 0 && node.kind === 175; + var isClassExpressionWithStaticProperties = staticProperties.length > 0 && node.kind === 177; var tempVariable; if (isClassExpressionWithStaticProperties) { tempVariable = createAndRecordTempVariable(0); @@ -23714,7 +25125,7 @@ var ts; } } function emitClassLikeDeclarationBelowES6(node) { - if (node.kind === 202) { + if (node.kind === 204) { if (!shouldHoistDeclarationInSystemJsModule(node)) { write("var "); } @@ -23772,11 +25183,11 @@ var ts; emit(baseTypeNode.expression); } write(")"); - if (node.kind === 202) { + if (node.kind === 204) { write(";"); } emitEnd(node); - if (node.kind === 202) { + if (node.kind === 204) { emitExportMemberAssignment(node); } if (languageVersion < 2 && node.parent === currentSourceFile && node.name) { @@ -23850,13 +25261,13 @@ var ts; } else { decorators = member.decorators; - if (member.kind === 135) { + if (member.kind === 136) { functionLikeMember = member; } } writeLine(); emitStart(member); - if (member.kind !== 133) { + if (member.kind !== 134) { write("Object.defineProperty("); emitStart(member.name); emitClassMemberPrefix(node, member); @@ -23886,7 +25297,7 @@ var ts; write(", "); emitExpressionForPropertyName(member.name); emitEnd(member.name); - if (member.kind !== 133) { + if (member.kind !== 134) { write(", Object.getOwnPropertyDescriptor("); emitStart(member.name); emitClassMemberPrefix(node, member); @@ -23925,26 +25336,26 @@ var ts; } function shouldEmitTypeMetadata(node) { switch (node.kind) { - case 135: - case 137: + case 136: case 138: - case 133: + case 139: + case 134: return true; } return false; } function shouldEmitReturnTypeMetadata(node) { switch (node.kind) { - case 135: + case 136: return true; } return false; } function shouldEmitParamTypesMetadata(node) { switch (node.kind) { - case 202: - case 135: - case 138: + case 204: + case 136: + case 139: return true; } return false; @@ -23953,7 +25364,7 @@ var ts; var argumentsWritten = 0; if (compilerOptions.emitDecoratorMetadata) { if (shouldEmitTypeMetadata(node)) { - var serializedType = resolver.serializeTypeOfNode(node, getGeneratedNameForNode); + var serializedType = resolver.serializeTypeOfNode(node); if (serializedType) { if (writeComma) { write(", "); @@ -23966,7 +25377,7 @@ var ts; } } if (shouldEmitParamTypesMetadata(node)) { - var serializedTypes = resolver.serializeParameterTypesOfNode(node, getGeneratedNameForNode); + var serializedTypes = resolver.serializeParameterTypesOfNode(node); if (serializedTypes) { if (writeComma || argumentsWritten) { write(", "); @@ -23984,7 +25395,7 @@ var ts; } } if (shouldEmitReturnTypeMetadata(node)) { - var serializedType = resolver.serializeReturnTypeOfNode(node, getGeneratedNameForNode); + var serializedType = resolver.serializeReturnTypeOfNode(node); if (serializedType) { if (writeComma || argumentsWritten) { write(", "); @@ -24025,7 +25436,7 @@ var ts; } function shouldEmitEnumDeclaration(node) { var isConstEnum = ts.isConst(node); - return !isConstEnum || compilerOptions.preserveConstEnums || compilerOptions.separateCompilation; + return !isConstEnum || compilerOptions.preserveConstEnums || compilerOptions.isolatedModules; } function emitEnumDeclaration(node) { if (!shouldEmitEnumDeclaration(node)) { @@ -24080,7 +25491,7 @@ var ts; emitDeclarationName(node); write("\", "); emitDeclarationName(node); - write(")"); + write(");"); } emitExportMemberAssignments(node.name); } @@ -24114,13 +25525,13 @@ var ts; } } function getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration) { - if (moduleDeclaration.body.kind === 206) { + if (moduleDeclaration.body.kind === 208) { var recursiveInnerModule = getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration.body); return recursiveInnerModule || moduleDeclaration.body; } } function shouldEmitModuleDeclaration(node) { - return ts.isInstantiatedModule(node, compilerOptions.preserveConstEnums || compilerOptions.separateCompilation); + return ts.isInstantiatedModule(node, compilerOptions.preserveConstEnums || compilerOptions.isolatedModules); } function isModuleMergedWithES6Class(node) { return languageVersion === 2 && !!(resolver.getNodeCheckFlags(node) & 2048); @@ -24149,7 +25560,7 @@ var ts; write(getGeneratedNameForNode(node)); emitEnd(node.name); write(") "); - if (node.body.kind === 207) { + if (node.body.kind === 209) { var saveTempFlags = tempFlags; var saveTempVariables = tempVariables; tempFlags = 0; @@ -24188,7 +25599,7 @@ var ts; emitDeclarationName(node); write("\", "); emitDeclarationName(node); - write(")"); + write(");"); } emitExportMemberAssignments(node.name); } @@ -24206,16 +25617,16 @@ var ts; } } function getNamespaceDeclarationNode(node) { - if (node.kind === 209) { + if (node.kind === 211) { return node; } var importClause = node.importClause; - if (importClause && importClause.namedBindings && importClause.namedBindings.kind === 212) { + if (importClause && importClause.namedBindings && importClause.namedBindings.kind === 214) { return importClause.namedBindings; } } function isDefaultImport(node) { - return node.kind === 210 && node.importClause && !!node.importClause.name; + return node.kind === 212 && node.importClause && !!node.importClause.name; } function emitExportImportAssignments(node) { if (ts.isAliasSymbolDeclaration(node) && resolver.isValueAliasDeclaration(node)) { @@ -24242,7 +25653,7 @@ var ts; if (shouldEmitNamedBindings) { emitLeadingComments(node.importClause.namedBindings); emitStart(node.importClause.namedBindings); - if (node.importClause.namedBindings.kind === 212) { + if (node.importClause.namedBindings.kind === 214) { write("* as "); emit(node.importClause.namedBindings.name); } @@ -24268,7 +25679,7 @@ var ts; } function emitExternalImportDeclaration(node) { if (ts.contains(externalImports, node)) { - var isExportedImport = node.kind === 209 && (node.flags & 1) !== 0; + var isExportedImport = node.kind === 211 && (node.flags & 1) !== 0; var namespaceDeclaration = getNamespaceDeclarationNode(node); if (compilerOptions.module !== 2) { emitLeadingComments(node); @@ -24280,7 +25691,7 @@ var ts; write(" = "); } else { - var isNakedImport = 210 && !node.importClause; + var isNakedImport = 212 && !node.importClause; if (!isNakedImport) { write("var "); write(getGeneratedNameForNode(node)); @@ -24436,8 +25847,8 @@ var ts; write("export default "); var expression = node.expression; emit(expression); - if (expression.kind !== 201 && - expression.kind !== 202) { + if (expression.kind !== 203 && + expression.kind !== 204) { write(";"); } emitEnd(node); @@ -24473,18 +25884,18 @@ var ts; for (var _a = 0, _b = sourceFile.statements; _a < _b.length; _a++) { var node = _b[_a]; switch (node.kind) { - case 210: + case 212: if (!node.importClause || resolver.isReferencedAliasDeclaration(node.importClause, true)) { externalImports.push(node); } break; - case 209: - if (node.moduleReference.kind === 220 && resolver.isReferencedAliasDeclaration(node)) { + case 211: + if (node.moduleReference.kind === 222 && resolver.isReferencedAliasDeclaration(node)) { externalImports.push(node); } break; - case 216: + case 218: if (node.moduleSpecifier) { if (!node.exportClause) { externalImports.push(node); @@ -24497,12 +25908,12 @@ var ts; else { for (var _c = 0, _d = node.exportClause.elements; _c < _d.length; _c++) { var specifier = _d[_c]; - var name_20 = (specifier.propertyName || specifier.name).text; - (exportSpecifiers[name_20] || (exportSpecifiers[name_20] = [])).push(specifier); + var name_21 = (specifier.propertyName || specifier.name).text; + (exportSpecifiers[name_21] || (exportSpecifiers[name_21] = [])).push(specifier); } } break; - case 215: + case 217: if (node.isExportEquals && !exportEquals) { exportEquals = node; } @@ -24522,13 +25933,16 @@ var ts; write("}"); } } - function getLocalNameForExternalImport(importNode) { - var namespaceDeclaration = getNamespaceDeclarationNode(importNode); - if (namespaceDeclaration && !isDefaultImport(importNode)) { + function getLocalNameForExternalImport(node) { + var namespaceDeclaration = getNamespaceDeclarationNode(node); + if (namespaceDeclaration && !isDefaultImport(node)) { return ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, namespaceDeclaration.name); } - else { - return getGeneratedNameForNode(importNode); + if (node.kind === 212 && node.importClause) { + return getGeneratedNameForNode(node); + } + if (node.kind === 218 && node.moduleSpecifier) { + return getGeneratedNameForNode(node); } } function getExternalModuleNameText(importNode) { @@ -24546,8 +25960,8 @@ var ts; var started = false; for (var _a = 0; _a < externalImports.length; _a++) { var importNode = externalImports[_a]; - var skipNode = importNode.kind === 216 || - (importNode.kind === 210 && !importNode.importClause); + var skipNode = importNode.kind === 218 || + (importNode.kind === 212 && !importNode.importClause); if (skipNode) { continue; } @@ -24572,7 +25986,7 @@ var ts; var hasExportDeclarationWithExportClause = false; for (var _a = 0; _a < externalImports.length; _a++) { var externalImport = externalImports[_a]; - if (externalImport.kind === 216 && externalImport.exportClause) { + if (externalImport.kind === 218 && externalImport.exportClause) { hasExportDeclarationWithExportClause = true; break; } @@ -24601,7 +26015,7 @@ var ts; } for (var _d = 0; _d < externalImports.length; _d++) { var externalImport = externalImports[_d]; - if (externalImport.kind !== 216) { + if (externalImport.kind !== 218) { continue; } var exportDecl = externalImport; @@ -24671,11 +26085,11 @@ var ts; var seen = {}; for (var i = 0; i < hoistedVars.length; ++i) { var local = hoistedVars[i]; - var name_21 = local.kind === 65 + var name_22 = local.kind === 65 ? local : local.name; - if (name_21) { - var text = ts.unescapeIdentifier(name_21.text); + if (name_22) { + var text = ts.unescapeIdentifier(name_22.text); if (ts.hasProperty(seen, text)) { continue; } @@ -24686,7 +26100,7 @@ var ts; if (i !== 0) { write(", "); } - if (local.kind === 202 || local.kind === 206 || local.kind === 205) { + if (local.kind === 204 || local.kind === 208 || local.kind === 207) { emitDeclarationName(local); } else { @@ -24720,21 +26134,21 @@ var ts; if (node.flags & 2) { return; } - if (node.kind === 201) { + if (node.kind === 203) { if (!hoistedFunctionDeclarations) { hoistedFunctionDeclarations = []; } hoistedFunctionDeclarations.push(node); return; } - if (node.kind === 202) { + if (node.kind === 204) { if (!hoistedVars) { hoistedVars = []; } hoistedVars.push(node); return; } - if (node.kind === 205) { + if (node.kind === 207) { if (shouldEmitEnumDeclaration(node)) { if (!hoistedVars) { hoistedVars = []; @@ -24743,7 +26157,7 @@ var ts; } return; } - if (node.kind === 206) { + if (node.kind === 208) { if (shouldEmitModuleDeclaration(node)) { if (!hoistedVars) { hoistedVars = []; @@ -24752,17 +26166,17 @@ var ts; } return; } - if (node.kind === 199 || node.kind === 153) { + if (node.kind === 201 || node.kind === 155) { if (shouldHoistVariable(node, false)) { - var name_22 = node.name; - if (name_22.kind === 65) { + var name_23 = node.name; + if (name_23.kind === 65) { if (!hoistedVars) { hoistedVars = []; } - hoistedVars.push(name_22); + hoistedVars.push(name_23); } else { - ts.forEachChild(name_22, visit); + ts.forEachChild(name_23, visit); } } return; @@ -24781,7 +26195,7 @@ var ts; return false; } return (ts.getCombinedNodeFlags(node) & 12288) === 0 || - ts.getEnclosingBlockScopeContainer(node).kind === 228; + ts.getEnclosingBlockScopeContainer(node).kind === 230; } function isCurrentFileSystemExternalModule() { return compilerOptions.module === 4 && ts.isExternalModule(currentSourceFile); @@ -24798,10 +26212,10 @@ var ts; emitSetters(exportStarFunction); writeLine(); emitExecute(node, startIndex); - emitTempDeclarations(true); decreaseIndent(); writeLine(); write("}"); + emitTempDeclarations(true); } function emitSetters(exportStarFunction) { write("setters:["); @@ -24816,27 +26230,27 @@ var ts; var parameterName = "_" + importVariableName; write("function (" + parameterName + ") {"); switch (importNode.kind) { - case 210: + case 212: if (!importNode.importClause) { break; } - case 209: + case 211: ts.Debug.assert(importVariableName !== ""); increaseIndent(); writeLine(); write(importVariableName + " = " + parameterName + ";"); writeLine(); - var defaultName = importNode.kind === 210 + var defaultName = importNode.kind === 212 ? importNode.importClause.name : importNode.name; if (defaultName) { emitExportMemberAssignments(defaultName); writeLine(); } - if (importNode.kind === 210 && + if (importNode.kind === 212 && importNode.importClause.namedBindings) { var namedBindings = importNode.importClause.namedBindings; - if (namedBindings.kind === 212) { + if (namedBindings.kind === 214) { emitExportMemberAssignments(namedBindings.name); writeLine(); } @@ -24850,7 +26264,7 @@ var ts; } decreaseIndent(); break; - case 216: + case 218: ts.Debug.assert(importVariableName !== ""); increaseIndent(); if (importNode.exportClause) { @@ -24884,10 +26298,10 @@ var ts; for (var i = startIndex; i < node.statements.length; ++i) { var statement = node.statements[i]; switch (statement.kind) { - case 216: - case 210: - case 209: - case 201: + case 218: + case 212: + case 211: + case 203: continue; } writeLine(); @@ -24901,7 +26315,11 @@ var ts; collectExternalModuleInfo(node); ts.Debug.assert(!exportFunctionForFile); exportFunctionForFile = makeUniqueName("exports"); - write("System.register(["); + write("System.register("); + if (node.moduleName) { + write("\"" + node.moduleName + "\", "); + } + write("["); for (var i = 0; i < externalImports.length; ++i) { var text = getExternalModuleNameText(externalImports[i]); if (i !== 0) { @@ -24974,8 +26392,8 @@ var ts; collectExternalModuleInfo(node); writeLine(); write("define("); - if (node.amdModuleName) { - write("\"" + node.amdModuleName + "\", "); + if (node.moduleName) { + write("\"" + node.moduleName + "\", "); } emitAMDDependencies(node, true); write(") {"); @@ -25076,7 +26494,7 @@ var ts; paramEmitted = true; } } - if (ts.isExternalModule(node) || compilerOptions.separateCompilation) { + if (ts.isExternalModule(node) || compilerOptions.isolatedModules) { if (languageVersion >= 2) { emitES6Module(node, startIndex); } @@ -25104,7 +26522,7 @@ var ts; } emitLeadingComments(node.endOfFileToken); } - function emitNodeWithoutSourceMap(node, allowGeneratedIdentifiers) { + function emitNodeWithoutSourceMap(node) { if (!node) { return; } @@ -25115,46 +26533,47 @@ var ts; if (emitComments) { emitLeadingComments(node); } - emitJavaScriptWorker(node, allowGeneratedIdentifiers); + emitJavaScriptWorker(node); if (emitComments) { emitTrailingComments(node); } } function shouldEmitLeadingAndTrailingComments(node) { switch (node.kind) { - case 203: - case 201: - case 210: - case 209: - case 204: - case 215: - return false; - case 206: - return shouldEmitModuleDeclaration(node); case 205: + case 203: + case 212: + case 211: + case 206: + case 217: + return false; + case 183: + return shouldEmitLeadingAndTrailingCommentsForVariableStatement(node); + case 208: + return shouldEmitModuleDeclaration(node); + case 207: return shouldEmitEnumDeclaration(node); } - if (node.kind !== 180 && + if (node.kind !== 182 && node.parent && - node.parent.kind === 164 && + node.parent.kind === 166 && node.parent.body === node && compilerOptions.target <= 1) { return false; } return true; } - function emitJavaScriptWorker(node, allowGeneratedIdentifiers) { - if (allowGeneratedIdentifiers === void 0) { allowGeneratedIdentifiers = true; } + function emitJavaScriptWorker(node) { switch (node.kind) { case 65: - return emitIdentifier(node, allowGeneratedIdentifiers); - case 130: + return emitIdentifier(node); + case 131: return emitParameter(node); + case 136: case 135: - case 134: return emitMethod(node); - case 137: case 138: + case 139: return emitAccessor(node); case 93: return emitThis(node); @@ -25174,131 +26593,131 @@ var ts; case 12: case 13: return emitLiteral(node); - case 172: - return emitTemplateExpression(node); - case 178: - return emitTemplateSpan(node); - case 127: - return emitQualifiedName(node); - case 151: - return emitObjectBindingPattern(node); - case 152: - return emitArrayBindingPattern(node); - case 153: - return emitBindingElement(node); - case 154: - return emitArrayLiteral(node); - case 155: - return emitObjectLiteral(node); - case 225: - return emitPropertyAssignment(node); - case 226: - return emitShorthandPropertyAssignment(node); - case 128: - return emitComputedPropertyName(node); - case 156: - return emitPropertyAccess(node); - case 157: - return emitIndexedAccess(node); - case 158: - return emitCallExpression(node); - case 159: - return emitNewExpression(node); - case 160: - return emitTaggedTemplateExpression(node); - case 161: - return emit(node.expression); - case 162: - return emitParenExpression(node); - case 201: - case 163: - case 164: - return emitFunctionDeclaration(node); - case 165: - return emitDeleteExpression(node); - case 166: - return emitTypeOfExpression(node); - case 167: - return emitVoidExpression(node); - case 168: - return emitPrefixUnaryExpression(node); - case 169: - return emitPostfixUnaryExpression(node); - case 170: - return emitBinaryExpression(node); - case 171: - return emitConditionalExpression(node); case 174: - return emitSpreadElementExpression(node); - case 173: - return emitYieldExpression(node); - case 176: - return; + return emitTemplateExpression(node); case 180: - case 207: - return emitBlock(node); - case 181: - return emitVariableStatement(node); - case 182: - return write(";"); - case 183: - return emitExpressionStatement(node); - case 184: - return emitIfStatement(node); - case 185: - return emitDoStatement(node); - case 186: - return emitWhileStatement(node); - case 187: - return emitForStatement(node); - case 189: - case 188: - return emitForInOrForOfStatement(node); - case 190: - case 191: - return emitBreakOrContinueStatement(node); - case 192: - return emitReturnStatement(node); - case 193: - return emitWithStatement(node); - case 194: - return emitSwitchStatement(node); - case 221: - case 222: - return emitCaseOrDefaultClause(node); - case 195: - return emitLabelledStatement(node); - case 196: - return emitThrowStatement(node); - case 197: - return emitTryStatement(node); - case 224: - return emitCatchClause(node); - case 198: - return emitDebuggerStatement(node); - case 199: - return emitVariableDeclaration(node); - case 175: - return emitClassExpression(node); - case 202: - return emitClassDeclaration(node); - case 203: - return emitInterfaceDeclaration(node); - case 205: - return emitEnumDeclaration(node); + return emitTemplateSpan(node); + case 128: + return emitQualifiedName(node); + case 153: + return emitObjectBindingPattern(node); + case 154: + return emitArrayBindingPattern(node); + case 155: + return emitBindingElement(node); + case 156: + return emitArrayLiteral(node); + case 157: + return emitObjectLiteral(node); case 227: - return emitEnumMember(node); - case 206: - return emitModuleDeclaration(node); - case 210: - return emitImportDeclaration(node); - case 209: - return emitImportEqualsDeclaration(node); - case 216: - return emitExportDeclaration(node); - case 215: - return emitExportAssignment(node); + return emitPropertyAssignment(node); case 228: + return emitShorthandPropertyAssignment(node); + case 129: + return emitComputedPropertyName(node); + case 158: + return emitPropertyAccess(node); + case 159: + return emitIndexedAccess(node); + case 160: + return emitCallExpression(node); + case 161: + return emitNewExpression(node); + case 162: + return emitTaggedTemplateExpression(node); + case 163: + return emit(node.expression); + case 164: + return emitParenExpression(node); + case 203: + case 165: + case 166: + return emitFunctionDeclaration(node); + case 167: + return emitDeleteExpression(node); + case 168: + return emitTypeOfExpression(node); + case 169: + return emitVoidExpression(node); + case 170: + return emitPrefixUnaryExpression(node); + case 171: + return emitPostfixUnaryExpression(node); + case 172: + return emitBinaryExpression(node); + case 173: + return emitConditionalExpression(node); + case 176: + return emitSpreadElementExpression(node); + case 175: + return emitYieldExpression(node); + case 178: + return; + case 182: + case 209: + return emitBlock(node); + case 183: + return emitVariableStatement(node); + case 184: + return write(";"); + case 185: + return emitExpressionStatement(node); + case 186: + return emitIfStatement(node); + case 187: + return emitDoStatement(node); + case 188: + return emitWhileStatement(node); + case 189: + return emitForStatement(node); + case 191: + case 190: + return emitForInOrForOfStatement(node); + case 192: + case 193: + return emitBreakOrContinueStatement(node); + case 194: + return emitReturnStatement(node); + case 195: + return emitWithStatement(node); + case 196: + return emitSwitchStatement(node); + case 223: + case 224: + return emitCaseOrDefaultClause(node); + case 197: + return emitLabelledStatement(node); + case 198: + return emitThrowStatement(node); + case 199: + return emitTryStatement(node); + case 226: + return emitCatchClause(node); + case 200: + return emitDebuggerStatement(node); + case 201: + return emitVariableDeclaration(node); + case 177: + return emitClassExpression(node); + case 204: + return emitClassDeclaration(node); + case 205: + return emitInterfaceDeclaration(node); + case 207: + return emitEnumDeclaration(node); + case 229: + return emitEnumMember(node); + case 208: + return emitModuleDeclaration(node); + case 212: + return emitImportDeclaration(node); + case 211: + return emitImportEqualsDeclaration(node); + case 218: + return emitExportDeclaration(node); + case 217: + return emitExportAssignment(node); + case 230: return emitSourceFileNode(node); } } @@ -25326,7 +26745,7 @@ var ts; } function getLeadingCommentsToEmit(node) { if (node.parent) { - if (node.parent.kind === 228 || node.pos !== node.parent.pos) { + if (node.parent.kind === 230 || node.pos !== node.parent.pos) { if (hasDetachedComments(node.pos)) { return getLeadingCommentsWithoutDetachedComments(); } @@ -25338,7 +26757,7 @@ var ts; } function getTrailingCommentsToEmit(node) { if (node.parent) { - if (node.parent.kind === 228 || node.end !== node.parent.end) { + if (node.parent.kind === 230 || node.end !== node.parent.end) { return ts.getTrailingCommentRanges(currentSourceFile.text, node.end); } } @@ -25432,9 +26851,7 @@ var ts; ts.emitTime = 0; ts.ioReadTime = 0; ts.ioWriteTime = 0; - ts.version = "1.5.2"; - var carriageReturnLineFeed = "\r\n"; - var lineFeed = "\n"; + ts.version = "1.5.3"; function findConfigFile(searchPath) { var fileName = "tsconfig.json"; while (true) { @@ -25505,9 +26922,7 @@ var ts; } } } - var newLine = options.newLine === 0 ? carriageReturnLineFeed : - options.newLine === 1 ? lineFeed : - ts.sys.newLine; + var newLine = ts.getNewLineCharacter(options); return { getSourceFile: getSourceFile, getDefaultLibFileName: function (options) { return ts.combinePaths(ts.getDirectoryPath(ts.normalizePath(ts.sys.getExecutingFilePath())), ts.getDefaultLibFileName(options)); }, @@ -25520,7 +26935,7 @@ var ts; } ts.createCompilerHost = createCompilerHost; function getPreEmitDiagnostics(program, sourceFile) { - var diagnostics = program.getSyntacticDiagnostics(sourceFile).concat(program.getGlobalDiagnostics()).concat(program.getSemanticDiagnostics(sourceFile)); + var diagnostics = program.getOptionsDiagnostics().concat(program.getSyntacticDiagnostics(sourceFile), program.getGlobalDiagnostics(), program.getSemanticDiagnostics(sourceFile)); if (program.getCompilerOptions().declaration) { diagnostics.concat(program.getDeclarationDiagnostics(sourceFile)); } @@ -25553,16 +26968,17 @@ var ts; function createProgram(rootNames, options, host) { var program; var files = []; - var filesByName = {}; var diagnostics = ts.createDiagnosticCollection(); - var seenNoDefaultLib = options.noLib; var commonSourceDirectory; var diagnosticsProducingTypeChecker; var noDiagnosticsTypeChecker; + var classifiableNames; + var skipDefaultLib = options.noLib; var start = new Date().getTime(); host = host || createCompilerHost(options); + var filesByName = ts.createFileMap(function (fileName) { return host.getCanonicalFileName(fileName); }); ts.forEach(rootNames, function (name) { return processRootFile(name, false); }); - if (!seenNoDefaultLib) { + if (!skipDefaultLib) { processRootFile(host.getDefaultLibFileName(options), true); } verifyCompilerOptions(); @@ -25572,10 +26988,12 @@ var ts; getSourceFiles: function () { return files; }, getCompilerOptions: function () { return options; }, getSyntacticDiagnostics: getSyntacticDiagnostics, + getOptionsDiagnostics: getOptionsDiagnostics, getGlobalDiagnostics: getGlobalDiagnostics, getSemanticDiagnostics: getSemanticDiagnostics, getDeclarationDiagnostics: getDeclarationDiagnostics, getTypeChecker: getTypeChecker, + getClassifiableNames: getClassifiableNames, getDiagnosticsProducingTypeChecker: getDiagnosticsProducingTypeChecker, getCommonSourceDirectory: function () { return commonSourceDirectory; }, emit: emit, @@ -25586,6 +27004,17 @@ var ts; getTypeCount: function () { return getDiagnosticsProducingTypeChecker().getTypeCount(); } }; return program; + function getClassifiableNames() { + if (!classifiableNames) { + getTypeChecker(); + classifiableNames = {}; + for (var _i = 0; _i < files.length; _i++) { + var sourceFile = files[_i]; + ts.copyMap(sourceFile.classifiableNames, classifiableNames); + } + } + return classifiableNames; + } function getEmitHost(writeFileCallback) { return { getCanonicalFileName: function (fileName) { return host.getCanonicalFileName(fileName); }, @@ -25615,8 +27044,7 @@ var ts; return emitResult; } function getSourceFile(fileName) { - fileName = host.getCanonicalFileName(ts.normalizeSlashes(fileName)); - return ts.hasProperty(filesByName, fileName) ? filesByName[fileName] : undefined; + return filesByName.get(fileName); } function getDiagnosticsHelper(sourceFile, getDiagnostics) { if (sourceFile) { @@ -25655,13 +27083,16 @@ var ts; return ts.getDeclarationDiagnostics(getEmitHost(writeFile), resolver, sourceFile); } } - function getGlobalDiagnostics() { - var typeChecker = getDiagnosticsProducingTypeChecker(); + function getOptionsDiagnostics() { var allDiagnostics = []; - ts.addRange(allDiagnostics, typeChecker.getGlobalDiagnostics()); ts.addRange(allDiagnostics, diagnostics.getGlobalDiagnostics()); return ts.sortAndDeduplicateDiagnostics(allDiagnostics); } + function getGlobalDiagnostics() { + var allDiagnostics = []; + ts.addRange(allDiagnostics, getDiagnosticsProducingTypeChecker().getGlobalDiagnostics()); + return ts.sortAndDeduplicateDiagnostics(allDiagnostics); + } function hasExtension(fileName) { return ts.getBaseFileName(fileName).indexOf(".") >= 0; } @@ -25693,14 +27124,17 @@ var ts; } } else { - if (options.allowNonTsExtensions && !findSourceFile(fileName, isDefaultLib, refFile, refPos, refEnd)) { - diagnostic = ts.Diagnostics.File_0_not_found; - diagnosticArgument = [fileName]; - } - else if (!ts.forEach(ts.supportedExtensions, function (extension) { return findSourceFile(fileName + extension, isDefaultLib, refFile, refPos, refEnd); })) { - diagnostic = ts.Diagnostics.File_0_not_found; - fileName += ".ts"; - diagnosticArgument = [fileName]; + var nonTsFile = options.allowNonTsExtensions && findSourceFile(fileName, isDefaultLib, refFile, refPos, refEnd); + if (!nonTsFile) { + if (options.allowNonTsExtensions) { + diagnostic = ts.Diagnostics.File_0_not_found; + diagnosticArgument = [fileName]; + } + else if (!ts.forEach(ts.supportedExtensions, function (extension) { return findSourceFile(fileName + extension, isDefaultLib, refFile, refPos, refEnd); })) { + diagnostic = ts.Diagnostics.File_0_not_found; + fileName += ".ts"; + diagnosticArgument = [fileName]; + } } } if (diagnostic) { @@ -25714,16 +27148,16 @@ var ts; } function findSourceFile(fileName, isDefaultLib, refFile, refStart, refLength) { var canonicalName = host.getCanonicalFileName(ts.normalizeSlashes(fileName)); - if (ts.hasProperty(filesByName, canonicalName)) { + if (filesByName.contains(canonicalName)) { return getSourceFileFromCache(fileName, canonicalName, false); } else { var normalizedAbsolutePath = ts.getNormalizedAbsolutePath(fileName, host.getCurrentDirectory()); var canonicalAbsolutePath = host.getCanonicalFileName(normalizedAbsolutePath); - if (ts.hasProperty(filesByName, canonicalAbsolutePath)) { + if (filesByName.contains(canonicalAbsolutePath)) { return getSourceFileFromCache(normalizedAbsolutePath, canonicalAbsolutePath, true); } - var file = filesByName[canonicalName] = host.getSourceFile(fileName, options.target, function (hostErrorMessage) { + var file = host.getSourceFile(fileName, options.target, function (hostErrorMessage) { if (refFile) { diagnostics.add(ts.createFileDiagnostic(refFile, refStart, refLength, ts.Diagnostics.Cannot_read_file_0_Colon_1, fileName, hostErrorMessage)); } @@ -25731,15 +27165,17 @@ var ts; diagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0_Colon_1, fileName, hostErrorMessage)); } }); + filesByName.set(canonicalName, file); if (file) { - seenNoDefaultLib = seenNoDefaultLib || file.hasNoDefaultLib; - filesByName[canonicalAbsolutePath] = file; + skipDefaultLib = skipDefaultLib || file.hasNoDefaultLib; + filesByName.set(canonicalAbsolutePath, file); if (!options.noResolve) { var basePath = ts.getDirectoryPath(fileName); processReferencedFiles(file, basePath); processImportedModules(file, basePath); } if (isDefaultLib) { + file.isDefaultLib = true; files.unshift(file); } else { @@ -25749,7 +27185,7 @@ var ts; return file; } function getSourceFileFromCache(fileName, canonicalName, useAbsolutePath) { - var file = filesByName[canonicalName]; + var file = filesByName.get(canonicalName); if (file && host.useCaseSensitiveFileNames()) { var sourceFileName = useAbsolutePath ? ts.getNormalizedAbsolutePath(file.fileName, host.getCurrentDirectory()) : file.fileName; if (canonicalName !== sourceFileName) { @@ -25767,7 +27203,7 @@ var ts; } function processImportedModules(file, basePath) { ts.forEach(file.statements, function (node) { - if (node.kind === 210 || node.kind === 209 || node.kind === 216) { + if (node.kind === 212 || node.kind === 211 || node.kind === 218) { var moduleNameExpr = ts.getExternalModuleName(node); if (moduleNameExpr && moduleNameExpr.kind === 8) { var moduleNameText = moduleNameExpr.text; @@ -25788,7 +27224,7 @@ var ts; } } } - else if (node.kind === 206 && node.name.kind === 8 && (node.flags & 2 || ts.isDeclarationFile(file))) { + else if (node.kind === 208 && node.name.kind === 8 && (node.flags & 2 || ts.isDeclarationFile(file))) { ts.forEachChild(node.body, function (node) { if (ts.isExternalModuleImportEqualsDeclaration(node) && ts.getExternalModuleImportEqualsDeclarationExpression(node).kind === 8) { @@ -25854,18 +27290,18 @@ var ts; return allFilesBelongToPath; } function verifyCompilerOptions() { - if (options.separateCompilation) { + if (options.isolatedModules) { if (options.sourceMap) { - diagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_sourceMap_cannot_be_specified_with_option_separateCompilation)); + diagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_sourceMap_cannot_be_specified_with_option_isolatedModules)); } if (options.declaration) { - diagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_declaration_cannot_be_specified_with_option_separateCompilation)); + diagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_declaration_cannot_be_specified_with_option_isolatedModules)); } if (options.noEmitOnError) { - diagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_noEmitOnError_cannot_be_specified_with_option_separateCompilation)); + diagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_noEmitOnError_cannot_be_specified_with_option_isolatedModules)); } if (options.out) { - diagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_out_cannot_be_specified_with_option_separateCompilation)); + diagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_out_cannot_be_specified_with_option_isolatedModules)); } } if (options.inlineSourceMap) { @@ -25895,14 +27331,14 @@ var ts; } var languageVersion = options.target || 0; var firstExternalModuleSourceFile = ts.forEach(files, function (f) { return ts.isExternalModule(f) ? f : undefined; }); - if (options.separateCompilation) { + if (options.isolatedModules) { if (!options.module && languageVersion < 2) { - diagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_separateCompilation_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES6_or_higher)); + diagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES6_or_higher)); } var firstNonExternalModuleSourceFile = ts.forEach(files, function (f) { return !ts.isExternalModule(f) && !ts.isDeclarationFile(f) ? f : undefined; }); if (firstNonExternalModuleSourceFile) { var span = ts.getErrorSpanForNode(firstNonExternalModuleSourceFile, firstNonExternalModuleSourceFile); - diagnostics.add(ts.createFileDiagnostic(firstNonExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_compile_namespaces_when_the_separateCompilation_flag_is_provided)); + diagnostics.add(ts.createFileDiagnostic(firstNonExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided)); } } else if (firstExternalModuleSourceFile && languageVersion < 2 && !options.module) { @@ -25934,6 +27370,10 @@ var ts; diagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_noEmit_cannot_be_specified_with_option_declaration)); } } + if (options.emitDecoratorMetadata && + !options.experimentalDecorators) { + diagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_experimentalDecorators_must_also_be_specified_when_option_emitDecoratorMetadata_is_specified)); + } } } ts.createProgram = createProgram; @@ -25979,98 +27419,98 @@ var ts; function spanInNode(node) { if (node) { if (ts.isExpression(node)) { - if (node.parent.kind === 185) { + if (node.parent.kind === 187) { return spanInPreviousNode(node); } - if (node.parent.kind === 187) { + if (node.parent.kind === 189) { return textSpan(node); } - if (node.parent.kind === 170 && node.parent.operatorToken.kind === 23) { + if (node.parent.kind === 172 && node.parent.operatorToken.kind === 23) { return textSpan(node); } - if (node.parent.kind == 164 && node.parent.body == node) { + if (node.parent.kind === 166 && node.parent.body === node) { return textSpan(node); } } switch (node.kind) { - case 181: + case 183: return spanInVariableDeclaration(node.declarationList.declarations[0]); - case 199: - case 133: - case 132: - return spanInVariableDeclaration(node); - case 130: - return spanInParameterDeclaration(node); case 201: - case 135: case 134: - case 137: - case 138: + case 133: + return spanInVariableDeclaration(node); + case 131: + return spanInParameterDeclaration(node); + case 203: case 136: - case 163: - case 164: + case 135: + case 138: + case 139: + case 137: + case 165: + case 166: return spanInFunctionDeclaration(node); - case 180: + case 182: if (ts.isFunctionBlock(node)) { return spanInFunctionBlock(node); } - case 207: + case 209: return spanInBlock(node); - case 224: + case 226: return spanInBlock(node.block); - case 183: + case 185: return textSpan(node.expression); - case 192: + case 194: return textSpan(node.getChildAt(0), node.expression); + case 188: + return textSpan(node, ts.findNextToken(node.expression, node)); + case 187: + return spanInNode(node.statement); + case 200: + return textSpan(node.getChildAt(0)); case 186: return textSpan(node, ts.findNextToken(node.expression, node)); - case 185: - return spanInNode(node.statement); - case 198: - return textSpan(node.getChildAt(0)); - case 184: - return textSpan(node, ts.findNextToken(node.expression, node)); - case 195: - return spanInNode(node.statement); - case 191: - case 190: - return textSpan(node.getChildAt(0), node.label); - case 187: - return spanInForStatement(node); - case 188: - case 189: - return textSpan(node, ts.findNextToken(node.expression, node)); - case 194: - return textSpan(node, ts.findNextToken(node.expression, node)); - case 221: - case 222: - return spanInNode(node.statements[0]); case 197: - return spanInBlock(node.tryBlock); + return spanInNode(node.statement); + case 193: + case 192: + return textSpan(node.getChildAt(0), node.label); + case 189: + return spanInForStatement(node); + case 190: + case 191: + return textSpan(node, ts.findNextToken(node.expression, node)); case 196: + return textSpan(node, ts.findNextToken(node.expression, node)); + case 223: + case 224: + return spanInNode(node.statements[0]); + case 199: + return spanInBlock(node.tryBlock); + case 198: return textSpan(node, node.expression); - case 215: + case 217: return textSpan(node, node.expression); - case 209: + case 211: return textSpan(node, node.moduleReference); - case 210: + case 212: return textSpan(node, node.moduleSpecifier); - case 216: + case 218: return textSpan(node, node.moduleSpecifier); - case 206: + case 208: if (ts.getModuleInstanceState(node) !== 1) { return undefined; } - case 202: - case 205: - case 227: - case 158: - case 159: - return textSpan(node); - case 193: - return spanInNode(node.statement); - case 203: case 204: + case 207: + case 229: + case 160: + case 161: + return textSpan(node); + case 195: + return spanInNode(node.statement); + case 205: + case 206: return undefined; case 22: case 1: @@ -26097,10 +27537,10 @@ var ts; case 81: return spanInNextNode(node); default: - if (node.parent.kind === 225 && node.parent.name === node) { + if (node.parent.kind === 227 && node.parent.name === node) { return spanInNode(node.parent.initializer); } - if (node.parent.kind === 161 && node.parent.type === node) { + if (node.parent.kind === 163 && node.parent.type === node) { return spanInNode(node.parent.expression); } if (ts.isFunctionLike(node.parent) && node.parent.type === node) { @@ -26110,12 +27550,12 @@ var ts; } } function spanInVariableDeclaration(variableDeclaration) { - if (variableDeclaration.parent.parent.kind === 188 || - variableDeclaration.parent.parent.kind === 189) { + if (variableDeclaration.parent.parent.kind === 190 || + variableDeclaration.parent.parent.kind === 191) { return spanInNode(variableDeclaration.parent.parent); } - var isParentVariableStatement = variableDeclaration.parent.parent.kind === 181; - var isDeclarationOfForStatement = variableDeclaration.parent.parent.kind === 187 && ts.contains(variableDeclaration.parent.parent.initializer.declarations, variableDeclaration); + var isParentVariableStatement = variableDeclaration.parent.parent.kind === 183; + var isDeclarationOfForStatement = variableDeclaration.parent.parent.kind === 189 && ts.contains(variableDeclaration.parent.parent.initializer.declarations, variableDeclaration); var declarations = isParentVariableStatement ? variableDeclaration.parent.parent.declarationList.declarations : isDeclarationOfForStatement @@ -26161,7 +27601,7 @@ var ts; } function canFunctionHaveSpanInWholeDeclaration(functionDeclaration) { return !!(functionDeclaration.flags & 1) || - (functionDeclaration.parent.kind === 202 && functionDeclaration.kind !== 136); + (functionDeclaration.parent.kind === 204 && functionDeclaration.kind !== 137); } function spanInFunctionDeclaration(functionDeclaration) { if (!functionDeclaration.body) { @@ -26181,23 +27621,23 @@ var ts; } function spanInBlock(block) { switch (block.parent.kind) { - case 206: + case 208: if (ts.getModuleInstanceState(block.parent) !== 1) { return undefined; } - case 186: - case 184: case 188: - case 189: + case 186: + case 190: + case 191: return spanInNodeIfStartsOnSameLine(block.parent, block.statements[0]); - case 187: + case 189: return spanInNodeIfStartsOnSameLine(ts.findPrecedingToken(block.pos, sourceFile, block.parent), block.statements[0]); } return spanInNode(block.statements[0]); } function spanInForStatement(forStatement) { if (forStatement.initializer) { - if (forStatement.initializer.kind === 200) { + if (forStatement.initializer.kind === 202) { var variableDeclarationList = forStatement.initializer; if (variableDeclarationList.declarations.length > 0) { return spanInNode(variableDeclarationList.declarations[0]); @@ -26216,34 +27656,34 @@ var ts; } function spanInOpenBraceToken(node) { switch (node.parent.kind) { - case 205: + case 207: var enumDeclaration = node.parent; return spanInNodeIfStartsOnSameLine(ts.findPrecedingToken(node.pos, sourceFile, node.parent), enumDeclaration.members.length ? enumDeclaration.members[0] : enumDeclaration.getLastToken(sourceFile)); - case 202: + case 204: var classDeclaration = node.parent; return spanInNodeIfStartsOnSameLine(ts.findPrecedingToken(node.pos, sourceFile, node.parent), classDeclaration.members.length ? classDeclaration.members[0] : classDeclaration.getLastToken(sourceFile)); - case 208: + case 210: return spanInNodeIfStartsOnSameLine(node.parent.parent, node.parent.clauses[0]); } return spanInNode(node.parent); } function spanInCloseBraceToken(node) { switch (node.parent.kind) { - case 207: + case 209: if (ts.getModuleInstanceState(node.parent.parent) !== 1) { return undefined; } - case 205: - case 202: + case 207: + case 204: return textSpan(node); - case 180: + case 182: if (ts.isFunctionBlock(node.parent)) { return textSpan(node); } - case 224: + case 226: return spanInNode(ts.lastOrUndefined(node.parent.statements)); ; - case 208: + case 210: var caseBlock = node.parent; var lastClause = ts.lastOrUndefined(caseBlock.clauses); if (lastClause) { @@ -26255,24 +27695,24 @@ var ts; } } function spanInOpenParenToken(node) { - if (node.parent.kind === 185) { + if (node.parent.kind === 187) { return spanInPreviousNode(node); } return spanInNode(node.parent); } function spanInCloseParenToken(node) { switch (node.parent.kind) { - case 163: - case 201: - case 164: - case 135: - case 134: - case 137: - case 138: + case 165: + case 203: + case 166: case 136: - case 186: - case 185: + case 135: + case 138: + case 139: + case 137: + case 188: case 187: + case 189: return spanInPreviousNode(node); default: return spanInNode(node.parent); @@ -26280,19 +27720,19 @@ var ts; return spanInNode(node.parent); } function spanInColonToken(node) { - if (ts.isFunctionLike(node.parent) || node.parent.kind === 225) { + if (ts.isFunctionLike(node.parent) || node.parent.kind === 227) { return spanInPreviousNode(node); } return spanInNode(node.parent); } function spanInGreaterThanOrLessThanToken(node) { - if (node.parent.kind === 161) { + if (node.parent.kind === 163) { return spanInNode(node.parent.expression); } return spanInNode(node.parent); } function spanInWhileKeyword(node) { - if (node.parent.kind === 185) { + if (node.parent.kind === 187) { return textSpan(node, ts.findNextToken(node.parent.expression, node.parent)); } return spanInNode(node.parent); @@ -26370,7 +27810,7 @@ var ts; } } function autoCollapse(node) { - return ts.isFunctionBlock(node) && node.parent.kind !== 164; + return ts.isFunctionBlock(node) && node.parent.kind !== 166; } var depth = 0; var maxDepth = 20; @@ -26382,26 +27822,26 @@ var ts; addOutliningForLeadingCommentsForNode(n); } switch (n.kind) { - case 180: + case 182: if (!ts.isFunctionBlock(n)) { - var parent_6 = n.parent; + var parent_8 = n.parent; var openBrace = ts.findChildOfKind(n, 14, sourceFile); var closeBrace = ts.findChildOfKind(n, 15, sourceFile); - if (parent_6.kind === 185 || - parent_6.kind === 188 || - parent_6.kind === 189 || - parent_6.kind === 187 || - parent_6.kind === 184 || - parent_6.kind === 186 || - parent_6.kind === 193 || - parent_6.kind === 224) { - addOutliningSpan(parent_6, openBrace, closeBrace, autoCollapse(n)); + if (parent_8.kind === 187 || + parent_8.kind === 190 || + parent_8.kind === 191 || + parent_8.kind === 189 || + parent_8.kind === 186 || + parent_8.kind === 188 || + parent_8.kind === 195 || + parent_8.kind === 226) { + addOutliningSpan(parent_8, openBrace, closeBrace, autoCollapse(n)); break; } - if (parent_6.kind === 197) { - var tryStatement = parent_6; + if (parent_8.kind === 199) { + var tryStatement = parent_8; if (tryStatement.tryBlock === n) { - addOutliningSpan(parent_6, openBrace, closeBrace, autoCollapse(n)); + addOutliningSpan(parent_8, openBrace, closeBrace, autoCollapse(n)); break; } else if (tryStatement.finallyBlock === n) { @@ -26421,23 +27861,23 @@ var ts; }); break; } - case 207: { + case 209: { var openBrace = ts.findChildOfKind(n, 14, sourceFile); var closeBrace = ts.findChildOfKind(n, 15, sourceFile); addOutliningSpan(n.parent, openBrace, closeBrace, autoCollapse(n)); break; } - case 202: - case 203: + case 204: case 205: - case 155: - case 208: { + case 207: + case 157: + case 210: { var openBrace = ts.findChildOfKind(n, 14, sourceFile); var closeBrace = ts.findChildOfKind(n, 15, sourceFile); addOutliningSpan(n, openBrace, closeBrace, autoCollapse(n)); break; } - case 154: + case 156: var openBracket = ts.findChildOfKind(n, 18, sourceFile); var closeBracket = ts.findChildOfKind(n, 19, sourceFile); addOutliningSpan(n, openBracket, closeBracket, autoCollapse(n)); @@ -26463,10 +27903,10 @@ var ts; ts.forEach(program.getSourceFiles(), function (sourceFile) { cancellationToken.throwIfCancellationRequested(); var nameToDeclarations = sourceFile.getNamedDeclarations(); - for (var name_23 in nameToDeclarations) { - var declarations = ts.getProperty(nameToDeclarations, name_23); + for (var name_24 in nameToDeclarations) { + var declarations = ts.getProperty(nameToDeclarations, name_24); if (declarations) { - var matches = patternMatcher.getMatchesForLastSegmentOfPattern(name_23); + var matches = patternMatcher.getMatchesForLastSegmentOfPattern(name_24); if (!matches) { continue; } @@ -26477,14 +27917,14 @@ var ts; if (!containers) { return undefined; } - matches = patternMatcher.getMatches(containers, name_23); + matches = patternMatcher.getMatches(containers, name_24); if (!matches) { continue; } } var fileName = sourceFile.fileName; var matchKind = bestMatchKind(matches); - rawItems.push({ name: name_23, fileName: fileName, matchKind: matchKind, isCaseSensitive: allMatchesAreCaseSensitive(matches), declaration: declaration }); + rawItems.push({ name: name_24, fileName: fileName, matchKind: matchKind, isCaseSensitive: allMatchesAreCaseSensitive(matches), declaration: declaration }); } } } @@ -26521,7 +27961,7 @@ var ts; if (text !== undefined) { containers.unshift(text); } - else if (declaration.name.kind === 128) { + else if (declaration.name.kind === 129) { return tryAddComputedPropertyName(declaration.name.expression, containers, true); } else { @@ -26538,7 +27978,7 @@ var ts; } return true; } - if (expression.kind === 156) { + if (expression.kind === 158) { var propertyAccess = expression; if (includeLastPortion) { containers.unshift(propertyAccess.name.text); @@ -26549,7 +27989,7 @@ var ts; } function getContainers(declaration) { var containers = []; - if (declaration.name.kind === 128) { + if (declaration.name.kind === 129) { if (!tryAddComputedPropertyName(declaration.name.expression, containers, false)) { return undefined; } @@ -26613,14 +28053,14 @@ var ts; var current = node.parent; while (current) { switch (current.kind) { - case 206: + case 208: do { current = current.parent; - } while (current.kind === 206); - case 202: + } while (current.kind === 208); + case 204: + case 207: case 205: case 203: - case 201: indent++; } current = current.parent; @@ -26631,26 +28071,26 @@ var ts; var childNodes = []; function visit(node) { switch (node.kind) { - case 181: + case 183: ts.forEach(node.declarationList.declarations, visit); break; - case 151: - case 152: + case 153: + case 154: ts.forEach(node.elements, visit); break; - case 216: + case 218: if (node.exportClause) { ts.forEach(node.exportClause.elements, visit); } break; - case 210: + case 212: var importClause = node.importClause; if (importClause) { if (importClause.name) { childNodes.push(importClause); } if (importClause.namedBindings) { - if (importClause.namedBindings.kind === 212) { + if (importClause.namedBindings.kind === 214) { childNodes.push(importClause.namedBindings); } else { @@ -26659,20 +28099,20 @@ var ts; } } break; - case 153: - case 199: + case 155: + case 201: if (ts.isBindingPattern(node.name)) { visit(node.name); break; } - case 202: + case 204: + case 207: case 205: + case 208: case 203: - case 206: - case 201: - case 209: - case 214: - case 218: + case 211: + case 216: + case 220: childNodes.push(node); break; } @@ -26707,17 +28147,17 @@ var ts; for (var _i = 0; _i < nodes.length; _i++) { var node = nodes[_i]; switch (node.kind) { - case 202: + case 204: + case 207: case 205: - case 203: topLevelNodes.push(node); break; - case 206: + case 208: var moduleDeclaration = node; topLevelNodes.push(node); addTopLevelNodes(getInnermostModule(moduleDeclaration).body.statements, topLevelNodes); break; - case 201: + case 203: var functionDeclaration = node; if (isTopLevelFunctionDeclaration(functionDeclaration)) { topLevelNodes.push(node); @@ -26728,9 +28168,9 @@ var ts; } } function isTopLevelFunctionDeclaration(functionDeclaration) { - if (functionDeclaration.kind === 201) { - if (functionDeclaration.body && functionDeclaration.body.kind === 180) { - if (ts.forEach(functionDeclaration.body.statements, function (s) { return s.kind === 201 && !isEmpty(s.name.text); })) { + if (functionDeclaration.kind === 203) { + if (functionDeclaration.body && functionDeclaration.body.kind === 182) { + if (ts.forEach(functionDeclaration.body.statements, function (s) { return s.kind === 203 && !isEmpty(s.name.text); })) { return true; } if (!ts.isFunctionBlock(functionDeclaration.parent)) { @@ -26783,7 +28223,7 @@ var ts; } function createChildItem(node) { switch (node.kind) { - case 130: + case 131: if (ts.isBindingPattern(node.name)) { break; } @@ -26791,34 +28231,34 @@ var ts; return undefined; } return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.memberVariableElement); + case 136: case 135: - case 134: return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.memberFunctionElement); - case 137: - return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.memberGetAccessorElement); case 138: - return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.memberSetAccessorElement); - case 141: - return createItem(node, "[]", ts.ScriptElementKind.indexSignatureElement); - case 227: - return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.memberVariableElement); + return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.memberGetAccessorElement); case 139: - return createItem(node, "()", ts.ScriptElementKind.callSignatureElement); - case 140: - return createItem(node, "new()", ts.ScriptElementKind.constructSignatureElement); - case 133: - case 132: + return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.memberSetAccessorElement); + case 142: + return createItem(node, "[]", ts.ScriptElementKind.indexSignatureElement); + case 229: return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.memberVariableElement); - case 201: + case 140: + return createItem(node, "()", ts.ScriptElementKind.callSignatureElement); + case 141: + return createItem(node, "new()", ts.ScriptElementKind.constructSignatureElement); + case 134: + case 133: + return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.memberVariableElement); + case 203: return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.functionElement); - case 199: - case 153: + case 201: + case 155: var variableDeclarationNode; - var name_24; - if (node.kind === 153) { - name_24 = node.name; + var name_25; + if (node.kind === 155) { + name_25 = node.name; variableDeclarationNode = node; - while (variableDeclarationNode && variableDeclarationNode.kind !== 199) { + while (variableDeclarationNode && variableDeclarationNode.kind !== 201) { variableDeclarationNode = variableDeclarationNode.parent; } ts.Debug.assert(variableDeclarationNode !== undefined); @@ -26826,24 +28266,24 @@ var ts; else { ts.Debug.assert(!ts.isBindingPattern(node.name)); variableDeclarationNode = node; - name_24 = node.name; + name_25 = node.name; } if (ts.isConst(variableDeclarationNode)) { - return createItem(node, getTextOfNode(name_24), ts.ScriptElementKind.constElement); + return createItem(node, getTextOfNode(name_25), ts.ScriptElementKind.constElement); } else if (ts.isLet(variableDeclarationNode)) { - return createItem(node, getTextOfNode(name_24), ts.ScriptElementKind.letElement); + return createItem(node, getTextOfNode(name_25), ts.ScriptElementKind.letElement); } else { - return createItem(node, getTextOfNode(name_24), ts.ScriptElementKind.variableElement); + return createItem(node, getTextOfNode(name_25), ts.ScriptElementKind.variableElement); } - case 136: + case 137: return createItem(node, "constructor", ts.ScriptElementKind.constructorImplementationElement); - case 218: - case 214: - case 209: + case 220: + case 216: case 211: - case 212: + case 213: + case 214: return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.alias); } return undefined; @@ -26873,17 +28313,17 @@ var ts; } function createTopLevelItem(node) { switch (node.kind) { - case 228: + case 230: return createSourceFileItem(node); - case 202: + case 204: return createClassItem(node); - case 205: + case 207: return createEnumItem(node); - case 203: + case 205: return createIterfaceItem(node); - case 206: + case 208: return createModuleItem(node); - case 201: + case 203: return createFunctionItem(node); } return undefined; @@ -26893,7 +28333,7 @@ var ts; } var result = []; result.push(moduleDeclaration.name.text); - while (moduleDeclaration.body && moduleDeclaration.body.kind === 206) { + while (moduleDeclaration.body && moduleDeclaration.body.kind === 208) { moduleDeclaration = moduleDeclaration.body; result.push(moduleDeclaration.name.text); } @@ -26905,7 +28345,7 @@ var ts; return getNavigationBarItem(moduleName, ts.ScriptElementKind.moduleElement, ts.getNodeModifiers(node), [getNodeSpan(node)], childItems, getIndent(node)); } function createFunctionItem(node) { - if (node.body && node.body.kind === 180) { + if (node.body && node.body.kind === 182) { var childItems = getItemsWorker(sortNodes(node.body.statements), createChildItem); return getNavigationBarItem(!node.name ? "default" : node.name.text, ts.ScriptElementKind.functionElement, ts.getNodeModifiers(node), [getNodeSpan(node)], childItems, getIndent(node)); } @@ -26926,7 +28366,7 @@ var ts; var childItems; if (node.members) { var constructor = ts.forEach(node.members, function (member) { - return member.kind === 136 && member; + return member.kind === 137 && member; }); var nodes = removeDynamicallyNamedProperties(node); if (constructor) { @@ -26947,19 +28387,19 @@ var ts; } } function removeComputedProperties(node) { - return ts.filter(node.members, function (member) { return member.name === undefined || member.name.kind !== 128; }); + return ts.filter(node.members, function (member) { return member.name === undefined || member.name.kind !== 129; }); } function removeDynamicallyNamedProperties(node) { return ts.filter(node.members, function (member) { return !ts.hasDynamicName(member); }); } function getInnermostModule(node) { - while (node.body.kind === 206) { + while (node.body.kind === 208) { node = node.body; } return node; } function getNodeSpan(node) { - return node.kind === 228 + return node.kind === 230 ? ts.createTextSpanFromBounds(node.getFullStart(), node.getEnd()) : ts.createTextSpanFromBounds(node.getStart(), node.getEnd()); } @@ -27342,7 +28782,7 @@ var ts; var hasTransitionFromUpperToLower = transitionFromUpperToLower(identifier, word, i, wordStart); if (charIsPunctuation(identifier.charCodeAt(i - 1)) || charIsPunctuation(identifier.charCodeAt(i)) || - lastIsDigit != currentIsDigit || + lastIsDigit !== currentIsDigit || hasTransitionFromLowerToUpper || hasTransitionFromUpperToLower) { if (!isAllPunctuation(identifier, wordStart, i)) { @@ -27396,7 +28836,7 @@ var ts; } function transitionFromUpperToLower(identifier, word, index, wordStart) { if (word) { - if (index != wordStart && + if (index !== wordStart && index + 1 < identifier.length) { var currentIsUpper = isUpperCaseLetter(identifier.charCodeAt(index)); var nextIsLower = isLowerCaseLetter(identifier.charCodeAt(index + 1)); @@ -27450,14 +28890,14 @@ var ts; } return createSignatureHelpItems(candidates, resolvedSignature, argumentInfo); function createJavaScriptSignatureHelpItems(argumentInfo) { - if (argumentInfo.invocation.kind !== 158) { + if (argumentInfo.invocation.kind !== 160) { return undefined; } var callExpression = argumentInfo.invocation; var expression = callExpression.expression; var name = expression.kind === 65 ? expression - : expression.kind === 156 + : expression.kind === 158 ? expression.name : undefined; if (!name || !name.text) { @@ -27486,7 +28926,7 @@ var ts; } } function getImmediatelyContainingArgumentInfo(node) { - if (node.parent.kind === 158 || node.parent.kind === 159) { + if (node.parent.kind === 160 || node.parent.kind === 161) { var callExpression = node.parent; if (node.kind === 24 || node.kind === 16) { @@ -27517,23 +28957,23 @@ var ts; }; } } - else if (node.kind === 10 && node.parent.kind === 160) { + else if (node.kind === 10 && node.parent.kind === 162) { if (ts.isInsideTemplateLiteral(node, position)) { return getArgumentListInfoForTemplate(node.parent, 0); } } - else if (node.kind === 11 && node.parent.parent.kind === 160) { + else if (node.kind === 11 && node.parent.parent.kind === 162) { var templateExpression = node.parent; var tagExpression = templateExpression.parent; - ts.Debug.assert(templateExpression.kind === 172); + ts.Debug.assert(templateExpression.kind === 174); var argumentIndex = ts.isInsideTemplateLiteral(node, position) ? 0 : 1; return getArgumentListInfoForTemplate(tagExpression, argumentIndex); } - else if (node.parent.kind === 178 && node.parent.parent.parent.kind === 160) { + else if (node.parent.kind === 180 && node.parent.parent.parent.kind === 162) { var templateSpan = node.parent; var templateExpression = templateSpan.parent; var tagExpression = templateExpression.parent; - ts.Debug.assert(templateExpression.kind === 172); + ts.Debug.assert(templateExpression.kind === 174); if (node.kind === 13 && !ts.isInsideTemplateLiteral(node, position)) { return undefined; } @@ -27597,7 +29037,7 @@ var ts; var template = taggedTemplate.template; var applicableSpanStart = template.getStart(); var applicableSpanEnd = template.getEnd(); - if (template.kind === 172) { + if (template.kind === 174) { var lastSpan = ts.lastOrUndefined(template.templateSpans); if (lastSpan.literal.getFullWidth() === 0) { applicableSpanEnd = ts.skipTrivia(sourceFile.text, applicableSpanEnd, false); @@ -27606,7 +29046,7 @@ var ts; return ts.createTextSpan(applicableSpanStart, applicableSpanEnd - applicableSpanStart); } function getContainingArgumentInfo(node) { - for (var n = node; n.kind !== 228; n = n.parent) { + for (var n = node; n.kind !== 230; n = n.parent) { if (ts.isFunctionBlock(n)) { return undefined; } @@ -27787,39 +29227,39 @@ var ts; return false; } switch (n.kind) { - case 202: - case 203: + case 204: case 205: - case 155: - case 151: - case 146: - case 180: case 207: - case 208: + case 157: + case 153: + case 148: + case 182: + case 209: + case 210: return nodeEndsWith(n, 15, sourceFile); - case 224: + case 226: return isCompletedNode(n.block, sourceFile); - case 159: + case 161: if (!n.arguments) { return true; } - case 158: - case 162: - case 150: + case 160: + case 164: + case 152: return nodeEndsWith(n, 17, sourceFile); - case 143: - case 144: + case 145: + case 146: return isCompletedNode(n.type, sourceFile); - case 136: case 137: case 138: - case 201: - case 163: - case 135: - case 134: - case 140: case 139: - case 164: + case 203: + case 165: + case 136: + case 135: + case 141: + case 140: + case 166: if (n.body) { return isCompletedNode(n.body, sourceFile); } @@ -27827,61 +29267,61 @@ var ts; return isCompletedNode(n.type, sourceFile); } return hasChildOfKind(n, 17, sourceFile); - case 206: + case 208: return n.body && isCompletedNode(n.body, sourceFile); - case 184: + case 186: if (n.elseStatement) { return isCompletedNode(n.elseStatement, sourceFile); } return isCompletedNode(n.thenStatement, sourceFile); - case 183: + case 185: return isCompletedNode(n.expression, sourceFile); + case 156: case 154: - case 152: - case 157: - case 128: - case 148: + case 159: + case 129: + case 150: return nodeEndsWith(n, 19, sourceFile); - case 141: + case 142: if (n.type) { return isCompletedNode(n.type, sourceFile); } return hasChildOfKind(n, 19, sourceFile); - case 221: - case 222: + case 223: + case 224: return false; - case 187: - case 188: case 189: - case 186: + case 190: + case 191: + case 188: return isCompletedNode(n.statement, sourceFile); - case 185: + case 187: var hasWhileKeyword = findChildOfKind(n, 100, sourceFile); if (hasWhileKeyword) { return nodeEndsWith(n, 17, sourceFile); } return isCompletedNode(n.statement, sourceFile); - case 145: + case 147: return isCompletedNode(n.exprName, sourceFile); - case 166: - case 165: + case 168: case 167: - case 173: - case 174: + case 169: + case 175: + case 176: var unaryWordExpression = n; return isCompletedNode(unaryWordExpression.expression, sourceFile); - case 160: + case 162: return isCompletedNode(n.template, sourceFile); - case 172: + case 174: var lastSpan = ts.lastOrUndefined(n.templateSpans); return isCompletedNode(lastSpan, sourceFile); - case 178: + case 180: return ts.nodeIsPresent(n.literal); - case 168: - return isCompletedNode(n.operand, sourceFile); case 170: + return isCompletedNode(n.operand, sourceFile); + case 172: return isCompletedNode(n.right, sourceFile); - case 171: + case 173: return isCompletedNode(n.whenFalse, sourceFile); default: return true; @@ -27924,7 +29364,7 @@ var ts; ts.findChildOfKind = findChildOfKind; function findContainingList(node) { var syntaxList = ts.forEach(node.parent.getChildren(), function (c) { - if (c.kind === 229 && c.pos <= node.pos && c.end >= node.end) { + if (c.kind === 253 && c.pos <= node.pos && c.end >= node.end) { return c; } }); @@ -28030,7 +29470,7 @@ var ts; } } } - ts.Debug.assert(startNode !== undefined || n.kind === 228); + ts.Debug.assert(startNode !== undefined || n.kind === 230); if (children.length) { var candidate = findRightmostChildNodeWithTokens(children, children.length); return candidate && findRightmostToken(candidate); @@ -28067,17 +29507,17 @@ var ts; } ts.getNodeModifiers = getNodeModifiers; function getTypeArgumentOrTypeParameterList(node) { - if (node.kind === 142 || node.kind === 158) { + if (node.kind === 144 || node.kind === 160) { return node.typeArguments; } - if (ts.isFunctionLike(node) || node.kind === 202 || node.kind === 203) { + if (ts.isFunctionLike(node) || node.kind === 204 || node.kind === 205) { return node.typeParameters; } return undefined; } ts.getTypeArgumentOrTypeParameterList = getTypeArgumentOrTypeParameterList; function isToken(n) { - return n.kind >= 0 && n.kind <= 126; + return n.kind >= 0 && n.kind <= 127; } ts.isToken = isToken; function isWord(kind) { @@ -28130,7 +29570,7 @@ var ts; var ts; (function (ts) { function isFirstDeclarationOfSymbolParameter(symbol) { - return symbol.declarations && symbol.declarations.length > 0 && symbol.declarations[0].kind === 130; + return symbol.declarations && symbol.declarations.length > 0 && symbol.declarations[0].kind === 131; } ts.isFirstDeclarationOfSymbolParameter = isFirstDeclarationOfSymbolParameter; var displayPartWriter = getDisplayPartWriter(); @@ -28294,10 +29734,6 @@ var ts; }); } ts.signatureToDisplayParts = signatureToDisplayParts; - function isJavaScript(fileName) { - return ts.fileExtensionIs(fileName, ".js"); - } - ts.isJavaScript = isJavaScript; })(ts || (ts = {})); /// /// @@ -28519,7 +29955,7 @@ var ts; if (this.tokensAreOnSameLine === undefined) { var startLine = this.sourceFile.getLineAndCharacterOfPosition(this.currentTokenSpan.pos).line; var endLine = this.sourceFile.getLineAndCharacterOfPosition(this.nextTokenSpan.pos).line; - this.tokensAreOnSameLine = (startLine == endLine); + this.tokensAreOnSameLine = (startLine === endLine); } return this.tokensAreOnSameLine; }; @@ -28538,7 +29974,7 @@ var ts; FormattingContext.prototype.NodeIsOnOneLine = function (node) { var startLine = this.sourceFile.getLineAndCharacterOfPosition(node.getStart(this.sourceFile)).line; var endLine = this.sourceFile.getLineAndCharacterOfPosition(node.getEnd()).line; - return startLine == endLine; + return startLine === endLine; }; FormattingContext.prototype.BlockIsOnOneLine = function (node) { var openBrace = ts.findChildOfKind(node, 14, this.sourceFile); @@ -28653,7 +30089,7 @@ var ts; this.customContextChecks = funcs; } RuleOperationContext.prototype.IsAny = function () { - return this == RuleOperationContext.Any; + return this === RuleOperationContext.Any; }; RuleOperationContext.prototype.InContext = function (context) { if (this.IsAny()) { @@ -28701,7 +30137,7 @@ var ts; this.NoSpaceBeforeOpenBracket = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 18), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8)); this.NoSpaceAfterOpenBracket = new formatting.Rule(formatting.RuleDescriptor.create3(18, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8)); this.NoSpaceBeforeCloseBracket = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 19), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8)); - this.NoSpaceAfterCloseBracket = new formatting.Rule(formatting.RuleDescriptor.create3(19, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8)); + this.NoSpaceAfterCloseBracket = new formatting.Rule(formatting.RuleDescriptor.create3(19, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsNotBeforeBlockInFunctionDeclarationContext), 8)); this.FunctionOpenBraceLeftTokenRange = formatting.Shared.TokenRange.AnyIncludingMultilineComments; this.SpaceBeforeOpenBraceInFunction = new formatting.Rule(formatting.RuleDescriptor.create2(this.FunctionOpenBraceLeftTokenRange, 14), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext, Rules.IsBeforeBlockContext, Rules.IsNotFormatOnEnter, Rules.IsSameLineTokenOrBeforeMultilineBlockContext), 2), 1); this.TypeScriptOpenBraceLeftTokenRange = formatting.Shared.TokenRange.FromTokens([65, 3]); @@ -28734,12 +30170,12 @@ var ts; this.NoSpaceBetweenReturnAndSemicolon = new formatting.Rule(formatting.RuleDescriptor.create1(90, 22), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8)); this.SpaceBetweenStatements = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([17, 75, 76, 67]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsNotForContext), 2)); this.SpaceAfterTryFinally = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.FromTokens([96, 81]), 14), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 2)); - this.SpaceAfterGetSetInMember = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.FromTokens([116, 121]), 65), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext), 2)); + this.SpaceAfterGetSetInMember = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.FromTokens([116, 122]), 65), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext), 2)); this.SpaceBeforeBinaryKeywordOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.BinaryKeywordOperators), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsBinaryOpContext), 2)); this.SpaceAfterBinaryKeywordOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.BinaryKeywordOperators, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsBinaryOpContext), 2)); this.NoSpaceAfterConstructor = new formatting.Rule(formatting.RuleDescriptor.create1(114, 16), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8)); - this.NoSpaceAfterModuleImport = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.FromTokens([117, 119]), 16), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8)); - this.SpaceAfterCertainTypeScriptKeywords = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([69, 115, 77, 78, 79, 116, 102, 85, 103, 117, 118, 106, 108, 121, 109]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 2)); + this.NoSpaceAfterModuleImport = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.FromTokens([118, 120]), 16), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8)); + this.SpaceAfterCertainTypeScriptKeywords = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([69, 115, 77, 78, 79, 116, 102, 85, 103, 118, 119, 106, 108, 122, 109]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 2)); this.SpaceBeforeCertainTypeScriptKeywords = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.FromTokens([79, 102])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 2)); this.SpaceAfterModuleName = new formatting.Rule(formatting.RuleDescriptor.create1(8, 14), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsModuleDeclContext), 2)); this.SpaceAfterArrow = new formatting.Rule(formatting.RuleDescriptor.create3(32, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 2)); @@ -28753,7 +30189,11 @@ var ts; this.NoSpaceBetweenEmptyInterfaceBraceBrackets = new formatting.Rule(formatting.RuleDescriptor.create1(14, 15), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsObjectTypeContext), 8)); this.SpaceBeforeAt = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 52), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 2)); this.NoSpaceAfterAt = new formatting.Rule(formatting.RuleDescriptor.create3(52, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8)); - this.SpaceAfterDecorator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.FromTokens([65, 78, 73, 69, 109, 108, 106, 107, 116, 121, 18, 35])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsEndOfDecoratorContextOnSameLine), 2)); + this.SpaceAfterDecorator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.FromTokens([65, 78, 73, 69, 109, 108, 106, 107, 116, 122, 18, 35])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsEndOfDecoratorContextOnSameLine), 2)); + this.NoSpaceBetweenFunctionKeywordAndStar = new formatting.Rule(formatting.RuleDescriptor.create1(83, 35), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclarationOrFunctionExpressionContext), 8)); + this.SpaceAfterStarInGeneratorDeclaration = new formatting.Rule(formatting.RuleDescriptor.create3(35, formatting.Shared.TokenRange.FromTokens([65, 16])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclarationOrFunctionExpressionContext), 2)); + this.NoSpaceBetweenYieldKeywordAndStar = new formatting.Rule(formatting.RuleDescriptor.create1(110, 35), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsYieldOrYieldStarWithOperand), 8)); + this.SpaceBetweenYieldOrYieldStarAndOperand = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([110, 35]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsYieldOrYieldStarWithOperand), 2)); this.HighPriorityCommonRules = [ this.IgnoreBeforeComment, this.IgnoreAfterLineComment, @@ -28770,7 +30210,9 @@ var ts; this.NoSpaceAfterCloseBrace, this.SpaceAfterOpenBrace, this.SpaceBeforeCloseBrace, this.NewLineBeforeCloseBraceInBlockContext, this.SpaceAfterCloseBrace, this.SpaceBetweenCloseBraceAndElse, this.SpaceBetweenCloseBraceAndWhile, this.NoSpaceBetweenEmptyBraceBrackets, + this.NoSpaceBetweenFunctionKeywordAndStar, this.SpaceAfterStarInGeneratorDeclaration, this.SpaceAfterFunctionInFuncDecl, this.NewLineAfterOpenBraceInBlockContext, this.SpaceAfterGetSetInMember, + this.NoSpaceBetweenYieldKeywordAndStar, this.SpaceBetweenYieldOrYieldStarAndOperand, this.NoSpaceBetweenReturnAndSemicolon, this.SpaceAfterCertainKeywords, this.SpaceAfterLetConstInVariableDeclaration, @@ -28827,37 +30269,38 @@ var ts; } Rules.prototype.getRuleName = function (rule) { var o = this; - for (var name_25 in o) { - if (o[name_25] === rule) { - return name_25; + for (var name_26 in o) { + if (o[name_26] === rule) { + return name_26; } } throw new Error("Unknown rule"); }; Rules.IsForContext = function (context) { - return context.contextNode.kind === 187; + return context.contextNode.kind === 189; }; Rules.IsNotForContext = function (context) { return !Rules.IsForContext(context); }; Rules.IsBinaryOpContext = function (context) { switch (context.contextNode.kind) { - case 170: - case 171: + case 172: + case 173: + case 143: return true; - case 153: - case 204: - case 209: - case 199: - case 130: - case 227: + case 155: + case 206: + case 211: + case 201: + case 131: + case 229: + case 134: case 133: - case 132: return context.currentTokenSpan.kind === 53 || context.nextTokenSpan.kind === 53; - case 188: + case 190: return context.currentTokenSpan.kind === 86 || context.nextTokenSpan.kind === 86; - case 189: - return context.currentTokenSpan.kind === 126 || context.nextTokenSpan.kind === 126; + case 191: + return context.currentTokenSpan.kind === 127 || context.nextTokenSpan.kind === 127; } return false; }; @@ -28865,7 +30308,7 @@ var ts; return !Rules.IsBinaryOpContext(context); }; Rules.IsConditionalOperatorContext = function (context) { - return context.contextNode.kind === 171; + return context.contextNode.kind === 173; }; Rules.IsSameLineTokenOrBeforeMultilineBlockContext = function (context) { //// This check is mainly used inside SpaceBeforeOpenBraceInControl and SpaceBeforeOpenBraceInFunction. @@ -28906,82 +30349,85 @@ var ts; return true; } switch (node.kind) { - case 180: - case 208: - case 155: - case 207: + case 182: + case 210: + case 157: + case 209: return true; } return false; }; Rules.IsFunctionDeclContext = function (context) { switch (context.contextNode.kind) { - case 201: + case 203: + case 136: case 135: - case 134: - case 137: case 138: case 139: - case 163: - case 136: - case 164: - case 203: + case 140: + case 165: + case 137: + case 166: + case 205: return true; } return false; }; + Rules.IsFunctionDeclarationOrFunctionExpressionContext = function (context) { + return context.contextNode.kind === 203 || context.contextNode.kind === 165; + }; Rules.IsTypeScriptDeclWithBlockContext = function (context) { return Rules.NodeIsTypeScriptDeclWithBlockContext(context.contextNode); }; Rules.NodeIsTypeScriptDeclWithBlockContext = function (node) { switch (node.kind) { - case 202: - case 203: + case 204: case 205: - case 146: - case 206: + case 207: + case 148: + case 208: return true; } return false; }; Rules.IsAfterCodeBlockContext = function (context) { switch (context.currentTokenParent.kind) { - case 202: - case 206: - case 205: - case 180: - case 224: + case 204: + case 208: case 207: - case 194: + case 182: + case 226: + case 209: + case 196: return true; } return false; }; Rules.IsControlDeclContext = function (context) { switch (context.contextNode.kind) { - case 184: - case 194: - case 187: - case 188: - case 189: case 186: - case 197: - case 185: - case 193: - case 224: + case 196: + case 189: + case 190: + case 191: + case 188: + case 199: + case 187: + case 195: + case 226: return true; default: return false; } }; Rules.IsObjectContext = function (context) { - return context.contextNode.kind === 155; + return context.contextNode.kind === 157; }; Rules.IsFunctionCallContext = function (context) { - return context.contextNode.kind === 158; + return context.contextNode.kind === 160; }; Rules.IsNewContext = function (context) { - return context.contextNode.kind === 159; + return context.contextNode.kind === 161; }; Rules.IsFunctionCallOrNewContext = function (context) { return Rules.IsFunctionCallContext(context) || Rules.IsNewContext(context); @@ -28992,6 +30438,9 @@ var ts; Rules.IsSameLineTokenContext = function (context) { return context.TokensAreOnSameLine(); }; + Rules.IsNotBeforeBlockInFunctionDeclarationContext = function (context) { + return !Rules.IsFunctionDeclContext(context) && !Rules.IsBeforeBlockContext(context); + }; Rules.IsEndOfDecoratorContextOnSameLine = function (context) { return context.TokensAreOnSameLine() && context.contextNode.decorators && @@ -29002,38 +30451,38 @@ var ts; while (ts.isExpression(node)) { node = node.parent; } - return node.kind === 131; + return node.kind === 132; }; Rules.IsStartOfVariableDeclarationList = function (context) { - return context.currentTokenParent.kind === 200 && + return context.currentTokenParent.kind === 202 && context.currentTokenParent.getStart(context.sourceFile) === context.currentTokenSpan.pos; }; Rules.IsNotFormatOnEnter = function (context) { - return context.formattingRequestKind != 2; + return context.formattingRequestKind !== 2; }; Rules.IsModuleDeclContext = function (context) { - return context.contextNode.kind === 206; + return context.contextNode.kind === 208; }; Rules.IsObjectTypeContext = function (context) { - return context.contextNode.kind === 146; + return context.contextNode.kind === 148; }; Rules.IsTypeArgumentOrParameter = function (token, parent) { if (token.kind !== 24 && token.kind !== 25) { return false; } switch (parent.kind) { - case 142: - case 202: + case 144: + case 204: + case 205: case 203: - case 201: - case 163: - case 164: + case 165: + case 166: + case 136: case 135: - case 134: - case 139: case 140: - case 158: - case 159: + case 141: + case 160: + case 161: return true; default: return false; @@ -29044,7 +30493,10 @@ var ts; Rules.IsTypeArgumentOrParameter(context.nextTokenSpan, context.nextTokenParent); }; Rules.IsVoidOpContext = function (context) { - return context.currentTokenSpan.kind === 99 && context.currentTokenParent.kind === 167; + return context.currentTokenSpan.kind === 99 && context.currentTokenParent.kind === 169; + }; + Rules.IsYieldOrYieldStarWithOperand = function (context) { + return context.contextNode.kind === 175 && context.contextNode.expression !== undefined; }; return Rules; })(); @@ -29067,7 +30519,7 @@ var ts; return result; }; RulesMap.prototype.Initialize = function (rules) { - this.mapRowLength = 126 + 1; + this.mapRowLength = 127 + 1; this.map = new Array(this.mapRowLength * this.mapRowLength); var rulesBucketConstructionStateList = new Array(this.map.length); this.FillRules(rules, rulesBucketConstructionStateList); @@ -29085,13 +30537,13 @@ var ts; }; RulesMap.prototype.FillRule = function (rule, rulesBucketConstructionStateList) { var _this = this; - var specificRule = rule.Descriptor.LeftTokenRange != formatting.Shared.TokenRange.Any && - rule.Descriptor.RightTokenRange != formatting.Shared.TokenRange.Any; + var specificRule = rule.Descriptor.LeftTokenRange !== formatting.Shared.TokenRange.Any && + rule.Descriptor.RightTokenRange !== formatting.Shared.TokenRange.Any; rule.Descriptor.LeftTokenRange.GetTokens().forEach(function (left) { rule.Descriptor.RightTokenRange.GetTokens().forEach(function (right) { var rulesBucketIndex = _this.GetRuleBucketIndex(left, right); var rulesBucket = _this.map[rulesBucketIndex]; - if (rulesBucket == undefined) { + if (rulesBucket === undefined) { rulesBucket = _this.map[rulesBucketIndex] = new RulesBucket(); } rulesBucket.AddRule(rule, specificRule, rulesBucketConstructionStateList, rulesBucketIndex); @@ -29143,7 +30595,7 @@ var ts; RulesBucketConstructionState.prototype.IncreaseInsertionIndex = function (maskPosition) { var value = (this.rulesInsertionIndexBitmap >> maskPosition) & Mask; value++; - ts.Debug.assert((value & Mask) == value, "Adding more rules into the sub-bucket than allowed. Maximum allowed is 32 rules."); + ts.Debug.assert((value & Mask) === value, "Adding more rules into the sub-bucket than allowed. Maximum allowed is 32 rules."); var temp = this.rulesInsertionIndexBitmap & ~(Mask << maskPosition); temp |= value << maskPosition; this.rulesInsertionIndexBitmap = temp; @@ -29160,7 +30612,7 @@ var ts; }; RulesBucket.prototype.AddRule = function (rule, specificTokens, constructionState, rulesBucketIndex) { var position; - if (rule.Operation.Action == 1) { + if (rule.Operation.Action === 1) { position = specificTokens ? RulesPosition.IgnoreRulesSpecific : RulesPosition.IgnoreRulesAny; @@ -29234,7 +30686,7 @@ var ts; return [this.token]; }; TokenSingleValueAccess.prototype.Contains = function (tokenValue) { - return tokenValue == this.token; + return tokenValue === this.token; }; return TokenSingleValueAccess; })(); @@ -29244,7 +30696,7 @@ var ts; } TokenAllAccess.prototype.GetTokens = function () { var result = []; - for (var token = 0; token <= 126; token++) { + for (var token = 0; token <= 127; token++) { result.push(token); } return result; @@ -29286,9 +30738,9 @@ var ts; }; TokenRange.Any = TokenRange.AllTokens(); TokenRange.AnyIncludingMultilineComments = TokenRange.FromTokens(TokenRange.Any.GetTokens().concat([3])); - TokenRange.Keywords = TokenRange.FromRange(66, 126); + TokenRange.Keywords = TokenRange.FromRange(66, 127); TokenRange.BinaryOperators = TokenRange.FromRange(24, 64); - TokenRange.BinaryKeywordOperators = TokenRange.FromTokens([86, 87, 126]); + TokenRange.BinaryKeywordOperators = TokenRange.FromTokens([86, 87, 127, 117]); TokenRange.UnaryPrefixOperators = TokenRange.FromTokens([38, 39, 47, 46]); TokenRange.UnaryPrefixExpressions = TokenRange.FromTokens([7, 65, 16, 18, 14, 93, 88]); TokenRange.UnaryPreincrementExpressions = TokenRange.FromTokens([65, 16, 93, 88]); @@ -29296,7 +30748,7 @@ var ts; TokenRange.UnaryPredecrementExpressions = TokenRange.FromTokens([65, 16, 93, 88]); TokenRange.UnaryPostdecrementExpressions = TokenRange.FromTokens([65, 17, 19, 88]); TokenRange.Comments = TokenRange.FromTokens([2, 3]); - TokenRange.TypeNames = TokenRange.FromTokens([65, 120, 122, 113, 123, 99, 112]); + TokenRange.TypeNames = TokenRange.FromTokens([65, 121, 123, 113, 124, 99, 112]); return TokenRange; })(); Shared.TokenRange = TokenRange; @@ -29474,17 +30926,17 @@ var ts; } function isListElement(parent, node) { switch (parent.kind) { - case 202: - case 203: + case 204: + case 205: return ts.rangeContainsRange(parent.members, node); - case 206: + case 208: var body = parent.body; - return body && body.kind === 180 && ts.rangeContainsRange(body.statements, node); - case 228: - case 180: - case 207: + return body && body.kind === 182 && ts.rangeContainsRange(body.statements, node); + case 230: + case 182: + case 209: return ts.rangeContainsRange(parent.statements, node); - case 224: + case 226: return ts.rangeContainsRange(parent.block.statements, node); } return false; @@ -29609,9 +31061,9 @@ var ts; if (indentation === -1) { if (isSomeBlock(node.kind)) { if (isSomeBlock(parent.kind) || - parent.kind === 228 || - parent.kind === 221 || - parent.kind === 222) { + parent.kind === 230 || + parent.kind === 223 || + parent.kind === 224) { indentation = parentDynamicIndentation.getIndentation() + parentDynamicIndentation.getDelta(); } else { @@ -29644,18 +31096,18 @@ var ts; return node.modifiers[0].kind; } switch (node.kind) { - case 202: return 69; - case 203: return 103; - case 201: return 83; - case 205: return 205; - case 137: return 116; - case 138: return 121; - case 135: + case 204: return 69; + case 205: return 103; + case 203: return 83; + case 207: return 207; + case 138: return 116; + case 139: return 122; + case 136: if (node.asteriskToken) { return 35; } - case 133: - case 130: + case 134: + case 131: return node.name.kind; } } @@ -29762,7 +31214,7 @@ var ts; consumeTokenAndAdvanceScanner(tokenInfo, node, parentDynamicIndentation); return inheritedIndentation; } - var effectiveParentStartLine = child.kind === 131 ? childStartLine : undecoratedParentStartLine; + var effectiveParentStartLine = child.kind === 132 ? childStartLine : undecoratedParentStartLine; var childIndentation = computeIndentation(child, childStartLine, childIndentationAmount, node, parentDynamicIndentation, effectiveParentStartLine); processNode(child, childContextNode, childStartLine, undecoratedChildStartLine, childIndentation.indentation, childIndentation.delta); childContextNode = node; @@ -30052,20 +31504,20 @@ var ts; } function isSomeBlock(kind) { switch (kind) { - case 180: - case 207: + case 182: + case 209: return true; } return false; } function getOpenTokenForList(node, list) { switch (node.kind) { + case 137: + case 203: + case 165: case 136: - case 201: - case 163: case 135: - case 134: - case 164: + case 166: if (node.typeParameters === list) { return 24; } @@ -30073,8 +31525,8 @@ var ts; return 16; } break; - case 158: - case 159: + case 160: + case 161: if (node.typeArguments === list) { return 24; } @@ -30082,7 +31534,7 @@ var ts; return 16; } break; - case 142: + case 144: if (node.typeArguments === list) { return 24; } @@ -30174,7 +31626,7 @@ var ts; return 0; } var lineAtPosition = sourceFile.getLineAndCharacterOfPosition(position).line; - if (precedingToken.kind === 23 && precedingToken.parent.kind !== 170) { + if (precedingToken.kind === 23 && precedingToken.parent.kind !== 172) { var actualIndentation = getActualIndentationForListItemBeforeComma(precedingToken, sourceFile, options); if (actualIndentation !== -1) { return actualIndentation; @@ -30264,7 +31716,7 @@ var ts; } function getActualIndentationForNode(current, parent, currentLineAndChar, parentAndChildShareLine, sourceFile, options) { var useActualIndentation = (ts.isDeclaration(current) || ts.isStatement(current)) && - (parent.kind === 228 || !parentAndChildShareLine); + (parent.kind === 230 || !parentAndChildShareLine); if (!useActualIndentation) { return -1; } @@ -30288,7 +31740,7 @@ var ts; return sourceFile.getLineAndCharacterOfPosition(n.getStart(sourceFile)); } function childStartsOnTheSameLineWithElseInIfStatement(parent, child, childStartLine, sourceFile) { - if (parent.kind === 184 && parent.elseStatement === child) { + if (parent.kind === 186 && parent.elseStatement === child) { var elseKeyword = ts.findChildOfKind(parent, 76, sourceFile); ts.Debug.assert(elseKeyword !== undefined); var elseKeywordStartLine = getStartLineAndCharacterForNode(elseKeyword, sourceFile).line; @@ -30300,23 +31752,23 @@ var ts; function getContainingList(node, sourceFile) { if (node.parent) { switch (node.parent.kind) { - case 142: + case 144: if (node.parent.typeArguments && ts.rangeContainsStartEnd(node.parent.typeArguments, node.getStart(sourceFile), node.getEnd())) { return node.parent.typeArguments; } break; - case 155: + case 157: return node.parent.properties; - case 154: + case 156: return node.parent.elements; - case 201: - case 163: - case 164: + case 203: + case 165: + case 166: + case 136: case 135: - case 134: - case 139: - case 140: { + case 140: + case 141: { var start = node.getStart(sourceFile); if (node.parent.typeParameters && ts.rangeContainsStartEnd(node.parent.typeParameters, start, node.getEnd())) { @@ -30327,8 +31779,8 @@ var ts; } break; } - case 159: - case 158: { + case 161: + case 160: { var start = node.getStart(sourceFile); if (node.parent.typeArguments && ts.rangeContainsStartEnd(node.parent.typeArguments, start, node.getEnd())) { @@ -30397,28 +31849,28 @@ var ts; SmartIndenter.findFirstNonWhitespaceColumn = findFirstNonWhitespaceColumn; function nodeContentIsAlwaysIndented(kind) { switch (kind) { - case 202: - case 203: + case 204: case 205: - case 154: - case 180: case 207: - case 155: - case 146: + case 156: + case 182: + case 209: + case 157: case 148: - case 208: - case 222: - case 221: - case 162: - case 158: - case 159: - case 181: - case 199: - case 215: - case 192: - case 171: - case 152: - case 151: + case 150: + case 210: + case 224: + case 223: + case 164: + case 160: + case 161: + case 183: + case 201: + case 217: + case 194: + case 173: + case 154: + case 153: return true; } return false; @@ -30428,22 +31880,22 @@ var ts; return true; } switch (parent) { - case 185: - case 186: - case 188: - case 189: case 187: - case 184: - case 201: - case 163: - case 135: - case 134: - case 139: - case 164: + case 188: + case 190: + case 191: + case 189: + case 186: + case 203: + case 165: case 136: + case 135: + case 140: + case 166: case 137: case 138: - return child !== 180; + case 139: + return child !== 182; default: return false; } @@ -30456,8 +31908,7 @@ var ts; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; /// /// @@ -30523,7 +31974,7 @@ var ts; return this.getEnd() - this.getStart(sourceFile); }; NodeObject.prototype.getFullWidth = function () { - return this.end - this.getFullStart(); + return this.end - this.pos; }; NodeObject.prototype.getLeadingTriviaWidth = function (sourceFile) { return this.getStart(sourceFile) - this.pos; @@ -30545,7 +31996,7 @@ var ts; return pos; }; NodeObject.prototype.createSyntaxList = function (nodes) { - var list = createNode(229, nodes.pos, nodes.end, 1024, this); + var list = createNode(253, nodes.pos, nodes.end, 1024, this); list._children = []; var pos = nodes.pos; for (var _i = 0; _i < nodes.length; _i++) { @@ -30564,7 +32015,7 @@ var ts; NodeObject.prototype.createChildren = function (sourceFile) { var _this = this; var children; - if (this.kind >= 127) { + if (this.kind >= 128) { scanner.setText((sourceFile || this.getSourceFile()).text); children = []; var pos = this.pos; @@ -30609,7 +32060,7 @@ var ts; var children = this.getChildren(); for (var _i = 0; _i < children.length; _i++) { var child = children[_i]; - if (child.kind < 127) { + if (child.kind < 128) { return child; } return child.getFirstToken(sourceFile); @@ -30619,7 +32070,7 @@ var ts; var children = this.getChildren(sourceFile); for (var i = children.length - 1; i >= 0; i--) { var child = children[i]; - if (child.kind < 127) { + if (child.kind < 128) { return child; } return child.getLastToken(sourceFile); @@ -30665,7 +32116,7 @@ var ts; ts.forEach(declarations, function (declaration, indexOfDeclaration) { if (ts.indexOf(declarations, declaration) === indexOfDeclaration) { var sourceFileOfDeclaration = ts.getSourceFileOfNode(declaration); - if (canUseParsedParamTagComments && declaration.kind === 130) { + if (canUseParsedParamTagComments && declaration.kind === 131) { ts.forEach(getJsDocCommentTextRange(declaration.parent, sourceFileOfDeclaration), function (jsDocCommentTextRange) { var cleanedParamJsDocComment = getCleanedParamJsDocComment(jsDocCommentTextRange.pos, jsDocCommentTextRange.end, sourceFileOfDeclaration); if (cleanedParamJsDocComment) { @@ -30673,13 +32124,13 @@ var ts; } }); } - if (declaration.kind === 206 && declaration.body.kind === 206) { + if (declaration.kind === 208 && declaration.body.kind === 208) { return; } - while (declaration.kind === 206 && declaration.parent.kind === 206) { + while (declaration.kind === 208 && declaration.parent.kind === 208) { declaration = declaration.parent; } - ts.forEach(getJsDocCommentTextRange(declaration.kind === 199 ? declaration.parent.parent : declaration, sourceFileOfDeclaration), function (jsDocCommentTextRange) { + ts.forEach(getJsDocCommentTextRange(declaration.kind === 201 ? declaration.parent.parent : declaration, sourceFileOfDeclaration), function (jsDocCommentTextRange) { var cleanedJsDocComment = getCleanedJsDocComment(jsDocCommentTextRange.pos, jsDocCommentTextRange.end, sourceFileOfDeclaration); if (cleanedJsDocComment) { jsDocCommentParts.push.apply(jsDocCommentParts, cleanedJsDocComment); @@ -30984,9 +32435,9 @@ var ts; if (result_2 !== undefined) { return result_2; } - if (declaration.name.kind === 128) { + if (declaration.name.kind === 129) { var expr = declaration.name.expression; - if (expr.kind === 156) { + if (expr.kind === 158) { return expr.name.text; } return getTextOfIdentifierOrLiteral(expr); @@ -31006,9 +32457,9 @@ var ts; } function visit(node) { switch (node.kind) { - case 201: + case 203: + case 136: case 135: - case 134: var functionDeclaration = node; var declarationName = getDeclarationName(functionDeclaration); if (declarationName) { @@ -31025,62 +32476,62 @@ var ts; ts.forEachChild(node, visit); } break; - case 202: - case 203: case 204: case 205: case 206: - case 209: - case 218: - case 214: - case 209: - case 211: - case 212: - case 137: - case 138: - case 146: - addDeclaration(node); - case 136: - case 181: - case 200: - case 151: - case 152: case 207: + case 208: + case 211: + case 220: + case 216: + case 211: + case 213: + case 214: + case 138: + case 139: + case 148: + addDeclaration(node); + case 137: + case 183: + case 202: + case 153: + case 154: + case 209: ts.forEachChild(node, visit); break; - case 180: + case 182: if (ts.isFunctionBlock(node)) { ts.forEachChild(node, visit); } break; - case 130: + case 131: if (!(node.flags & 112)) { break; } - case 199: - case 153: + case 201: + case 155: if (ts.isBindingPattern(node.name)) { ts.forEachChild(node.name, visit); break; } - case 227: + case 229: + case 134: case 133: - case 132: addDeclaration(node); break; - case 216: + case 218: if (node.exportClause) { ts.forEach(node.exportClause.elements, visit); } break; - case 210: + case 212: var importClause = node.importClause; if (importClause) { if (importClause.name) { addDeclaration(importClause); } if (importClause.namedBindings) { - if (importClause.namedBindings.kind === 212) { + if (importClause.namedBindings.kind === 214) { addDeclaration(importClause.namedBindings); } else { @@ -31204,6 +32655,7 @@ var ts; ClassificationTypeNames.typeParameterName = "type parameter name"; ClassificationTypeNames.typeAliasName = "type alias name"; ClassificationTypeNames.parameterName = "parameter name"; + ClassificationTypeNames.docCommentTagName = "doc comment tag name"; return ClassificationTypeNames; })(); ts.ClassificationTypeNames = ClassificationTypeNames; @@ -31219,14 +32671,14 @@ var ts; return false; } return ts.forEach(symbol.declarations, function (declaration) { - if (declaration.kind === 163) { + if (declaration.kind === 165) { return true; } - if (declaration.kind !== 199 && declaration.kind !== 201) { + if (declaration.kind !== 201 && declaration.kind !== 203) { return false; } - for (var parent_7 = declaration.parent; !ts.isFunctionBlock(parent_7); parent_7 = parent_7.parent) { - if (parent_7.kind === 228 || parent_7.kind === 207) { + for (var parent_9 = declaration.parent; !ts.isFunctionBlock(parent_9); parent_9 = parent_9.parent) { + if (parent_9.kind === 230 || parent_9.kind === 209) { return false; } } @@ -31265,8 +32717,7 @@ var ts; var HostCache = (function () { function HostCache(host, getCanonicalFileName) { this.host = host; - this.getCanonicalFileName = getCanonicalFileName; - this.fileNameToEntry = {}; + this.fileNameToEntry = ts.createFileMap(getCanonicalFileName); var rootFileNames = host.getScriptFileNames(); for (var _i = 0; _i < rootFileNames.length; _i++) { var fileName = rootFileNames[_i]; @@ -31277,9 +32728,6 @@ var ts; HostCache.prototype.compilationSettings = function () { return this._compilationSettings; }; - HostCache.prototype.normalizeFileName = function (fileName) { - return this.getCanonicalFileName(ts.normalizeSlashes(fileName)); - }; HostCache.prototype.createEntry = function (fileName) { var entry; var scriptSnapshot = this.host.getScriptSnapshot(fileName); @@ -31290,13 +32738,14 @@ var ts; scriptSnapshot: scriptSnapshot }; } - return this.fileNameToEntry[this.normalizeFileName(fileName)] = entry; + this.fileNameToEntry.set(fileName, entry); + return entry; }; HostCache.prototype.getEntry = function (fileName) { - return ts.lookUp(this.fileNameToEntry, this.normalizeFileName(fileName)); + return this.fileNameToEntry.get(fileName); }; HostCache.prototype.contains = function (fileName) { - return ts.hasProperty(this.fileNameToEntry, this.normalizeFileName(fileName)); + return this.fileNameToEntry.contains(fileName); }; HostCache.prototype.getOrCreateEntry = function (fileName) { if (this.contains(fileName)) { @@ -31305,12 +32754,10 @@ var ts; return this.createEntry(fileName); }; HostCache.prototype.getRootFileNames = function () { - var _this = this; var fileNames = []; - ts.forEachKey(this.fileNameToEntry, function (key) { - var entry = _this.getEntry(key); - if (entry) { - fileNames.push(entry.hostFileName); + this.fileNameToEntry.forEachValue(function (value) { + if (value) { + fileNames.push(value.hostFileName); } }); return fileNames; @@ -31357,15 +32804,18 @@ var ts; sourceFile.version = version; sourceFile.scriptSnapshot = scriptSnapshot; } - function transpile(input, compilerOptions, fileName, diagnostics) { + function transpile(input, compilerOptions, fileName, diagnostics, moduleName) { var options = compilerOptions ? ts.clone(compilerOptions) : getDefaultCompilerOptions(); - options.separateCompilation = true; + options.isolatedModules = true; options.allowNonTsExtensions = true; + options.noLib = true; + options.noResolve = true; var inputFileName = fileName || "module.ts"; var sourceFile = ts.createSourceFile(inputFileName, input, options.target); - if (diagnostics && sourceFile.parseDiagnostics) { - diagnostics.push.apply(diagnostics, sourceFile.parseDiagnostics); + if (moduleName) { + sourceFile.moduleName = moduleName; } + var newLine = ts.getNewLineCharacter(options); var outputText; var compilerHost = { getSourceFile: function (fileName, target) { return fileName === inputFileName ? sourceFile : undefined; }, @@ -31377,19 +32827,19 @@ var ts; useCaseSensitiveFileNames: function () { return false; }, getCanonicalFileName: function (fileName) { return fileName; }, getCurrentDirectory: function () { return ""; }, - getNewLine: function () { return (ts.sys && ts.sys.newLine) || "\r\n"; } + getNewLine: function () { return newLine; } }; var program = ts.createProgram([inputFileName], options, compilerHost); - if (diagnostics) { - diagnostics.push.apply(diagnostics, program.getGlobalDiagnostics()); - } + ts.addRange(diagnostics, program.getSyntacticDiagnostics(sourceFile)); + ts.addRange(diagnostics, program.getOptionsDiagnostics()); program.emit(); ts.Debug.assert(outputText !== undefined, "Output generation failed"); return outputText; } ts.transpile = transpile; function createLanguageServiceSourceFile(fileName, scriptSnapshot, scriptTarget, version, setNodeParents) { - var sourceFile = ts.createSourceFile(fileName, scriptSnapshot.getText(0, scriptSnapshot.getLength()), scriptTarget, setNodeParents); + var text = scriptSnapshot.getText(0, scriptSnapshot.getLength()); + var sourceFile = ts.createSourceFile(fileName, text, scriptTarget, setNodeParents); setSourceFileFields(sourceFile, scriptSnapshot, version); sourceFile.nameTable = sourceFile.identifiers; return sourceFile; @@ -31400,7 +32850,25 @@ var ts; if (textChangeRange) { if (version !== sourceFile.version) { if (!ts.disableIncrementalParsing) { - var newSourceFile = ts.updateSourceFile(sourceFile, scriptSnapshot.getText(0, scriptSnapshot.getLength()), textChangeRange, aggressiveChecks); + var newText; + var prefix = textChangeRange.span.start !== 0 + ? sourceFile.text.substr(0, textChangeRange.span.start) + : ""; + var suffix = ts.textSpanEnd(textChangeRange.span) !== sourceFile.text.length + ? sourceFile.text.substr(ts.textSpanEnd(textChangeRange.span)) + : ""; + if (textChangeRange.newLength === 0) { + newText = prefix && suffix ? prefix + suffix : prefix || suffix; + } + else { + var changedText = scriptSnapshot.getText(textChangeRange.span.start, textChangeRange.span.start + textChangeRange.newLength); + newText = prefix && suffix + ? prefix + changedText + suffix + : prefix + ? (prefix + changedText) + : (changedText + suffix); + } + var newSourceFile = ts.updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks); setSourceFileFields(newSourceFile, scriptSnapshot, version); newSourceFile.nameTable = undefined; return newSourceFile; @@ -31410,8 +32878,14 @@ var ts; return createLanguageServiceSourceFile(sourceFile.fileName, scriptSnapshot, sourceFile.languageVersion, version, true); } ts.updateLanguageServiceSourceFile = updateLanguageServiceSourceFile; - function createDocumentRegistry() { + function createGetCanonicalFileName(useCaseSensitivefileNames) { + return useCaseSensitivefileNames + ? (function (fileName) { return fileName; }) + : (function (fileName) { return fileName.toLowerCase(); }); + } + function createDocumentRegistry(useCaseSensitiveFileNames) { var buckets = {}; + var getCanonicalFileName = createGetCanonicalFileName(!!useCaseSensitiveFileNames); function getKeyFromCompilationSettings(settings) { return "_" + settings.target; } @@ -31419,7 +32893,7 @@ var ts; var key = getKeyFromCompilationSettings(settings); var bucket = ts.lookUp(buckets, key); if (!bucket && createIfMissing) { - buckets[key] = bucket = {}; + buckets[key] = bucket = ts.createFileMap(getCanonicalFileName); } return bucket; } @@ -31428,7 +32902,7 @@ var ts; var entries = ts.lookUp(buckets, name); var sourceFiles = []; for (var i in entries) { - var entry = entries[i]; + var entry = entries.get(i); sourceFiles.push({ name: i, refCount: entry.languageServiceRefCount, @@ -31451,15 +32925,16 @@ var ts; } function acquireOrUpdateDocument(fileName, compilationSettings, scriptSnapshot, version, acquiring) { var bucket = getBucketForCompilationSettings(compilationSettings, true); - var entry = ts.lookUp(bucket, fileName); + var entry = bucket.get(fileName); if (!entry) { ts.Debug.assert(acquiring, "How could we be trying to update a document that the registry doesn't have?"); var sourceFile = createLanguageServiceSourceFile(fileName, scriptSnapshot, compilationSettings.target, version, false); - bucket[fileName] = entry = { + entry = { sourceFile: sourceFile, languageServiceRefCount: 0, owners: [] }; + bucket.set(fileName, entry); } else { if (entry.sourceFile.version !== version) { @@ -31474,11 +32949,11 @@ var ts; function releaseDocument(fileName, compilationSettings) { var bucket = getBucketForCompilationSettings(compilationSettings, false); ts.Debug.assert(bucket !== undefined); - var entry = ts.lookUp(bucket, fileName); + var entry = bucket.get(fileName); entry.languageServiceRefCount--; ts.Debug.assert(entry.languageServiceRefCount >= 0); if (entry.languageServiceRefCount === 0) { - delete bucket[fileName]; + bucket.remove(fileName); } } return { @@ -31530,7 +33005,7 @@ var ts; else { if (token === 65) { token = scanner.scan(); - if (token === 125) { + if (token === 126) { token = scanner.scan(); if (token === 8) { recordModuleName(); @@ -31539,7 +33014,7 @@ var ts; } else if (token === 53) { token = scanner.scan(); - if (token === 119) { + if (token === 120) { token = scanner.scan(); if (token === 16) { token = scanner.scan(); @@ -31564,7 +33039,7 @@ var ts; } if (token === 15) { token = scanner.scan(); - if (token === 125) { + if (token === 126) { token = scanner.scan(); if (token === 8) { recordModuleName(); @@ -31578,7 +33053,7 @@ var ts; token = scanner.scan(); if (token === 65) { token = scanner.scan(); - if (token === 125) { + if (token === 126) { token = scanner.scan(); if (token === 8) { recordModuleName(); @@ -31598,7 +33073,7 @@ var ts; } if (token === 15) { token = scanner.scan(); - if (token === 125) { + if (token === 126) { token = scanner.scan(); if (token === 8) { recordModuleName(); @@ -31608,7 +33083,7 @@ var ts; } else if (token === 35) { token = scanner.scan(); - if (token === 125) { + if (token === 126) { token = scanner.scan(); if (token === 8) { recordModuleName(); @@ -31629,7 +33104,7 @@ var ts; ts.preProcessFile = preProcessFile; function getTargetLabel(referenceNode, labelName) { while (referenceNode) { - if (referenceNode.kind === 195 && referenceNode.label.text === labelName) { + if (referenceNode.kind === 197 && referenceNode.label.text === labelName) { return referenceNode.label; } referenceNode = referenceNode.parent; @@ -31638,16 +33113,16 @@ var ts; } function isJumpStatementTarget(node) { return node.kind === 65 && - (node.parent.kind === 191 || node.parent.kind === 190) && + (node.parent.kind === 193 || node.parent.kind === 192) && node.parent.label === node; } function isLabelOfLabeledStatement(node) { return node.kind === 65 && - node.parent.kind === 195 && + node.parent.kind === 197 && node.parent.label === node; } function isLabeledBy(node, labelName) { - for (var owner = node.parent; owner.kind === 195; owner = owner.parent) { + for (var owner = node.parent; owner.kind === 197; owner = owner.parent) { if (owner.label.text === labelName) { return true; } @@ -31658,25 +33133,25 @@ var ts; return isLabelOfLabeledStatement(node) || isJumpStatementTarget(node); } function isRightSideOfQualifiedName(node) { - return node.parent.kind === 127 && node.parent.right === node; + return node.parent.kind === 128 && node.parent.right === node; } function isRightSideOfPropertyAccess(node) { - return node && node.parent && node.parent.kind === 156 && node.parent.name === node; + return node && node.parent && node.parent.kind === 158 && node.parent.name === node; } function isCallExpressionTarget(node) { if (isRightSideOfPropertyAccess(node)) { node = node.parent; } - return node && node.parent && node.parent.kind === 158 && node.parent.expression === node; + return node && node.parent && node.parent.kind === 160 && node.parent.expression === node; } function isNewExpressionTarget(node) { if (isRightSideOfPropertyAccess(node)) { node = node.parent; } - return node && node.parent && node.parent.kind === 159 && node.parent.expression === node; + return node && node.parent && node.parent.kind === 161 && node.parent.expression === node; } function isNameOfModuleDeclaration(node) { - return node.parent.kind === 206 && node.parent.name === node; + return node.parent.kind === 208 && node.parent.name === node; } function isNameOfFunctionDeclaration(node) { return node.kind === 65 && @@ -31684,22 +33159,22 @@ var ts; } function isNameOfPropertyAssignment(node) { return (node.kind === 65 || node.kind === 8 || node.kind === 7) && - (node.parent.kind === 225 || node.parent.kind === 226) && node.parent.name === node; + (node.parent.kind === 227 || node.parent.kind === 228) && node.parent.name === node; } function isLiteralNameOfPropertyDeclarationOrIndexAccess(node) { if (node.kind === 8 || node.kind === 7) { switch (node.parent.kind) { - case 133: - case 132: - case 225: - case 227: - case 135: case 134: - case 137: + case 133: + case 227: + case 229: + case 136: + case 135: case 138: - case 206: + case 139: + case 208: return node.parent.name === node; - case 157: + case 159: return node.parent.argumentExpression === node; } } @@ -31737,7 +33212,7 @@ var ts; } } var keywordCompletions = []; - for (var i = 66; i <= 126; i++) { + for (var i = 66; i <= 127; i++) { keywordCompletions.push({ name: ts.tokenToString(i), kind: ScriptElementKind.keyword, @@ -31752,17 +33227,17 @@ var ts; return undefined; } switch (node.kind) { - case 228: + case 230: + case 136: case 135: - case 134: - case 201: - case 163: - case 137: - case 138: - case 202: case 203: + case 165: + case 138: + case 139: + case 204: case 205: - case 206: + case 207: + case 208: return node; } } @@ -31770,38 +33245,38 @@ var ts; ts.getContainerNode = getContainerNode; function getNodeKind(node) { switch (node.kind) { - case 206: return ScriptElementKind.moduleElement; - case 202: return ScriptElementKind.classElement; - case 203: return ScriptElementKind.interfaceElement; - case 204: return ScriptElementKind.typeElement; - case 205: return ScriptElementKind.enumElement; - case 199: + case 208: return ScriptElementKind.moduleElement; + case 204: return ScriptElementKind.classElement; + case 205: return ScriptElementKind.interfaceElement; + case 206: return ScriptElementKind.typeElement; + case 207: return ScriptElementKind.enumElement; + case 201: return ts.isConst(node) ? ScriptElementKind.constElement : ts.isLet(node) ? ScriptElementKind.letElement : ScriptElementKind.variableElement; - case 201: return ScriptElementKind.functionElement; - case 137: return ScriptElementKind.memberGetAccessorElement; - case 138: return ScriptElementKind.memberSetAccessorElement; + case 203: return ScriptElementKind.functionElement; + case 138: return ScriptElementKind.memberGetAccessorElement; + case 139: return ScriptElementKind.memberSetAccessorElement; + case 136: case 135: - case 134: return ScriptElementKind.memberFunctionElement; + case 134: case 133: - case 132: return ScriptElementKind.memberVariableElement; - case 141: return ScriptElementKind.indexSignatureElement; - case 140: return ScriptElementKind.constructSignatureElement; - case 139: return ScriptElementKind.callSignatureElement; - case 136: return ScriptElementKind.constructorImplementationElement; - case 129: return ScriptElementKind.typeParameterElement; - case 227: return ScriptElementKind.variableElement; - case 130: return (node.flags & 112) ? ScriptElementKind.memberVariableElement : ScriptElementKind.parameterElement; - case 209: - case 214: + case 142: return ScriptElementKind.indexSignatureElement; + case 141: return ScriptElementKind.constructSignatureElement; + case 140: return ScriptElementKind.callSignatureElement; + case 137: return ScriptElementKind.constructorImplementationElement; + case 130: return ScriptElementKind.typeParameterElement; + case 229: return ScriptElementKind.variableElement; + case 131: return (node.flags & 112) ? ScriptElementKind.memberVariableElement : ScriptElementKind.parameterElement; case 211: - case 218: - case 212: + case 216: + case 213: + case 220: + case 214: return ScriptElementKind.alias; } return ScriptElementKind.unknown; @@ -31823,9 +33298,7 @@ var ts; host.log(message); } } - function getCanonicalFileName(fileName) { - return useCaseSensitivefileNames ? fileName : fileName.toLowerCase(); - } + var getCanonicalFileName = createGetCanonicalFileName(useCaseSensitivefileNames); function getValidSourceFile(fileName) { fileName = ts.normalizeSlashes(fileName); var sourceFile = program.getSourceFile(getCanonicalFileName(fileName)); @@ -31878,10 +33351,12 @@ var ts; } } } + hostCache = undefined; program = newProgram; program.getTypeChecker(); return; function getOrCreateSourceFile(fileName) { + ts.Debug.assert(hostCache !== undefined); var hostFileInformation = hostCache.getOrCreateEntry(fileName); if (!hostFileInformation) { return undefined; @@ -31953,44 +33428,44 @@ var ts; return false; } switch (node.kind) { - case 209: + case 211: diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.import_can_only_be_used_in_a_ts_file)); return true; - case 215: + case 217: diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.export_can_only_be_used_in_a_ts_file)); return true; - case 202: + case 204: var classDeclaration = node; if (checkModifiers(classDeclaration.modifiers) || checkTypeParameters(classDeclaration.typeParameters)) { return true; } break; - case 223: + case 225: var heritageClause = node; if (heritageClause.token === 102) { diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.implements_clauses_can_only_be_used_in_a_ts_file)); return true; } break; - case 203: + case 205: diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.interface_declarations_can_only_be_used_in_a_ts_file)); return true; - case 206: + case 208: diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.module_declarations_can_only_be_used_in_a_ts_file)); return true; - case 204: + case 206: diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.type_aliases_can_only_be_used_in_a_ts_file)); return true; - case 135: - case 134: case 136: + case 135: case 137: case 138: - case 163: - case 201: - case 164: - case 201: + case 139: + case 165: + case 203: + case 166: + case 203: var functionDeclaration = node; if (checkModifiers(functionDeclaration.modifiers) || checkTypeParameters(functionDeclaration.typeParameters) || @@ -31998,20 +33473,20 @@ var ts; return true; } break; - case 181: + case 183: var variableStatement = node; if (checkModifiers(variableStatement.modifiers)) { return true; } break; - case 199: + case 201: var variableDeclaration = node; if (checkTypeAnnotation(variableDeclaration.type)) { return true; } break; - case 158: - case 159: + case 160: + case 161: var expression = node; if (expression.typeArguments && expression.typeArguments.length > 0) { var start = expression.typeArguments.pos; @@ -32019,7 +33494,7 @@ var ts; return true; } break; - case 130: + case 131: var parameter = node; if (parameter.modifiers) { var start = parameter.modifiers.pos; @@ -32027,7 +33502,7 @@ var ts; return true; } if (parameter.questionToken) { - diagnostics.push(ts.createDiagnosticForNode(parameter.questionToken, ts.Diagnostics.can_only_be_used_in_a_ts_file)); + diagnostics.push(ts.createDiagnosticForNode(parameter.questionToken, ts.Diagnostics._0_can_only_be_used_in_a_ts_file, '?')); return true; } if (parameter.type) { @@ -32035,17 +33510,17 @@ var ts; return true; } break; - case 133: + case 134: diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.property_declarations_can_only_be_used_in_a_ts_file)); return true; - case 205: + case 207: diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.enum_declarations_can_only_be_used_in_a_ts_file)); return true; - case 161: + case 163: var typeAssertionExpression = node; diagnostics.push(ts.createDiagnosticForNode(typeAssertionExpression.type, ts.Diagnostics.type_assertion_expressions_can_only_be_used_in_a_ts_file)); return true; - case 131: + case 132: diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.decorators_can_only_be_used_in_a_ts_file)); return true; } @@ -32089,7 +33564,7 @@ var ts; } function getCompilerOptionsDiagnostics() { synchronizeHostData(); - return program.getGlobalDiagnostics(); + return program.getOptionsDiagnostics().concat(program.getGlobalDiagnostics()); } function getCompletionEntryDisplayNameForSymbol(symbol, target, performCharacterChecks) { var displayName = symbol.getName(); @@ -32136,6 +33611,7 @@ var ts; var typeChecker = program.getTypeChecker(); var syntacticStart = new Date().getTime(); var sourceFile = getValidSourceFile(fileName); + var isJavaScriptFile = ts.isJavaScript(fileName); var start = new Date().getTime(); var currentToken = ts.getTokenAtPosition(sourceFile, position); log("getCompletionData: Get current token: " + (new Date().getTime() - start)); @@ -32161,11 +33637,11 @@ var ts; } var node = currentToken; var isRightOfDot = false; - if (contextToken && contextToken.kind === 20 && contextToken.parent.kind === 156) { + if (contextToken && contextToken.kind === 20 && contextToken.parent.kind === 158) { node = contextToken.parent.expression; isRightOfDot = true; } - else if (contextToken && contextToken.kind === 20 && contextToken.parent.kind === 127) { + else if (contextToken && contextToken.kind === 20 && contextToken.parent.kind === 128) { node = contextToken.parent.left; isRightOfDot = true; } @@ -32188,7 +33664,7 @@ var ts; function getTypeScriptMemberSymbols() { isMemberCompletion = true; isNewIdentifierLocation = false; - if (node.kind === 65 || node.kind === 127 || node.kind === 156) { + if (node.kind === 65 || node.kind === 128 || node.kind === 158) { var symbol = typeChecker.getSymbolAtLocation(node); if (symbol && symbol.flags & 8388608) { symbol = typeChecker.getAliasedSymbol(symbol); @@ -32203,12 +33679,23 @@ var ts; } } var type = typeChecker.getTypeAtLocation(node); + addTypeProperties(type); + } + function addTypeProperties(type) { if (type) { - ts.forEach(type.getApparentProperties(), function (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 & 16384) { + var unionType = type; + for (var _b = 0, _c = unionType.types; _b < _c.length; _b++) { + var elementType = _c[_b]; + addTypeProperties(elementType); + } + } } } function tryGetGlobalSymbols() { @@ -32225,11 +33712,11 @@ var ts; symbols = filterContextualMembersList(contextualTypeMembers, containingObjectLiteral.properties); } } - else if (ts.getAncestor(contextToken, 211)) { + else if (ts.getAncestor(contextToken, 213)) { isMemberCompletion = true; isNewIdentifierLocation = true; if (showCompletionsInImportsClause(contextToken)) { - var importDeclaration = ts.getAncestor(contextToken, 210); + var importDeclaration = ts.getAncestor(contextToken, 212); ts.Debug.assert(importDeclaration !== undefined); var exports_2; if (importDeclaration.moduleSpecifier) { @@ -32274,7 +33761,7 @@ var ts; function showCompletionsInImportsClause(node) { if (node) { if (node.kind === 14 || node.kind === 23) { - return node.parent.kind === 213; + return node.parent.kind === 215; } } return false; @@ -32284,38 +33771,38 @@ var ts; var containingNodeKind = previousToken.parent.kind; switch (previousToken.kind) { case 23: - return containingNodeKind === 158 - || containingNodeKind === 136 - || containingNodeKind === 159 - || containingNodeKind === 154 - || containingNodeKind === 170 - || containingNodeKind === 143; + return containingNodeKind === 160 + || containingNodeKind === 137 + || containingNodeKind === 161 + || containingNodeKind === 156 + || containingNodeKind === 172 + || containingNodeKind === 145; case 16: - return containingNodeKind === 158 - || containingNodeKind === 136 - || containingNodeKind === 159 - || containingNodeKind === 162 - || containingNodeKind === 150; + return containingNodeKind === 160 + || containingNodeKind === 137 + || containingNodeKind === 161 + || containingNodeKind === 164 + || containingNodeKind === 152; case 18: - return containingNodeKind === 154; - case 117: + return containingNodeKind === 156; case 118: + case 119: return true; case 20: - return containingNodeKind === 206; + return containingNodeKind === 208; case 14: - return containingNodeKind === 202; + return containingNodeKind === 204; case 53: - return containingNodeKind === 199 - || containingNodeKind === 170; + return containingNodeKind === 201 + || containingNodeKind === 172; case 11: - return containingNodeKind === 172; + return containingNodeKind === 174; case 12: - return containingNodeKind === 178; + return containingNodeKind === 180; case 108: case 106: case 107: - return containingNodeKind === 133; + return containingNodeKind === 134; } switch (previousToken.getText()) { case "public": @@ -32335,8 +33822,9 @@ var ts; if (start_3 < position && position < end) { return true; } - else if (position === end) { - return !!previousToken.isUnterminated; + if (position === end) { + return !!previousToken.isUnterminated || + previousToken.kind === 9; } } return false; @@ -32344,12 +33832,12 @@ var ts; function getContainingObjectLiteralApplicableForCompletion(previousToken) { // The locations in an object literal expression that are applicable for completion are property name definition locations. if (previousToken) { - var parent_8 = previousToken.parent; + var parent_10 = previousToken.parent; switch (previousToken.kind) { case 14: case 23: - if (parent_8 && parent_8.kind === 155) { - return parent_8; + if (parent_10 && parent_10.kind === 157) { + return parent_10; } break; } @@ -32358,16 +33846,16 @@ var ts; } function isFunction(kind) { switch (kind) { - case 163: - case 164: - case 201: + case 165: + case 166: + case 203: + case 136: case 135: - case 134: - case 137: case 138: case 139: case 140: case 141: + case 142: return true; } return false; @@ -32377,63 +33865,63 @@ var ts; var containingNodeKind = previousToken.parent.kind; switch (previousToken.kind) { case 23: - return containingNodeKind === 199 || - containingNodeKind === 200 || - containingNodeKind === 181 || - containingNodeKind === 205 || - isFunction(containingNodeKind) || + return containingNodeKind === 201 || containingNodeKind === 202 || - containingNodeKind === 201 || + containingNodeKind === 183 || + containingNodeKind === 207 || + isFunction(containingNodeKind) || + containingNodeKind === 204 || containingNodeKind === 203 || - containingNodeKind === 152 || - containingNodeKind === 151; + containingNodeKind === 205 || + containingNodeKind === 154 || + containingNodeKind === 153; case 20: - return containingNodeKind === 152; + return containingNodeKind === 154; case 51: - return containingNodeKind === 153; + return containingNodeKind === 155; case 18: - return containingNodeKind === 152; + return containingNodeKind === 154; case 16: - return containingNodeKind === 224 || + return containingNodeKind === 226 || isFunction(containingNodeKind); case 14: - return containingNodeKind === 205 || - containingNodeKind === 203 || - containingNodeKind === 146 || - containingNodeKind === 151; + return containingNodeKind === 207 || + containingNodeKind === 205 || + containingNodeKind === 148 || + containingNodeKind === 153; case 22: - return containingNodeKind === 132 && + return containingNodeKind === 133 && previousToken.parent && previousToken.parent.parent && - (previousToken.parent.parent.kind === 203 || - previousToken.parent.parent.kind === 146); + (previousToken.parent.parent.kind === 205 || + previousToken.parent.parent.kind === 148); case 24: - return containingNodeKind === 202 || - containingNodeKind === 201 || + return containingNodeKind === 204 || containingNodeKind === 203 || + containingNodeKind === 205 || isFunction(containingNodeKind); case 109: - return containingNodeKind === 133; + return containingNodeKind === 134; case 21: - return containingNodeKind === 130 || - containingNodeKind === 136 || + return containingNodeKind === 131 || + containingNodeKind === 137 || (previousToken.parent && previousToken.parent.parent && - previousToken.parent.parent.kind === 152); + previousToken.parent.parent.kind === 154); case 108: case 106: case 107: - return containingNodeKind === 130; + return containingNodeKind === 131; case 69: case 77: case 103: case 83: case 98: case 116: - case 121: + case 122: case 85: case 104: case 70: case 110: - case 124: + case 125: return true; } switch (previousToken.getText()) { @@ -32464,7 +33952,7 @@ var ts; return exports; } if (importDeclaration.importClause.namedBindings && - importDeclaration.importClause.namedBindings.kind === 213) { + importDeclaration.importClause.namedBindings.kind === 215) { ts.forEach(importDeclaration.importClause.namedBindings.elements, function (el) { var name = el.propertyName || el.name; exisingImports[name.text] = true; @@ -32481,7 +33969,7 @@ var ts; } var existingMemberNames = {}; ts.forEach(existingMembers, function (m) { - if (m.kind !== 225 && m.kind !== 226) { + if (m.kind !== 227 && m.kind !== 228) { return; } if (m.getStart() <= position && position <= m.getEnd()) { @@ -32527,10 +34015,10 @@ var ts; for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { var sourceFile = _a[_i]; var nameTable = getNameTable(sourceFile); - for (var name_26 in nameTable) { - if (!allNames[name_26]) { - allNames[name_26] = name_26; - var displayName = getCompletionEntryDisplayName(name_26, target, true); + for (var name_27 in nameTable) { + if (!allNames[name_27]) { + allNames[name_27] = name_27; + var displayName = getCompletionEntryDisplayName(name_27, target, true); if (displayName) { var entry = { name: displayName, @@ -32706,14 +34194,14 @@ var ts; var signature; type = typeChecker.getTypeOfSymbolAtLocation(symbol, location); if (type) { - if (location.parent && location.parent.kind === 156) { + if (location.parent && location.parent.kind === 158) { var right = location.parent.name; if (right === location || (right && right.getFullWidth() === 0)) { location = location.parent; } } var callExpression; - if (location.kind === 158 || location.kind === 159) { + if (location.kind === 160 || location.kind === 161) { callExpression = location; } else if (isCallExpressionTarget(location) || isNewExpressionTarget(location)) { @@ -32725,7 +34213,7 @@ var ts; if (!signature && candidateSignatures.length) { signature = candidateSignatures[0]; } - var useConstructSignatures = callExpression.kind === 159 || callExpression.expression.kind === 91; + var useConstructSignatures = callExpression.kind === 161 || callExpression.expression.kind === 91; var allSignatures = useConstructSignatures ? type.getConstructSignatures() : type.getCallSignatures(); if (!ts.contains(allSignatures, signature.target || signature)) { signature = allSignatures.length ? allSignatures[0] : undefined; @@ -32773,21 +34261,21 @@ var ts; } } else if ((isNameOfFunctionDeclaration(location) && !(symbol.flags & 98304)) || - (location.kind === 114 && location.parent.kind === 136)) { + (location.kind === 114 && location.parent.kind === 137)) { var functionDeclaration = location.parent; - var allSignatures = functionDeclaration.kind === 136 ? type.getConstructSignatures() : type.getCallSignatures(); + var allSignatures = functionDeclaration.kind === 137 ? type.getConstructSignatures() : type.getCallSignatures(); if (!typeChecker.isImplementationOfOverload(functionDeclaration)) { signature = typeChecker.getSignatureFromDeclaration(functionDeclaration); } else { signature = allSignatures[0]; } - if (functionDeclaration.kind === 136) { + if (functionDeclaration.kind === 137) { symbolKind = ScriptElementKind.constructorImplementationElement; addPrefixForAnyFunctionOrVar(type.symbol, symbolKind); } else { - addPrefixForAnyFunctionOrVar(functionDeclaration.kind === 139 && + addPrefixForAnyFunctionOrVar(functionDeclaration.kind === 140 && !(type.symbol.flags & 2048 || type.symbol.flags & 4096) ? type.symbol : symbol, symbolKind); } addSignatureDisplayParts(signature, allSignatures); @@ -32810,7 +34298,7 @@ var ts; } if (symbolFlags & 524288) { addNewLineIfDisplayPartsExist(); - displayParts.push(ts.keywordPart(124)); + displayParts.push(ts.keywordPart(125)); displayParts.push(ts.spacePart()); addFullSymbolName(symbol); displayParts.push(ts.spacePart()); @@ -32830,9 +34318,9 @@ var ts; } if (symbolFlags & 1536) { addNewLineIfDisplayPartsExist(); - var declaration = ts.getDeclarationOfKind(symbol, 206); + var declaration = ts.getDeclarationOfKind(symbol, 208); var isNamespace = declaration && declaration.name && declaration.name.kind === 65; - displayParts.push(ts.keywordPart(isNamespace ? 118 : 117)); + displayParts.push(ts.keywordPart(isNamespace ? 119 : 118)); displayParts.push(ts.spacePart()); addFullSymbolName(symbol); } @@ -32851,13 +34339,13 @@ var ts; writeTypeParametersOfSymbol(symbol.parent, enclosingDeclaration); } else { - var signatureDeclaration = ts.getDeclarationOfKind(symbol, 129).parent; + var signatureDeclaration = ts.getDeclarationOfKind(symbol, 130).parent; var signature = typeChecker.getSignatureFromDeclaration(signatureDeclaration); - if (signatureDeclaration.kind === 140) { + if (signatureDeclaration.kind === 141) { displayParts.push(ts.keywordPart(88)); displayParts.push(ts.spacePart()); } - else if (signatureDeclaration.kind !== 139 && signatureDeclaration.name) { + else if (signatureDeclaration.kind !== 140 && signatureDeclaration.name) { addFullSymbolName(signatureDeclaration.symbol); } displayParts.push.apply(displayParts, ts.signatureToDisplayParts(typeChecker, signature, sourceFile, 32)); @@ -32866,7 +34354,7 @@ var ts; if (symbolFlags & 8) { addPrefixForAnyFunctionOrVar(symbol, "enum member"); var declaration = symbol.declarations[0]; - if (declaration.kind === 227) { + if (declaration.kind === 229) { var constantValue = typeChecker.getConstantValue(declaration); if (constantValue !== undefined) { displayParts.push(ts.spacePart()); @@ -32882,13 +34370,13 @@ var ts; displayParts.push(ts.spacePart()); addFullSymbolName(symbol); ts.forEach(symbol.declarations, function (declaration) { - if (declaration.kind === 209) { + if (declaration.kind === 211) { var importEqualsDeclaration = declaration; if (ts.isExternalModuleImportEqualsDeclaration(importEqualsDeclaration)) { displayParts.push(ts.spacePart()); displayParts.push(ts.operatorPart(53)); displayParts.push(ts.spacePart()); - displayParts.push(ts.keywordPart(119)); + displayParts.push(ts.keywordPart(120)); displayParts.push(ts.punctuationPart(16)); displayParts.push(ts.displayPart(ts.getTextOfNode(ts.getExternalModuleImportEqualsDeclarationExpression(importEqualsDeclaration)), SymbolDisplayPartKind.stringLiteral)); displayParts.push(ts.punctuationPart(17)); @@ -33012,8 +34500,8 @@ var ts; if (!symbol) { switch (node.kind) { case 65: - case 156: - case 127: + case 158: + case 128: case 93: case 91: var type = typeChecker.getTypeAtLocation(node); @@ -33067,7 +34555,7 @@ var ts; if (isNewExpressionTarget(location) || location.kind === 114) { if (symbol.flags & 32) { var classDeclaration = symbol.getDeclarations()[0]; - ts.Debug.assert(classDeclaration && classDeclaration.kind === 202); + ts.Debug.assert(classDeclaration && classDeclaration.kind === 204); return tryAddSignature(classDeclaration.members, true, symbolKind, symbolName, containerName, result); } } @@ -33083,8 +34571,8 @@ var ts; var declarations = []; var definition; ts.forEach(signatureDeclarations, function (d) { - if ((selectConstructors && d.kind === 136) || - (!selectConstructors && (d.kind === 201 || d.kind === 135 || d.kind === 134))) { + if ((selectConstructors && d.kind === 137) || + (!selectConstructors && (d.kind === 203 || d.kind === 136 || d.kind === 135))) { declarations.push(d); if (d.body) definition = d; @@ -33139,7 +34627,7 @@ var ts; symbol = typeChecker.getAliasedSymbol(symbol); } } - if (node.parent.kind === 226) { + if (node.parent.kind === 228) { var shorthandSymbol = typeChecker.getShorthandAssignmentValueSymbol(symbol.valueDeclaration); if (!shorthandSymbol) { return []; @@ -33172,7 +34660,7 @@ var ts; var result = []; ts.forEach(type.types, function (t) { if (t.symbol) { - result.push.apply(result, getDefinitionFromSymbol(t.symbol, node)); + ts.addRange(result, getDefinitionFromSymbol(t.symbol, node)); } }); return result; @@ -33263,74 +34751,74 @@ var ts; switch (node.kind) { case 84: case 76: - if (hasKind(node.parent, 184)) { + if (hasKind(node.parent, 186)) { return getIfElseOccurrences(node.parent); } break; case 90: - if (hasKind(node.parent, 192)) { + if (hasKind(node.parent, 194)) { return getReturnOccurrences(node.parent); } break; case 94: - if (hasKind(node.parent, 196)) { + if (hasKind(node.parent, 198)) { return getThrowOccurrences(node.parent); } break; case 68: - if (hasKind(parent(parent(node)), 197)) { + if (hasKind(parent(parent(node)), 199)) { return getTryCatchFinallyOccurrences(node.parent.parent); } break; case 96: case 81: - if (hasKind(parent(node), 197)) { + if (hasKind(parent(node), 199)) { return getTryCatchFinallyOccurrences(node.parent); } break; case 92: - if (hasKind(node.parent, 194)) { + if (hasKind(node.parent, 196)) { return getSwitchCaseDefaultOccurrences(node.parent); } break; case 67: case 73: - if (hasKind(parent(parent(parent(node))), 194)) { + if (hasKind(parent(parent(parent(node))), 196)) { return getSwitchCaseDefaultOccurrences(node.parent.parent.parent); } break; case 66: case 71: - if (hasKind(node.parent, 191) || hasKind(node.parent, 190)) { + if (hasKind(node.parent, 193) || hasKind(node.parent, 192)) { return getBreakOrContinueStatementOccurences(node.parent); } break; case 82: - if (hasKind(node.parent, 187) || - hasKind(node.parent, 188) || - hasKind(node.parent, 189)) { + if (hasKind(node.parent, 189) || + hasKind(node.parent, 190) || + hasKind(node.parent, 191)) { return getLoopBreakContinueOccurrences(node.parent); } break; case 100: case 75: - if (hasKind(node.parent, 186) || hasKind(node.parent, 185)) { + if (hasKind(node.parent, 188) || hasKind(node.parent, 187)) { return getLoopBreakContinueOccurrences(node.parent); } break; case 114: - if (hasKind(node.parent, 136)) { + if (hasKind(node.parent, 137)) { return getConstructorOccurrences(node.parent); } break; case 116: - case 121: - if (hasKind(node.parent, 137) || hasKind(node.parent, 138)) { + case 122: + if (hasKind(node.parent, 138) || hasKind(node.parent, 139)) { return getGetAndSetOccurrences(node.parent); } default: if (ts.isModifier(node.kind) && node.parent && - (ts.isDeclaration(node.parent) || node.parent.kind === 181)) { + (ts.isDeclaration(node.parent) || node.parent.kind === 183)) { return getModifierOccurrences(node.kind, node.parent); } } @@ -33342,10 +34830,10 @@ var ts; aggregate(node); return statementAccumulator; function aggregate(node) { - if (node.kind === 196) { + if (node.kind === 198) { statementAccumulator.push(node); } - else if (node.kind === 197) { + else if (node.kind === 199) { var tryStatement = node; if (tryStatement.catchClause) { aggregate(tryStatement.catchClause); @@ -33366,17 +34854,17 @@ var ts; function getThrowStatementOwner(throwStatement) { var child = throwStatement; while (child.parent) { - var parent_9 = child.parent; - if (ts.isFunctionBlock(parent_9) || parent_9.kind === 228) { - return parent_9; + var parent_11 = child.parent; + if (ts.isFunctionBlock(parent_11) || parent_11.kind === 230) { + return parent_11; } - if (parent_9.kind === 197) { - var tryStatement = parent_9; + if (parent_11.kind === 199) { + var tryStatement = parent_11; if (tryStatement.tryBlock === child && tryStatement.catchClause) { return child; } } - child = parent_9; + child = parent_11; } return undefined; } @@ -33385,7 +34873,7 @@ var ts; aggregate(node); return statementAccumulator; function aggregate(node) { - if (node.kind === 191 || node.kind === 190) { + if (node.kind === 193 || node.kind === 192) { statementAccumulator.push(node); } else if (!ts.isFunctionLike(node)) { @@ -33399,23 +34887,23 @@ var ts; return actualOwner && actualOwner === owner; } function getBreakOrContinueOwner(statement) { - for (var node_1 = statement.parent; node_1; node_1 = node_1.parent) { - switch (node_1.kind) { - case 194: - if (statement.kind === 190) { + for (var node_2 = statement.parent; node_2; node_2 = node_2.parent) { + switch (node_2.kind) { + case 196: + if (statement.kind === 192) { continue; } - case 187: - case 188: case 189: - case 186: - case 185: - if (!statement.label || isLabeledBy(node_1, statement.label.text)) { - return node_1; + case 190: + case 191: + case 188: + case 187: + if (!statement.label || isLabeledBy(node_2, statement.label.text)) { + return node_2; } break; default: - if (ts.isFunctionLike(node_1)) { + if (ts.isFunctionLike(node_2)) { return undefined; } break; @@ -33426,18 +34914,18 @@ var ts; function getModifierOccurrences(modifier, declaration) { var container = declaration.parent; if (ts.isAccessibilityModifier(modifier)) { - if (!(container.kind === 202 || - (declaration.kind === 130 && hasKind(container, 136)))) { + if (!(container.kind === 204 || + (declaration.kind === 131 && hasKind(container, 137)))) { return undefined; } } else if (modifier === 109) { - if (container.kind !== 202) { + if (container.kind !== 204) { return undefined; } } else if (modifier === 78 || modifier === 115) { - if (!(container.kind === 207 || container.kind === 228)) { + if (!(container.kind === 209 || container.kind === 230)) { return undefined; } } @@ -33448,18 +34936,18 @@ var ts; var modifierFlag = getFlagFromModifier(modifier); var nodes; switch (container.kind) { - case 207: - case 228: + case 209: + case 230: nodes = container.statements; break; - case 136: + case 137: nodes = container.parameters.concat(container.parent.members); break; - case 202: + case 204: nodes = container.members; if (modifierFlag & 112) { var constructor = ts.forEach(container.members, function (member) { - return member.kind === 136 && member; + return member.kind === 137 && member; }); if (constructor) { nodes = nodes.concat(constructor.parameters); @@ -33507,13 +34995,13 @@ var ts; } function getGetAndSetOccurrences(accessorDeclaration) { var keywords = []; - tryPushAccessorKeyword(accessorDeclaration.symbol, 137); tryPushAccessorKeyword(accessorDeclaration.symbol, 138); + tryPushAccessorKeyword(accessorDeclaration.symbol, 139); return ts.map(keywords, getHighlightSpanForNode); function tryPushAccessorKeyword(accessorSymbol, accessorKind) { var accessor = ts.getDeclarationOfKind(accessorSymbol, accessorKind); if (accessor) { - ts.forEach(accessor.getChildren(), function (child) { return pushKeywordIf(keywords, child, 116, 121); }); + ts.forEach(accessor.getChildren(), function (child) { return pushKeywordIf(keywords, child, 116, 122); }); } } } @@ -33530,7 +35018,7 @@ var ts; function getLoopBreakContinueOccurrences(loopNode) { var keywords = []; if (pushKeywordIf(keywords, loopNode.getFirstToken(), 82, 100, 75)) { - if (loopNode.kind === 185) { + if (loopNode.kind === 187) { var loopTokens = loopNode.getChildren(); for (var i = loopTokens.length - 1; i >= 0; i--) { if (pushKeywordIf(keywords, loopTokens[i], 100)) { @@ -33551,13 +35039,13 @@ var ts; var owner = getBreakOrContinueOwner(breakOrContinueStatement); if (owner) { switch (owner.kind) { + case 189: + case 190: + case 191: case 187: case 188: - case 189: - case 185: - case 186: return getLoopBreakContinueOccurrences(owner); - case 194: + case 196: return getSwitchCaseDefaultOccurrences(owner); } } @@ -33607,7 +35095,7 @@ var ts; } function getReturnOccurrences(returnStatement) { var func = ts.getContainingFunction(returnStatement); - if (!(func && hasKind(func.body, 180))) { + if (!(func && hasKind(func.body, 182))) { return undefined; } var keywords = []; @@ -33621,7 +35109,7 @@ var ts; } function getIfElseOccurrences(ifStatement) { var keywords = []; - while (hasKind(ifStatement.parent, 184) && ifStatement.parent.elseStatement === ifStatement) { + while (hasKind(ifStatement.parent, 186) && ifStatement.parent.elseStatement === ifStatement) { ifStatement = ifStatement.parent; } while (ifStatement) { @@ -33632,7 +35120,7 @@ var ts; break; } } - if (!hasKind(ifStatement.elseStatement, 184)) { + if (!hasKind(ifStatement.elseStatement, 186)) { break; } ifStatement = ifStatement.elseStatement; @@ -33790,16 +35278,16 @@ var ts; } function isImportOrExportSpecifierName(location) { return location.parent && - (location.parent.kind === 214 || location.parent.kind === 218) && + (location.parent.kind === 216 || location.parent.kind === 220) && location.parent.propertyName === location; } function isImportOrExportSpecifierImportSymbol(symbol) { return (symbol.flags & 8388608) && ts.forEach(symbol.declarations, function (declaration) { - return declaration.kind === 214 || declaration.kind === 218; + return declaration.kind === 216 || declaration.kind === 220; }); } function getDeclaredName(symbol, location) { - var functionExpression = ts.forEach(symbol.declarations, function (d) { return d.kind === 163 ? d : undefined; }); + var functionExpression = ts.forEach(symbol.declarations, function (d) { return d.kind === 165 ? d : undefined; }); var name; if (functionExpression && functionExpression.name) { name = functionExpression.name.text; @@ -33814,7 +35302,7 @@ var ts; if (isImportOrExportSpecifierName(location)) { return location.getText(); } - var functionExpression = ts.forEach(declarations, function (d) { return d.kind === 163 ? d : undefined; }); + var functionExpression = ts.forEach(declarations, function (d) { return d.kind === 165 ? d : undefined; }); var name = functionExpression && functionExpression.name ? functionExpression.name.text : symbol.name; @@ -33832,7 +35320,7 @@ var ts; if (symbol.flags & (4 | 8192)) { var privateDeclaration = ts.forEach(symbol.getDeclarations(), function (d) { return (d.flags & 32) ? d : undefined; }); if (privateDeclaration) { - return ts.getAncestor(privateDeclaration, 202); + return ts.getAncestor(privateDeclaration, 204); } } if (symbol.flags & 8388608) { @@ -33853,7 +35341,7 @@ var ts; if (scope && scope !== container) { return undefined; } - if (container.kind === 228 && !ts.isExternalModule(container)) { + if (container.kind === 230 && !ts.isExternalModule(container)) { return undefined; } scope = container; @@ -34012,13 +35500,13 @@ var ts; } var staticFlag = 128; switch (searchSpaceNode.kind) { - case 133: - case 132: - case 135: case 134: + case 133: case 136: + case 135: case 137: case 138: + case 139: staticFlag &= searchSpaceNode.flags; searchSpaceNode = searchSpaceNode.parent; break; @@ -34046,32 +35534,32 @@ var ts; var searchSpaceNode = ts.getThisContainer(thisOrSuperKeyword, false); var staticFlag = 128; switch (searchSpaceNode.kind) { + case 136: case 135: - case 134: if (ts.isObjectLiteralMethod(searchSpaceNode)) { break; } + case 134: case 133: - case 132: - case 136: case 137: case 138: + case 139: staticFlag &= searchSpaceNode.flags; searchSpaceNode = searchSpaceNode.parent; break; - case 228: + case 230: if (ts.isExternalModule(searchSpaceNode)) { return undefined; } - case 201: - case 163: + case 203: + case 165: break; default: return undefined; } var references = []; var possiblePositions; - if (searchSpaceNode.kind === 228) { + if (searchSpaceNode.kind === 230) { ts.forEach(sourceFiles, function (sourceFile) { possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "this", sourceFile.getStart(), sourceFile.getEnd()); getThisReferencesInFile(sourceFile, sourceFile, possiblePositions, references); @@ -34102,25 +35590,25 @@ var ts; } var container = ts.getThisContainer(node, false); switch (searchSpaceNode.kind) { - case 163: - case 201: + case 165: + case 203: if (searchSpaceNode.symbol === container.symbol) { result.push(getReferenceEntryFromNode(node)); } break; + case 136: case 135: - case 134: if (ts.isObjectLiteralMethod(searchSpaceNode) && searchSpaceNode.symbol === container.symbol) { result.push(getReferenceEntryFromNode(node)); } break; - case 202: + case 204: if (container.parent && searchSpaceNode.symbol === container.parent.symbol && (container.flags & 128) === staticFlag) { result.push(getReferenceEntryFromNode(node)); } break; - case 228: - if (container.kind === 228 && !ts.isExternalModule(container)) { + case 230: + if (container.kind === 230 && !ts.isExternalModule(container)) { result.push(getReferenceEntryFromNode(node)); } break; @@ -34155,11 +35643,11 @@ var ts; function getPropertySymbolsFromBaseTypes(symbol, propertyName, result) { if (symbol && symbol.flags & (32 | 64)) { ts.forEach(symbol.getDeclarations(), function (declaration) { - if (declaration.kind === 202) { + if (declaration.kind === 204) { getPropertySymbolFromTypeReference(ts.getClassExtendsHeritageClauseElement(declaration)); ts.forEach(ts.getClassImplementsHeritageClauseElements(declaration), getPropertySymbolFromTypeReference); } - else if (declaration.kind === 203) { + else if (declaration.kind === 205) { ts.forEach(ts.getInterfaceBaseTypeNodes(declaration), getPropertySymbolFromTypeReference); } }); @@ -34209,17 +35697,17 @@ var ts; if (isNameOfPropertyAssignment(node)) { var objectLiteral = node.parent.parent; var contextualType = typeChecker.getContextualType(objectLiteral); - var name_27 = node.text; + var name_28 = node.text; if (contextualType) { if (contextualType.flags & 16384) { - var unionProperty = contextualType.getProperty(name_27); + var unionProperty = contextualType.getProperty(name_28); if (unionProperty) { return [unionProperty]; } else { var result_4 = []; ts.forEach(contextualType.types, function (t) { - var symbol = t.getProperty(name_27); + var symbol = t.getProperty(name_28); if (symbol) { result_4.push(symbol); } @@ -34228,7 +35716,7 @@ var ts; } } else { - var symbol_1 = contextualType.getProperty(name_27); + var symbol_1 = contextualType.getProperty(name_28); if (symbol_1) { return [symbol_1]; } @@ -34273,10 +35761,10 @@ var ts; } var parent = node.parent; if (parent) { - if (parent.kind === 169 || parent.kind === 168) { + if (parent.kind === 171 || parent.kind === 170) { return true; } - else if (parent.kind === 170 && parent.left === node) { + else if (parent.kind === 172 && parent.left === node) { var operator = parent.operatorToken.kind; return 53 <= operator && operator <= 64; } @@ -34309,33 +35797,33 @@ var ts; } function getMeaningFromDeclaration(node) { switch (node.kind) { - case 130: - case 199: - case 153: - case 133: - case 132: - case 225: - case 226: - case 227: - case 135: + case 131: + case 201: + case 155: case 134: + case 133: + case 227: + case 228: + case 229: case 136: + case 135: case 137: case 138: - case 201: - case 163: - case 164: - case 224: - return 1; - case 129: + case 139: case 203: - case 204: - case 146: - return 2; - case 202: + case 165: + case 166: + case 226: + return 1; + case 130: case 205: - return 1 | 2; case 206: + case 148: + return 2; + case 204: + case 207: + return 1 | 2; + case 208: if (node.name.kind === 8) { return 4 | 1; } @@ -34345,14 +35833,14 @@ var ts; else { return 4; } - case 213: - case 214: - case 209: - case 210: case 215: case 216: + case 211: + case 212: + case 217: + case 218: return 1 | 2 | 4; - case 228: + case 230: return 4 | 1; } return 1 | 2 | 4; @@ -34362,7 +35850,8 @@ var ts; if (ts.isRightSideOfQualifiedNameOrPropertyAccess(node)) { node = node.parent; } - return node.parent.kind === 142 || node.parent.kind === 177; + return node.parent.kind === 144 || + (node.parent.kind === 179 && !ts.isExpressionWithTypeArgumentsInClassExtendsClause(node.parent)); } function isNamespaceReference(node) { return isQualifiedNameNamespaceReference(node) || isPropertyAccessNamespaceReference(node); @@ -34370,47 +35859,47 @@ var ts; function isPropertyAccessNamespaceReference(node) { var root = node; var isLastClause = true; - if (root.parent.kind === 156) { - while (root.parent && root.parent.kind === 156) { + if (root.parent.kind === 158) { + while (root.parent && root.parent.kind === 158) { root = root.parent; } isLastClause = root.name === node; } - if (!isLastClause && root.parent.kind === 177 && root.parent.parent.kind === 223) { + if (!isLastClause && root.parent.kind === 179 && root.parent.parent.kind === 225) { var decl = root.parent.parent.parent; - return (decl.kind === 202 && root.parent.parent.token === 102) || - (decl.kind === 203 && root.parent.parent.token === 79); + return (decl.kind === 204 && root.parent.parent.token === 102) || + (decl.kind === 205 && root.parent.parent.token === 79); } return false; } function isQualifiedNameNamespaceReference(node) { var root = node; var isLastClause = true; - if (root.parent.kind === 127) { - while (root.parent && root.parent.kind === 127) { + if (root.parent.kind === 128) { + while (root.parent && root.parent.kind === 128) { root = root.parent; } isLastClause = root.right === node; } - return root.parent.kind === 142 && !isLastClause; + return root.parent.kind === 144 && !isLastClause; } function isInRightSideOfImport(node) { - while (node.parent.kind === 127) { + while (node.parent.kind === 128) { node = node.parent; } return ts.isInternalModuleImportEqualsDeclaration(node.parent) && node.parent.moduleReference === node; } function getMeaningFromRightHandSideOfImportEquals(node) { ts.Debug.assert(node.kind === 65); - if (node.parent.kind === 127 && + if (node.parent.kind === 128 && node.parent.right === node && - node.parent.parent.kind === 209) { + node.parent.parent.kind === 211) { return 1 | 2 | 4; } return 4; } function getMeaningFromLocation(node) { - if (node.parent.kind === 215) { + if (node.parent.kind === 217) { return 1 | 2 | 4; } else if (isInRightSideOfImport(node)) { @@ -34444,8 +35933,8 @@ var ts; return; } switch (node.kind) { - case 156: - case 127: + case 158: + case 128: case 8: case 80: case 95: @@ -34463,7 +35952,7 @@ var ts; nodeForStartPos = nodeForStartPos.parent; } else if (isNameOfModuleDeclaration(nodeForStartPos)) { - if (nodeForStartPos.parent.parent.kind === 206 && + if (nodeForStartPos.parent.parent.kind === 208 && nodeForStartPos.parent.parent.body === nodeForStartPos.parent) { nodeForStartPos = nodeForStartPos.parent.parent.name; } @@ -34493,6 +35982,7 @@ var ts; var sourceFile = getValidSourceFile(fileName); var typeChecker = program.getTypeChecker(); var result = []; + var classifiableNames = program.getClassifiableNames(); processNode(sourceFile); return { spans: result, endOfLineState: 0 }; function pushClassification(start, length, type) { @@ -34502,6 +35992,9 @@ var ts; } function classifySymbol(symbol, meaningAtPosition) { var flags = symbol.getFlags(); + if ((flags & 788448) === 0) { + return; + } if (flags & 32) { return 11; } @@ -34528,18 +36021,22 @@ var ts; return undefined; function hasValueSideModule(symbol) { return ts.forEach(symbol.declarations, function (declaration) { - return declaration.kind === 206 && ts.getModuleInstanceState(declaration) == 1; + return declaration.kind === 208 && + ts.getModuleInstanceState(declaration) === 1; }); } } function processNode(node) { - if (node && ts.textSpanIntersectsWith(span, node.getStart(), node.getWidth())) { - if (node.kind === 65 && node.getWidth() > 0) { - var symbol = typeChecker.getSymbolAtLocation(node); - if (symbol) { - var type = classifySymbol(symbol, getMeaningFromLocation(node)); - if (type) { - pushClassification(node.getStart(), node.getWidth(), type); + if (node && ts.textSpanIntersectsWith(span, node.getFullStart(), node.getFullWidth())) { + if (node.kind === 65 && !ts.nodeIsMissing(node)) { + var identifier = node; + if (classifiableNames[identifier.text]) { + var symbol = typeChecker.getSymbolAtLocation(node); + if (symbol) { + var type = classifySymbol(symbol, getMeaningFromLocation(node)); + if (type) { + pushClassification(node.getStart(), node.getWidth(), type); + } } } } @@ -34565,6 +36062,7 @@ var ts; case 15: return ClassificationTypeNames.typeParameterName; case 16: return ClassificationTypeNames.typeAliasName; case 17: return ClassificationTypeNames.parameterName; + case 18: return ClassificationTypeNames.docCommentTagName; } } function convertClassifications(classifications) { @@ -34584,6 +36082,8 @@ var ts; } function getEncodedSyntacticClassifications(fileName, span) { var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); + var spanStart = span.start; + var spanLength = span.length; var triviaScanner = ts.createScanner(2, false, sourceFile.text); var mergeConflictScanner = ts.createScanner(2, false, sourceFile.text); var result = []; @@ -34594,38 +36094,107 @@ var ts; result.push(length); result.push(type); } - function classifyLeadingTrivia(token) { - var tokenStart = ts.skipTrivia(sourceFile.text, token.pos, false); - if (tokenStart === token.pos) { - return; - } + function classifyLeadingTriviaAndGetTokenStart(token) { triviaScanner.setTextPos(token.pos); while (true) { var start = triviaScanner.getTextPos(); + if (!ts.couldStartTrivia(sourceFile.text, start)) { + return start; + } var kind = triviaScanner.scan(); var end = triviaScanner.getTextPos(); var width = end - start; if (!ts.isTrivia(kind)) { - return; + return start; } - if (ts.textSpanIntersectsWith(span, start, width)) { - if (ts.isComment(kind)) { + if (kind === 4 || kind === 5) { + continue; + } + if (ts.isComment(kind)) { + classifyComment(token, kind, start, width); + triviaScanner.setTextPos(end); + continue; + } + if (kind === 6) { + var text = sourceFile.text; + var ch = text.charCodeAt(start); + if (ch === 60 || ch === 62) { pushClassification(start, width, 1); continue; } - if (kind === 6) { - var text = sourceFile.text; - var ch = text.charCodeAt(start); - if (ch === 60 || ch === 62) { - pushClassification(start, width, 1); - continue; - } - ts.Debug.assert(ch === 61); - classifyDisabledMergeCode(text, start, end); - } + ts.Debug.assert(ch === 61); + classifyDisabledMergeCode(text, start, end); } } } + function classifyComment(token, kind, start, width) { + if (kind === 3) { + var docCommentAndDiagnostics = ts.parseIsolatedJSDocComment(sourceFile.text, start, width); + if (docCommentAndDiagnostics && docCommentAndDiagnostics.jsDocComment) { + docCommentAndDiagnostics.jsDocComment.parent = token; + classifyJSDocComment(docCommentAndDiagnostics.jsDocComment); + return; + } + } + pushCommentRange(start, width); + } + function pushCommentRange(start, width) { + pushClassification(start, width, 1); + } + function classifyJSDocComment(docComment) { + var pos = docComment.pos; + for (var _i = 0, _a = docComment.tags; _i < _a.length; _i++) { + var tag = _a[_i]; + if (tag.pos !== pos) { + pushCommentRange(pos, tag.pos - pos); + } + pushClassification(tag.atToken.pos, tag.atToken.end - tag.atToken.pos, 10); + pushClassification(tag.tagName.pos, tag.tagName.end - tag.tagName.pos, 18); + pos = tag.tagName.end; + switch (tag.kind) { + case 249: + processJSDocParameterTag(tag); + break; + case 252: + processJSDocTemplateTag(tag); + break; + case 251: + processElement(tag.typeExpression); + break; + case 250: + processElement(tag.typeExpression); + break; + } + pos = tag.end; + } + if (pos !== docComment.end) { + pushCommentRange(pos, docComment.end - pos); + } + 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.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; + } + } + } + function processJSDocTemplateTag(tag) { + for (var _i = 0, _a = tag.getChildren(); _i < _a.length; _i++) { + var child = _a[_i]; + processElement(child); + } + } function classifyDisabledMergeCode(text, start, end) { for (var i = start; i < end; i++) { if (ts.isLineBreak(text.charCodeAt(i))) { @@ -34648,11 +36217,16 @@ var ts; } } function classifyToken(token) { - classifyLeadingTrivia(token); - if (token.getWidth() > 0) { + if (ts.nodeIsMissing(token)) { + return; + } + var tokenStart = classifyLeadingTriviaAndGetTokenStart(token); + var tokenWidth = token.end - tokenStart; + ts.Debug.assert(tokenWidth >= 0); + if (tokenWidth > 0) { var type = classifyTokenType(token.kind, token); if (type) { - pushClassification(token.getStart(), token.getWidth(), type); + pushClassification(tokenStart, tokenWidth, type); } } } @@ -34668,16 +36242,16 @@ var ts; if (ts.isPunctuation(tokenKind)) { if (token) { if (tokenKind === 53) { - if (token.parent.kind === 199 || - token.parent.kind === 133 || - token.parent.kind === 130) { + if (token.parent.kind === 201 || + token.parent.kind === 134 || + token.parent.kind === 131) { return 5; } } - if (token.parent.kind === 170 || - token.parent.kind === 168 || - token.parent.kind === 169 || - token.parent.kind === 171) { + if (token.parent.kind === 172 || + token.parent.kind === 170 || + token.parent.kind === 171 || + token.parent.kind === 173) { return 5; } } @@ -34698,32 +36272,32 @@ var ts; else if (tokenKind === 65) { if (token) { switch (token.parent.kind) { - case 202: + case 204: if (token.parent.name === token) { return 11; } return; - case 129: + case 130: if (token.parent.name === token) { return 15; } return; - case 203: + case 205: if (token.parent.name === token) { return 13; } return; - case 205: + case 207: if (token.parent.name === token) { return 12; } return; - case 206: + case 208: if (token.parent.name === token) { return 14; } return; - case 130: + case 131: if (token.parent.name === token) { return 17; } @@ -34734,10 +36308,13 @@ var ts; } } function processElement(element) { - if (ts.textSpanIntersectsWith(span, element.getFullStart(), element.getFullWidth())) { - var children = element.getChildren(); - for (var _i = 0; _i < children.length; _i++) { - var child = children[_i]; + if (!element) { + return; + } + if (ts.decodedTextSpanIntersectsWith(spanStart, spanLength, element.pos, element.getFullWidth())) { + var children = element.getChildren(sourceFile); + for (var i = 0, n = children.length; i < n; i++) { + var child = children[i]; if (ts.isToken(child)) { classifyToken(child); } @@ -34989,7 +36566,7 @@ var ts; case 8: case 7: if (ts.isDeclarationName(node) || - node.parent.kind === 220 || + node.parent.kind === 222 || isArgumentOfElementAccessExpression(node)) { nameTable[node.text] = node.text; } @@ -35002,7 +36579,7 @@ var ts; function isArgumentOfElementAccessExpression(node) { return node && node.parent && - node.parent.kind === 157 && + node.parent.kind === 159 && node.parent.argumentExpression === node; } function createClassifier() { @@ -35024,7 +36601,7 @@ var ts; function canFollow(keyword1, keyword2) { if (ts.isAccessibilityModifier(keyword1)) { if (keyword2 === 116 || - keyword2 === 121 || + keyword2 === 122 || keyword2 === 114 || keyword2 === 109) { return true; @@ -35039,7 +36616,7 @@ var ts; var lastEnd = 0; for (var i = 0, n = dense.length; i < n; i += 3) { var start = dense[i]; - var length_1 = dense[i + 1]; + var length_2 = dense[i + 1]; var type = dense[i + 2]; if (lastEnd >= 0) { var whitespaceLength_1 = start - lastEnd; @@ -35047,8 +36624,8 @@ var ts; entries.push({ length: whitespaceLength_1, classification: TokenClass.Whitespace }); } } - entries.push({ length: length_1, classification: convertClassification(type) }); - lastEnd = start + length_1; + entries.push({ length: length_2, classification: convertClassification(type) }); + lastEnd = start + length_2; } var whitespaceLength = text.length - lastEnd; if (whitespaceLength > 0) { @@ -35140,10 +36717,10 @@ var ts; angleBracketStack--; } else if (token === 112 || - token === 122 || - token === 120 || + token === 123 || + token === 121 || token === 113 || - token === 123) { + token === 124) { if (angleBracketStack > 0 && !syntacticClassifierAbsent) { token = 65; } @@ -35297,7 +36874,7 @@ var ts; } } function isKeyword(token) { - return token >= 66 && token <= 126; + return token >= 66 && token <= 127; } function classFromKind(token) { if (isKeyword(token)) { @@ -35349,7 +36926,7 @@ var ts; getNodeConstructor: function (kind) { function Node() { } - var proto = kind === 228 ? new SourceFileObject() : new NodeObject(); + var proto = kind === 230 ? new SourceFileObject() : new NodeObject(); proto.kind = kind; proto.pos = 0; proto.end = 0; @@ -35367,7 +36944,6 @@ var ts; })(ts || (ts = {})); /// /// -/// /// /// var ts; @@ -35390,7 +36966,7 @@ var ts; if (a < b) { return -1; } - else if (a == b) { + else if (a === b) { return 0; } else @@ -35402,7 +36978,7 @@ var ts; } else if (a.file == b.file) { var n = compareNumber(a.start.line, b.start.line); - if (n == 0) { + if (n === 0) { return compareNumber(a.start.offset, b.start.offset); } else @@ -35451,6 +37027,7 @@ var ts; CommandNames.Saveto = "saveto"; CommandNames.SignatureHelp = "signatureHelp"; CommandNames.TypeDefinition = "typeDefinition"; + CommandNames.ProjectInfo = "projectInfo"; CommandNames.Unknown = "unknown"; })(CommandNames = server.CommandNames || (server.CommandNames = {})); var Errors; @@ -35458,9 +37035,11 @@ var ts; Errors.NoProject = new Error("No Project."); })(Errors || (Errors = {})); var Session = (function () { - function Session(host, logger) { + function Session(host, byteLength, hrtime, logger) { var _this = this; this.host = host; + this.byteLength = byteLength; + this.hrtime = hrtime; this.logger = logger; this.pendingOperation = false; this.fileHash = {}; @@ -35475,7 +37054,7 @@ var ts; var _this = this; if (eventName == "context") { this.projectService.log("got context event, updating diagnostics for" + fileName, "Info"); - this.updateErrorCheck([{ fileName: fileName, project: project }], this.changeSeq, function (n) { return n == _this.changeSeq; }, 100); + this.updateErrorCheck([{ fileName: fileName, project: project }], this.changeSeq, function (n) { return n === _this.changeSeq; }, 100); } }; Session.prototype.logError = function (err, cmd) { @@ -35497,7 +37076,7 @@ var ts; if (this.logger.isVerbose()) { this.logger.info(msg.type + ": " + json); } - this.sendLineToClient('Content-Length: ' + (1 + Buffer.byteLength(json, 'utf8')) + + this.sendLineToClient('Content-Length: ' + (1 + this.byteLength(json, 'utf8')) + '\r\n\r\n' + json); }; Session.prototype.event = function (info, eventName) { @@ -35664,6 +37243,17 @@ var ts; }; }); }; + Session.prototype.getProjectInfo = function (fileName, needFileNameList) { + fileName = ts.normalizePath(fileName); + var project = this.projectService.getProjectForFile(fileName); + var projectInfo = { + configFileName: project.projectFilename + }; + if (needFileNameList) { + projectInfo.fileNameList = project.getFileNameList(); + } + return projectInfo; + }; Session.prototype.getRenameLocations = function (line, offset, fileName, findInComments, findInStrings) { var file = ts.normalizePath(fileName); var project = this.projectService.getProjectForFile(file); @@ -35823,7 +37413,7 @@ var ts; var position = compilerService.host.lineOffsetToPosition(file, line, offset); var formatOptions = this.projectService.getFormatCodeOptions(file); var edits = compilerService.languageService.getFormattingEditsAfterKeystroke(file, position, key, formatOptions); - if ((key == "\n") && ((!edits) || (edits.length == 0) || allEditsBeforePos(edits, position))) { + if ((key == "\n") && ((!edits) || (edits.length === 0) || allEditsBeforePos(edits, position))) { var scriptInfo = compilerService.host.getScriptInfo(file); if (scriptInfo) { var lineInfo = scriptInfo.getLineInfo(line); @@ -35889,7 +37479,7 @@ var ts; return undefined; } return completions.entries.reduce(function (result, entry) { - if (completions.isMemberCompletion || (entry.name.toLowerCase().indexOf(prefix.toLowerCase()) == 0)) { + if (completions.isMemberCompletion || (entry.name.toLowerCase().indexOf(prefix.toLowerCase()) === 0)) { result.push(entry); } return result; @@ -35947,7 +37537,7 @@ var ts; return accum; }, []); if (checkList.length > 0) { - this.updateErrorCheck(checkList, this.changeSeq, function (n) { return n == _this.changeSeq; }, delay); + this.updateErrorCheck(checkList, this.changeSeq, function (n) { return n === _this.changeSeq; }, delay); } }; Session.prototype.change = function (line, offset, endLine, endOffset, insertString, fileName) { @@ -35962,7 +37552,7 @@ var ts; compilerService.host.editScript(file, start, end, insertString); this.changeSeq++; } - this.updateProjectStructure(this.changeSeq, function (n) { return n == _this.changeSeq; }); + this.updateProjectStructure(this.changeSeq, function (n) { return n === _this.changeSeq; }); } }; Session.prototype.reload = function (fileName, tempFileName, reqSeq) { @@ -36078,7 +37668,7 @@ var ts; Session.prototype.onMessage = function (message) { if (this.logger.isVerbose()) { this.logger.info("request: " + message); - var start = process.hrtime(); + var start = this.hrtime(); } try { var request = JSON.parse(message); @@ -36205,6 +37795,11 @@ var ts; response = this.getOccurrences(line, offset, fileName); break; } + case CommandNames.ProjectInfo: { + var _b = request.arguments, file = _b.file, needFileNameList = _b.needFileNameList; + response = this.getProjectInfo(file, needFileNameList); + break; + } default: { this.projectService.log("Unrecognized JSON command: " + message); this.output(undefined, CommandNames.Unknown, request.seq, "Unrecognized JSON command: " + request.command); @@ -36212,7 +37807,7 @@ var ts; } } if (this.logger.isVerbose()) { - var elapsed = process.hrtime(start); + var elapsed = this.hrtime(start); var seconds = elapsed[0]; var nanoseconds = elapsed[1]; var elapsedMs = ((1e9 * seconds) + nanoseconds) / 1000000.0; @@ -36245,7 +37840,6 @@ var ts; /// /// /// -/// var ts; (function (ts) { var server; @@ -36269,7 +37863,7 @@ var ts; this.isOpen = isOpen; this.children = []; this.formatCodeOptions = ts.clone(CompilerService.defaultFormatCodeOptions); - this.svc = ScriptVersionCache.fromString(content); + this.svc = ScriptVersionCache.fromString(host, content); } ScriptInfo.prototype.setFormatOptions = function (formatOptions) { if (formatOptions) { @@ -36304,6 +37898,7 @@ var ts; }; return ScriptInfo; })(); + server.ScriptInfo = ScriptInfo; var LSHost = (function () { function LSHost(host, project) { this.host = host; @@ -36434,6 +38029,7 @@ var ts; }; return LSHost; })(); + server.LSHost = LSHost; function getAbsolutePath(filename, directory) { var rootLength = ts.getRootLength(filename); if (rootLength > 0) { @@ -36477,6 +38073,10 @@ var ts; Project.prototype.openReferencedFile = function (filename) { return this.projectService.openFile(filename, false); }; + Project.prototype.getFileNameList = function () { + var sourceFiles = this.program.getSourceFiles(); + return sourceFiles.map(function (sourceFile) { return sourceFile.fileName; }); + }; Project.prototype.getSourceFile = function (info) { return this.filenameToSourceFile[info.fileName]; }; @@ -36730,7 +38330,7 @@ var ts; var orphanFiles = []; for (var i = 0, len = this.openFilesReferenced.length; i < len; i++) { var f = this.openFilesReferenced[i]; - if (f.defaultProject == removedProject) { + if (f.defaultProject === removedProject) { f.defaultProject = undefined; orphanFiles.push(f); } @@ -36754,7 +38354,7 @@ var ts; for (var i = 0, len = this.inferredProjects.length; i < len; i++) { var inferredProject = this.inferredProjects[i]; inferredProject.updateGraph(); - if (inferredProject != excludedProject) { + if (inferredProject !== excludedProject) { if (inferredProject.getSourceFile(info)) { info.defaultProject = inferredProject; referencingProjects.push(inferredProject); @@ -36792,7 +38392,7 @@ var ts; var rootFile = this.openFileRoots[i]; var rootedProject = rootFile.defaultProject; var referencingProjects = this.findReferencingProjects(rootFile, rootedProject); - if (referencingProjects.length == 0) { + if (referencingProjects.length === 0) { rootFile.defaultProject = rootedProject; openFileRoots.push(rootFile); } @@ -36966,7 +38566,7 @@ var ts; return rawConfig.error; } else { - var parsedCommandLine = ts.parseConfigFile(rawConfig.config, ts.sys, dirPath); + var parsedCommandLine = ts.parseConfigFile(rawConfig.config, this.host, dirPath); if (parsedCommandLine.errors && (parsedCommandLine.errors.length > 0)) { return { errorMsg: "tsconfig option errors" }; } @@ -37027,7 +38627,7 @@ var ts; CompilerService.defaultFormatCodeOptions = { IndentSize: 4, TabSize: 4, - NewLineCharacter: ts.sys.newLine, + NewLineCharacter: ts.sys ? ts.sys.newLine : '\n', ConvertTabsToSpaces: true, InsertSpaceAfterCommaDelimiter: true, InsertSpaceAfterSemicolonInForStatements: true, @@ -37040,7 +38640,7 @@ var ts; }; return CompilerService; })(); - var CharRangeSection; + server.CompilerService = CompilerService; (function (CharRangeSection) { CharRangeSection[CharRangeSection["PreStart"] = 0] = "PreStart"; CharRangeSection[CharRangeSection["Start"] = 1] = "Start"; @@ -37048,7 +38648,8 @@ var ts; CharRangeSection[CharRangeSection["Mid"] = 3] = "Mid"; CharRangeSection[CharRangeSection["End"] = 4] = "End"; CharRangeSection[CharRangeSection["PostEnd"] = 5] = "PostEnd"; - })(CharRangeSection || (CharRangeSection = {})); + })(server.CharRangeSection || (server.CharRangeSection = {})); + var CharRangeSection = server.CharRangeSection; var BaseLineIndexWalker = (function () { function BaseLineIndexWalker() { this.goSubtree = true; @@ -37093,7 +38694,7 @@ var ts; var lastZeroCount; for (var k = this.endBranch.length - 1; k >= 0; k--) { this.endBranch[k].updateCounts(); - if (this.endBranch[k].charCount() == 0) { + if (this.endBranch[k].charCount() === 0) { lastZeroCount = this.endBranch[k]; if (k > 0) { branchParent = this.endBranch[k - 1]; @@ -37149,7 +38750,7 @@ var ts; return this.lineIndex; }; EditWalker.prototype.post = function (relativeStart, relativeLength, lineCollection, parent, nodeType) { - if (lineCollection == this.lineCollectionAtBranch) { + if (lineCollection === this.lineCollectionAtBranch) { this.state = CharRangeSection.End; } this.stack.length--; @@ -37157,7 +38758,7 @@ var ts; }; EditWalker.prototype.pre = function (relativeStart, relativeLength, lineCollection, parent, nodeType) { var currentNode = this.stack[this.stack.length - 1]; - if ((this.state == CharRangeSection.Entire) && (nodeType == CharRangeSection.Start)) { + if ((this.state === CharRangeSection.Entire) && (nodeType === CharRangeSection.Start)) { this.state = CharRangeSection.Start; this.branchNode = currentNode; this.lineCollectionAtBranch = lineCollection; @@ -37173,12 +38774,12 @@ var ts; switch (nodeType) { case CharRangeSection.PreStart: this.goSubtree = false; - if (this.state != CharRangeSection.End) { + if (this.state !== CharRangeSection.End) { currentNode.add(lineCollection); } break; case CharRangeSection.Start: - if (this.state == CharRangeSection.End) { + if (this.state === CharRangeSection.End) { this.goSubtree = false; } else { @@ -37188,7 +38789,7 @@ var ts; } break; case CharRangeSection.Entire: - if (this.state != CharRangeSection.End) { + if (this.state !== CharRangeSection.End) { child = fresh(lineCollection); currentNode.add(child); this.startPath[this.startPath.length] = child; @@ -37205,7 +38806,7 @@ var ts; this.goSubtree = false; break; case CharRangeSection.End: - if (this.state != CharRangeSection.End) { + if (this.state !== CharRangeSection.End) { this.goSubtree = false; } else { @@ -37218,7 +38819,7 @@ var ts; break; case CharRangeSection.PostEnd: this.goSubtree = false; - if (this.state != CharRangeSection.Start) { + if (this.state !== CharRangeSection.Start) { currentNode.add(lineCollection); } break; @@ -37229,10 +38830,10 @@ var ts; return lineCollection; }; EditWalker.prototype.leaf = function (relativeStart, relativeLength, ll) { - if (this.state == CharRangeSection.Start) { + if (this.state === CharRangeSection.Start) { this.initialText = ll.text.substring(0, relativeStart); } - else if (this.state == CharRangeSection.Entire) { + else if (this.state === CharRangeSection.Entire) { this.initialText = ll.text.substring(0, relativeStart); this.trailingText = ll.text.substring(relativeStart + relativeLength); } @@ -37253,6 +38854,7 @@ var ts; }; return TextChange; })(); + server.TextChange = TextChange; var ScriptVersionCache = (function () { function ScriptVersionCache() { this.changes = []; @@ -37278,7 +38880,7 @@ var ts; return this.currentVersion; }; ScriptVersionCache.prototype.reloadFromFile = function (filename, cb) { - var content = ts.sys.readFile(filename); + var content = this.host.readFile(filename); this.reload(content); if (cb) cb(); @@ -37341,10 +38943,11 @@ var ts; return ts.unchangedTextChangeRange; } }; - ScriptVersionCache.fromString = function (script) { + ScriptVersionCache.fromString = function (host, script) { var svc = new ScriptVersionCache(); var snap = new LineIndexSnapshot(0, svc); svc.versions[svc.currentVersion] = snap; + svc.host = host; snap.index = new LineIndex(); var lm = LineIndex.linesFromText(script); snap.index.load(lm.lines); @@ -37399,6 +39002,7 @@ var ts; }; return LineIndexSnapshot; })(); + server.LineIndexSnapshot = LineIndexSnapshot; var LineIndex = (function () { function LineIndex() { this.checkEdits = false; @@ -37472,7 +39076,7 @@ var ts; if (nt === void 0) { nt = ""; } return source.substring(0, s) + nt + source.substring(s + dl, source.length); } - if (this.root.charCount() == 0) { + if (this.root.charCount() === 0) { if (newText) { this.load(LineIndex.linesFromText(newText).lines); return this; @@ -37498,7 +39102,7 @@ var ts; else if (deleteLength > 0) { var e = pos + deleteLength; var lineInfo = this.charOffsetToLineNumberAndPos(e); - if ((lineInfo && (lineInfo.offset == 0))) { + if ((lineInfo && (lineInfo.offset === 0))) { deleteLength += lineInfo.text.length; if (newText) { newText = newText + lineInfo.text; @@ -37541,7 +39145,7 @@ var ts; interiorNodes[i].totalChars = charCount; interiorNodes[i].totalLines = lineCount; } - if (interiorNodes.length == 1) { + if (interiorNodes.length === 1) { return interiorNodes[0]; } else { @@ -37550,7 +39154,7 @@ var ts; }; LineIndex.linesFromText = function (text) { var lineStarts = ts.computeLineStarts(text); - if (lineStarts.length == 0) { + if (lineStarts.length === 0) { return { lines: [], lineMap: lineStarts }; } var lines = new Array(lineStarts.length); @@ -37771,7 +39375,7 @@ var ts; LineNode.prototype.findChildIndex = function (child) { var childIndex = 0; var clen = this.children.length; - while ((this.children[childIndex] != child) && (childIndex < clen)) + while ((this.children[childIndex] !== child) && (childIndex < clen)) childIndex++; return childIndex; }; @@ -37779,7 +39383,7 @@ var ts; var childIndex = this.findChildIndex(child); var clen = this.children.length; var nodeCount = nodes.length; - if ((clen < lineCollectionCapacity) && (childIndex == (clen - 1)) && (nodeCount == 1)) { + if ((clen < lineCollectionCapacity) && (childIndex === (clen - 1)) && (nodeCount === 1)) { this.add(nodes[0]); this.updateCounts(); return []; @@ -37803,13 +39407,13 @@ var ts; var splitNode = splitNodes[0]; while (nodeIndex < nodeCount) { splitNode.add(nodes[nodeIndex++]); - if (splitNode.children.length == lineCollectionCapacity) { + if (splitNode.children.length === lineCollectionCapacity) { splitNodeIndex++; splitNode = splitNodes[splitNodeIndex]; } } for (i = splitNodes.length - 1; i >= 0; i--) { - if (splitNodes[i].children.length == 0) { + if (splitNodes[i].children.length === 0) { splitNodes.length--; } } @@ -37836,6 +39440,7 @@ var ts; }; return LineNode; })(); + server.LineNode = LineNode; var LineLeaf = (function () { function LineLeaf(text) { this.text = text; @@ -37860,6 +39465,7 @@ var ts; }; return LineLeaf; })(); + server.LineLeaf = LineLeaf; })(server = ts.server || (ts.server = {})); })(ts || (ts = {})); /// @@ -37969,7 +39575,7 @@ var ts; if (err) { watchedFile.callback(watchedFile.fileName); } - else if (watchedFile.mtime.getTime() != stats.mtime.getTime()) { + else if (watchedFile.mtime.getTime() !== stats.mtime.getTime()) { watchedFile.mtime = WatchedFileSet.getModifiedTime(watchedFile.fileName); watchedFile.callback(watchedFile.fileName); } @@ -37981,7 +39587,7 @@ var ts; var count = 0; var nextToCheck = _this.nextFileToCheck; var firstCheck = -1; - while ((count < _this.chunkSize) && (nextToCheck != firstCheck)) { + while ((count < _this.chunkSize) && (nextToCheck !== firstCheck)) { _this.poll(nextToCheck); if (firstCheck < 0) { firstCheck = nextToCheck; @@ -38015,7 +39621,7 @@ var ts; var IOSession = (function (_super) { __extends(IOSession, _super); function IOSession(host, logger) { - _super.call(this, host, logger); + _super.call(this, host, Buffer.byteLength, process.hrtime, logger); } IOSession.prototype.exit = function () { this.projectService.log("Exiting...", "Info"); diff --git a/bin/typescript.d.ts b/bin/typescript.d.ts index bcb379ed52f..2fd4bb2c2f3 100644 --- a/bin/typescript.d.ts +++ b/bin/typescript.d.ts @@ -17,6 +17,13 @@ declare module "typescript" { interface Map { [index: string]: T; } + interface FileMap { + get(fileName: string): T; + set(fileName: string, value: T): void; + contains(fileName: string): boolean; + remove(fileName: string): void; + forEachValue(f: (v: T) => void): void; + } interface TextRange { pos: number; end: number; @@ -139,134 +146,158 @@ declare module "typescript" { ConstructorKeyword = 114, DeclareKeyword = 115, GetKeyword = 116, - ModuleKeyword = 117, - NamespaceKeyword = 118, - RequireKeyword = 119, - NumberKeyword = 120, - SetKeyword = 121, - StringKeyword = 122, - SymbolKeyword = 123, - TypeKeyword = 124, - FromKeyword = 125, - OfKeyword = 126, - QualifiedName = 127, - ComputedPropertyName = 128, - TypeParameter = 129, - Parameter = 130, - Decorator = 131, - PropertySignature = 132, - PropertyDeclaration = 133, - MethodSignature = 134, - MethodDeclaration = 135, - Constructor = 136, - GetAccessor = 137, - SetAccessor = 138, - CallSignature = 139, - ConstructSignature = 140, - IndexSignature = 141, - TypeReference = 142, - FunctionType = 143, - ConstructorType = 144, - TypeQuery = 145, - TypeLiteral = 146, - ArrayType = 147, - TupleType = 148, - UnionType = 149, - ParenthesizedType = 150, - ObjectBindingPattern = 151, - ArrayBindingPattern = 152, - BindingElement = 153, - ArrayLiteralExpression = 154, - ObjectLiteralExpression = 155, - PropertyAccessExpression = 156, - ElementAccessExpression = 157, - CallExpression = 158, - NewExpression = 159, - TaggedTemplateExpression = 160, - TypeAssertionExpression = 161, - ParenthesizedExpression = 162, - FunctionExpression = 163, - ArrowFunction = 164, - DeleteExpression = 165, - TypeOfExpression = 166, - VoidExpression = 167, - PrefixUnaryExpression = 168, - PostfixUnaryExpression = 169, - BinaryExpression = 170, - ConditionalExpression = 171, - TemplateExpression = 172, - YieldExpression = 173, - SpreadElementExpression = 174, - ClassExpression = 175, - OmittedExpression = 176, - ExpressionWithTypeArguments = 177, - TemplateSpan = 178, - SemicolonClassElement = 179, - Block = 180, - VariableStatement = 181, - EmptyStatement = 182, - ExpressionStatement = 183, - IfStatement = 184, - DoStatement = 185, - WhileStatement = 186, - ForStatement = 187, - ForInStatement = 188, - ForOfStatement = 189, - ContinueStatement = 190, - BreakStatement = 191, - ReturnStatement = 192, - WithStatement = 193, - SwitchStatement = 194, - LabeledStatement = 195, - ThrowStatement = 196, - TryStatement = 197, - DebuggerStatement = 198, - VariableDeclaration = 199, - VariableDeclarationList = 200, - FunctionDeclaration = 201, - ClassDeclaration = 202, - InterfaceDeclaration = 203, - TypeAliasDeclaration = 204, - EnumDeclaration = 205, - ModuleDeclaration = 206, - ModuleBlock = 207, - CaseBlock = 208, - ImportEqualsDeclaration = 209, - ImportDeclaration = 210, - ImportClause = 211, - NamespaceImport = 212, - NamedImports = 213, - ImportSpecifier = 214, - ExportAssignment = 215, - ExportDeclaration = 216, - NamedExports = 217, - ExportSpecifier = 218, - MissingDeclaration = 219, - ExternalModuleReference = 220, - CaseClause = 221, - DefaultClause = 222, - HeritageClause = 223, - CatchClause = 224, - PropertyAssignment = 225, - ShorthandPropertyAssignment = 226, - EnumMember = 227, - SourceFile = 228, - SyntaxList = 229, - Count = 230, + IsKeyword = 117, + ModuleKeyword = 118, + NamespaceKeyword = 119, + RequireKeyword = 120, + NumberKeyword = 121, + SetKeyword = 122, + StringKeyword = 123, + SymbolKeyword = 124, + TypeKeyword = 125, + FromKeyword = 126, + OfKeyword = 127, + QualifiedName = 128, + ComputedPropertyName = 129, + TypeParameter = 130, + Parameter = 131, + Decorator = 132, + PropertySignature = 133, + PropertyDeclaration = 134, + MethodSignature = 135, + MethodDeclaration = 136, + Constructor = 137, + GetAccessor = 138, + SetAccessor = 139, + CallSignature = 140, + ConstructSignature = 141, + IndexSignature = 142, + TypePredicate = 143, + TypeReference = 144, + FunctionType = 145, + ConstructorType = 146, + TypeQuery = 147, + TypeLiteral = 148, + ArrayType = 149, + TupleType = 150, + UnionType = 151, + ParenthesizedType = 152, + ObjectBindingPattern = 153, + ArrayBindingPattern = 154, + BindingElement = 155, + ArrayLiteralExpression = 156, + ObjectLiteralExpression = 157, + PropertyAccessExpression = 158, + ElementAccessExpression = 159, + CallExpression = 160, + NewExpression = 161, + TaggedTemplateExpression = 162, + TypeAssertionExpression = 163, + ParenthesizedExpression = 164, + FunctionExpression = 165, + ArrowFunction = 166, + DeleteExpression = 167, + TypeOfExpression = 168, + VoidExpression = 169, + PrefixUnaryExpression = 170, + PostfixUnaryExpression = 171, + BinaryExpression = 172, + ConditionalExpression = 173, + TemplateExpression = 174, + YieldExpression = 175, + SpreadElementExpression = 176, + ClassExpression = 177, + OmittedExpression = 178, + ExpressionWithTypeArguments = 179, + TemplateSpan = 180, + SemicolonClassElement = 181, + Block = 182, + VariableStatement = 183, + EmptyStatement = 184, + ExpressionStatement = 185, + IfStatement = 186, + DoStatement = 187, + WhileStatement = 188, + ForStatement = 189, + ForInStatement = 190, + ForOfStatement = 191, + ContinueStatement = 192, + BreakStatement = 193, + ReturnStatement = 194, + WithStatement = 195, + SwitchStatement = 196, + LabeledStatement = 197, + ThrowStatement = 198, + TryStatement = 199, + DebuggerStatement = 200, + VariableDeclaration = 201, + VariableDeclarationList = 202, + FunctionDeclaration = 203, + ClassDeclaration = 204, + InterfaceDeclaration = 205, + TypeAliasDeclaration = 206, + EnumDeclaration = 207, + ModuleDeclaration = 208, + ModuleBlock = 209, + CaseBlock = 210, + ImportEqualsDeclaration = 211, + ImportDeclaration = 212, + ImportClause = 213, + NamespaceImport = 214, + NamedImports = 215, + ImportSpecifier = 216, + ExportAssignment = 217, + ExportDeclaration = 218, + NamedExports = 219, + ExportSpecifier = 220, + MissingDeclaration = 221, + ExternalModuleReference = 222, + CaseClause = 223, + DefaultClause = 224, + HeritageClause = 225, + CatchClause = 226, + PropertyAssignment = 227, + ShorthandPropertyAssignment = 228, + EnumMember = 229, + SourceFile = 230, + JSDocTypeExpression = 231, + JSDocAllType = 232, + JSDocUnknownType = 233, + JSDocArrayType = 234, + JSDocUnionType = 235, + JSDocTupleType = 236, + JSDocNullableType = 237, + JSDocNonNullableType = 238, + JSDocRecordType = 239, + JSDocRecordMember = 240, + JSDocTypeReference = 241, + JSDocOptionalType = 242, + JSDocFunctionType = 243, + JSDocVariadicType = 244, + JSDocConstructorType = 245, + JSDocThisType = 246, + JSDocComment = 247, + JSDocTag = 248, + JSDocParameterTag = 249, + JSDocReturnTag = 250, + JSDocTypeTag = 251, + JSDocTemplateTag = 252, + SyntaxList = 253, + Count = 254, FirstAssignment = 53, LastAssignment = 64, FirstReservedWord = 66, LastReservedWord = 101, FirstKeyword = 66, - LastKeyword = 126, + LastKeyword = 127, FirstFutureReservedWord = 102, LastFutureReservedWord = 110, - FirstTypeNode = 142, - LastTypeNode = 150, + FirstTypeNode = 144, + LastTypeNode = 152, FirstPunctuation = 14, LastPunctuation = 64, FirstToken = 0, - LastToken = 126, + LastToken = 127, FirstTriviaToken = 2, LastTriviaToken = 6, FirstLiteralToken = 7, @@ -275,7 +306,7 @@ declare module "typescript" { LastTemplateToken = 13, FirstBinaryOperator = 24, LastBinaryOperator = 64, - FirstNode = 127, + FirstNode = 128, } const enum NodeFlags { Export = 1, @@ -436,6 +467,10 @@ declare module "typescript" { typeName: EntityName; typeArguments?: NodeArray; } + interface TypePredicateNode extends TypeNode { + parameterName: Identifier; + type: TypeNode; + } interface TypeQueryNode extends TypeNode { exprName: EntityName; } @@ -495,7 +530,7 @@ declare module "typescript" { } interface YieldExpression extends Expression { asteriskToken?: Node; - expression: Expression; + expression?: Expression; } interface BinaryExpression extends Expression { left: Expression; @@ -570,7 +605,7 @@ declare module "typescript" { type: TypeNode; expression: UnaryExpression; } - interface Statement extends Node, ModuleElement { + interface Statement extends Node { _statementBrand: any; } interface Block extends Statement { @@ -650,9 +685,6 @@ declare module "typescript" { variableDeclaration: VariableDeclaration; block: Block; } - interface ModuleElement extends Node { - _moduleElementBrand: any; - } interface ClassLikeDeclaration extends Declaration { name?: Identifier; typeParameters?: NodeArray; @@ -666,7 +698,7 @@ declare module "typescript" { interface ClassElement extends Declaration { _classElementBrand: any; } - interface InterfaceDeclaration extends Declaration, ModuleElement { + interface InterfaceDeclaration extends Declaration, Statement { name: Identifier; typeParameters?: NodeArray; heritageClauses?: NodeArray; @@ -676,33 +708,34 @@ declare module "typescript" { token: SyntaxKind; types?: NodeArray; } - interface TypeAliasDeclaration extends Declaration, ModuleElement { + interface TypeAliasDeclaration extends Declaration, Statement { name: Identifier; + typeParameters?: NodeArray; type: TypeNode; } interface EnumMember extends Declaration { name: DeclarationName; initializer?: Expression; } - interface EnumDeclaration extends Declaration, ModuleElement { + interface EnumDeclaration extends Declaration, Statement { name: Identifier; members: NodeArray; } - interface ModuleDeclaration extends Declaration, ModuleElement { + interface ModuleDeclaration extends Declaration, Statement { name: Identifier | LiteralExpression; body: ModuleBlock | ModuleDeclaration; } - interface ModuleBlock extends Node, ModuleElement { - statements: NodeArray; + interface ModuleBlock extends Node, Statement { + statements: NodeArray; } - interface ImportEqualsDeclaration extends Declaration, ModuleElement { + interface ImportEqualsDeclaration extends Declaration, Statement { name: Identifier; moduleReference: EntityName | ExternalModuleReference; } interface ExternalModuleReference extends Node { expression?: Expression; } - interface ImportDeclaration extends ModuleElement { + interface ImportDeclaration extends Statement { importClause?: ImportClause; moduleSpecifier: Expression; } @@ -713,7 +746,7 @@ declare module "typescript" { interface NamespaceImport extends Declaration { name: Identifier; } - interface ExportDeclaration extends Declaration, ModuleElement { + interface ExportDeclaration extends Declaration, Statement { exportClause?: NamedExports; moduleSpecifier?: Expression; } @@ -728,7 +761,7 @@ declare module "typescript" { } type ImportSpecifier = ImportOrExportSpecifier; type ExportSpecifier = ImportOrExportSpecifier; - interface ExportAssignment extends Declaration, ModuleElement { + interface ExportAssignment extends Declaration, Statement { isExportEquals?: boolean; expression: Expression; } @@ -739,8 +772,84 @@ declare module "typescript" { hasTrailingNewLine?: boolean; kind: SyntaxKind; } + interface JSDocTypeExpression extends Node { + type: JSDocType; + } + interface JSDocType extends TypeNode { + _jsDocTypeBrand: any; + } + interface JSDocAllType extends JSDocType { + _JSDocAllTypeBrand: any; + } + interface JSDocUnknownType extends JSDocType { + _JSDocUnknownTypeBrand: any; + } + interface JSDocArrayType extends JSDocType { + elementType: JSDocType; + } + interface JSDocUnionType extends JSDocType { + types: NodeArray; + } + interface JSDocTupleType extends JSDocType { + types: NodeArray; + } + interface JSDocNonNullableType extends JSDocType { + type: JSDocType; + } + interface JSDocNullableType extends JSDocType { + type: JSDocType; + } + interface JSDocRecordType extends JSDocType, TypeLiteralNode { + members: NodeArray; + } + interface JSDocTypeReference extends JSDocType { + name: EntityName; + typeArguments: NodeArray; + } + interface JSDocOptionalType extends JSDocType { + type: JSDocType; + } + interface JSDocFunctionType extends JSDocType, SignatureDeclaration { + parameters: NodeArray; + type: JSDocType; + } + interface JSDocVariadicType extends JSDocType { + type: JSDocType; + } + interface JSDocConstructorType extends JSDocType { + type: JSDocType; + } + interface JSDocThisType extends JSDocType { + type: JSDocType; + } + interface JSDocRecordMember extends PropertyDeclaration { + name: Identifier | LiteralExpression; + type?: JSDocType; + } + interface JSDocComment extends Node { + tags: NodeArray; + } + interface JSDocTag extends Node { + atToken: Node; + tagName: Identifier; + } + interface JSDocTemplateTag extends JSDocTag { + typeParameters: NodeArray; + } + interface JSDocReturnTag extends JSDocTag { + typeExpression: JSDocTypeExpression; + } + interface JSDocTypeTag extends JSDocTag { + typeExpression: JSDocTypeExpression; + } + interface JSDocParameterTag extends JSDocTag { + preParameterName?: Identifier; + typeExpression?: JSDocTypeExpression; + postParameterName?: Identifier; + isBracketed: boolean; + } interface SourceFile extends Declaration { - statements: NodeArray; + statements: NodeArray; endOfFileToken: Node; fileName: string; text: string; @@ -748,8 +857,16 @@ declare module "typescript" { path: string; name: string; }[]; - amdModuleName: string; + moduleName: string; referencedFiles: FileReference[]; + /** + * lib.d.ts should have a reference comment like + * + * /// + * + * If any other file has this comment, it signals not to include lib.d.ts + * because this containing file is intended to act as a default library. + */ hasNoDefaultLib: boolean; languageVersion: ScriptTarget; } @@ -759,7 +876,7 @@ declare module "typescript" { getCurrentDirectory(): string; } interface ParseConfigHost { - readDirectory(rootDir: string, extension: string): string[]; + readDirectory(rootDir: string, extension: string, exclude: string[]): string[]; } interface WriteFileCallback { (fileName: string, data: string, writeByteOrderMark: boolean, onError?: (message: string) => void): void; @@ -780,8 +897,9 @@ declare module "typescript" { * will be invoked when writing the JavaScript and declaration files. */ emit(targetSourceFile?: SourceFile, writeFile?: WriteFileCallback): EmitResult; - getSyntacticDiagnostics(sourceFile?: SourceFile): Diagnostic[]; + getOptionsDiagnostics(): Diagnostic[]; getGlobalDiagnostics(): Diagnostic[]; + getSyntacticDiagnostics(sourceFile?: SourceFile): Diagnostic[]; getSemanticDiagnostics(sourceFile?: SourceFile): Diagnostic[]; getDeclarationDiagnostics(sourceFile?: SourceFile): Diagnostic[]; /** @@ -900,7 +1018,13 @@ declare module "typescript" { WriteTypeParametersOrArguments = 1, UseOnlyExternalAliasing = 2, } + interface TypePredicate { + parameterName: string; + parameterIndex: number; + type: Type; + } const enum SymbolFlags { + None = 0, FunctionScopedVariable = 1, BlockScopedVariable = 2, Property = 4, @@ -959,10 +1083,9 @@ declare module "typescript" { AliasExcludes = 8388608, ModuleMember = 8914931, ExportHasLocal = 944, - HasLocals = 255504, HasExports = 1952, HasMembers = 6240, - IsContainer = 262128, + BlockScoped = 418, PropertyOrAccessor = 98308, Export = 7340032, } @@ -970,9 +1093,9 @@ declare module "typescript" { flags: SymbolFlags; name: string; declarations?: Declaration[]; + valueDeclaration?: Declaration; members?: SymbolTable; exports?: SymbolTable; - valueDeclaration?: Declaration; } interface SymbolTable { [index: string]: Symbol; @@ -994,8 +1117,9 @@ declare module "typescript" { Tuple = 8192, Union = 16384, Anonymous = 32768, - ObjectLiteral = 131072, - ESSymbol = 1048576, + Instantiated = 65536, + ObjectLiteral = 262144, + ESSymbol = 2097152, StringLike = 258, NumberLike = 132, ObjectType = 48128, @@ -1011,9 +1135,10 @@ declare module "typescript" { } interface InterfaceType extends ObjectType { typeParameters: TypeParameter[]; - } - interface InterfaceTypeWithBaseTypes extends InterfaceType { - baseTypes: ObjectType[]; + outerTypeParameters: TypeParameter[]; + localTypeParameters: TypeParameter[]; + resolvedBaseConstructorType?: Type; + resolvedBaseTypes: ObjectType[]; } interface InterfaceTypeWithDeclaredMembers extends InterfaceType { declaredProperties: Symbol[]; @@ -1046,6 +1171,7 @@ declare module "typescript" { declaration: SignatureDeclaration; typeParameters: TypeParameter[]; parameters: Symbol[]; + typePredicate?: TypePredicate; } const enum IndexKind { String = 0, @@ -1114,7 +1240,8 @@ declare module "typescript" { target?: ScriptTarget; version?: boolean; watch?: boolean; - separateCompilation?: boolean; + isolatedModules?: boolean; + experimentalDecorators?: boolean; emitDecoratorMetadata?: boolean; [option: string]: string | number | boolean; } @@ -1181,7 +1308,7 @@ declare module "typescript" { createDirectory(path: string): void; getExecutingFilePath(): string; getCurrentDirectory(): string; - readDirectory(path: string, extension?: string): string[]; + readDirectory(path: string, extension?: string, exclude?: string[]): string[]; getMemoryUsage?(): number; exit(exitCode?: number): void; } @@ -1222,12 +1349,11 @@ declare module "typescript" { function getLineAndCharacterOfPosition(sourceFile: SourceFile, position: number): LineAndCharacter; function isWhiteSpace(ch: number): boolean; function isLineBreak(ch: number): boolean; + function couldStartTrivia(text: string, pos: number): boolean; function getLeadingCommentRanges(text: string, pos: number): CommentRange[]; function getTrailingCommentRanges(text: string, pos: number): CommentRange[]; function isIdentifierStart(ch: number, languageVersion: ScriptTarget): boolean; function isIdentifierPart(ch: number, languageVersion: ScriptTarget): boolean; - /** Creates a scanner over a (possibly unspecified) range of a piece of text. */ - function createScanner(languageVersion: ScriptTarget, skipTrivia: boolean, text?: string, onError?: ErrorCallback, start?: number, length?: number): Scanner; } declare module "typescript" { function getDefaultLibFileName(options: CompilerOptions): string; @@ -1239,6 +1365,7 @@ declare module "typescript" { 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; @@ -1256,6 +1383,7 @@ declare module "typescript" { * Vn. */ function collapseTextChangeRangesAcrossMultipleVersions(changes: TextChangeRange[]): TextChangeRange; + function getTypeParameterOwner(d: Declaration): Declaration; } declare module "typescript" { function getNodeConstructor(kind: SyntaxKind): new () => Node; @@ -1390,6 +1518,7 @@ declare module "typescript" { log?(s: string): void; trace?(s: string): void; error?(s: string): void; + useCaseSensitiveFileNames?(): boolean; } interface LanguageService { cleanupSemanticCache(): void; @@ -1812,6 +1941,7 @@ declare module "typescript" { static typeParameterName: string; static typeAliasName: string; static parameterName: string; + static docCommentTagName: string; } const enum ClassificationType { comment = 1, @@ -1831,6 +1961,7 @@ declare module "typescript" { typeParameterName = 15, typeAliasName = 16, parameterName = 17, + docCommentTagName = 18, } interface DisplayPartsSymbolWriter extends SymbolWriter { displayParts(): SymbolDisplayPart[]; @@ -1846,11 +1977,11 @@ declare module "typescript" { isCancellationRequested(): boolean; throwIfCancellationRequested(): void; } - function transpile(input: string, compilerOptions?: CompilerOptions, fileName?: string, diagnostics?: Diagnostic[]): string; + function transpile(input: string, compilerOptions?: CompilerOptions, fileName?: string, diagnostics?: Diagnostic[], moduleName?: string): string; function createLanguageServiceSourceFile(fileName: string, scriptSnapshot: IScriptSnapshot, scriptTarget: ScriptTarget, version: string, setNodeParents: boolean): SourceFile; let disableIncrementalParsing: boolean; function updateLanguageServiceSourceFile(sourceFile: SourceFile, scriptSnapshot: IScriptSnapshot, version: string, textChangeRange: TextChangeRange, aggressiveChecks?: boolean): SourceFile; - function createDocumentRegistry(): DocumentRegistry; + function createDocumentRegistry(useCaseSensitiveFileNames?: boolean): DocumentRegistry; function preProcessFile(sourceText: string, readImportFiles?: boolean): PreProcessedFileInfo; function createLanguageService(host: LanguageServiceHost, documentRegistry?: DocumentRegistry): LanguageService; function createClassifier(): Classifier; diff --git a/bin/typescript.js b/bin/typescript.js index 4cab75bfcb6..6989f225452 100644 --- a/bin/typescript.js +++ b/bin/typescript.js @@ -144,151 +144,178 @@ var ts; SyntaxKind[SyntaxKind["ConstructorKeyword"] = 114] = "ConstructorKeyword"; SyntaxKind[SyntaxKind["DeclareKeyword"] = 115] = "DeclareKeyword"; SyntaxKind[SyntaxKind["GetKeyword"] = 116] = "GetKeyword"; - SyntaxKind[SyntaxKind["ModuleKeyword"] = 117] = "ModuleKeyword"; - SyntaxKind[SyntaxKind["NamespaceKeyword"] = 118] = "NamespaceKeyword"; - SyntaxKind[SyntaxKind["RequireKeyword"] = 119] = "RequireKeyword"; - SyntaxKind[SyntaxKind["NumberKeyword"] = 120] = "NumberKeyword"; - SyntaxKind[SyntaxKind["SetKeyword"] = 121] = "SetKeyword"; - SyntaxKind[SyntaxKind["StringKeyword"] = 122] = "StringKeyword"; - SyntaxKind[SyntaxKind["SymbolKeyword"] = 123] = "SymbolKeyword"; - SyntaxKind[SyntaxKind["TypeKeyword"] = 124] = "TypeKeyword"; - SyntaxKind[SyntaxKind["FromKeyword"] = 125] = "FromKeyword"; - SyntaxKind[SyntaxKind["OfKeyword"] = 126] = "OfKeyword"; + SyntaxKind[SyntaxKind["IsKeyword"] = 117] = "IsKeyword"; + SyntaxKind[SyntaxKind["ModuleKeyword"] = 118] = "ModuleKeyword"; + SyntaxKind[SyntaxKind["NamespaceKeyword"] = 119] = "NamespaceKeyword"; + SyntaxKind[SyntaxKind["RequireKeyword"] = 120] = "RequireKeyword"; + SyntaxKind[SyntaxKind["NumberKeyword"] = 121] = "NumberKeyword"; + SyntaxKind[SyntaxKind["SetKeyword"] = 122] = "SetKeyword"; + SyntaxKind[SyntaxKind["StringKeyword"] = 123] = "StringKeyword"; + SyntaxKind[SyntaxKind["SymbolKeyword"] = 124] = "SymbolKeyword"; + SyntaxKind[SyntaxKind["TypeKeyword"] = 125] = "TypeKeyword"; + SyntaxKind[SyntaxKind["FromKeyword"] = 126] = "FromKeyword"; + SyntaxKind[SyntaxKind["OfKeyword"] = 127] = "OfKeyword"; // Parse tree nodes // Names - SyntaxKind[SyntaxKind["QualifiedName"] = 127] = "QualifiedName"; - SyntaxKind[SyntaxKind["ComputedPropertyName"] = 128] = "ComputedPropertyName"; + SyntaxKind[SyntaxKind["QualifiedName"] = 128] = "QualifiedName"; + SyntaxKind[SyntaxKind["ComputedPropertyName"] = 129] = "ComputedPropertyName"; // Signature elements - SyntaxKind[SyntaxKind["TypeParameter"] = 129] = "TypeParameter"; - SyntaxKind[SyntaxKind["Parameter"] = 130] = "Parameter"; - SyntaxKind[SyntaxKind["Decorator"] = 131] = "Decorator"; + SyntaxKind[SyntaxKind["TypeParameter"] = 130] = "TypeParameter"; + SyntaxKind[SyntaxKind["Parameter"] = 131] = "Parameter"; + SyntaxKind[SyntaxKind["Decorator"] = 132] = "Decorator"; // TypeMember - SyntaxKind[SyntaxKind["PropertySignature"] = 132] = "PropertySignature"; - SyntaxKind[SyntaxKind["PropertyDeclaration"] = 133] = "PropertyDeclaration"; - SyntaxKind[SyntaxKind["MethodSignature"] = 134] = "MethodSignature"; - SyntaxKind[SyntaxKind["MethodDeclaration"] = 135] = "MethodDeclaration"; - SyntaxKind[SyntaxKind["Constructor"] = 136] = "Constructor"; - SyntaxKind[SyntaxKind["GetAccessor"] = 137] = "GetAccessor"; - SyntaxKind[SyntaxKind["SetAccessor"] = 138] = "SetAccessor"; - SyntaxKind[SyntaxKind["CallSignature"] = 139] = "CallSignature"; - SyntaxKind[SyntaxKind["ConstructSignature"] = 140] = "ConstructSignature"; - SyntaxKind[SyntaxKind["IndexSignature"] = 141] = "IndexSignature"; + SyntaxKind[SyntaxKind["PropertySignature"] = 133] = "PropertySignature"; + SyntaxKind[SyntaxKind["PropertyDeclaration"] = 134] = "PropertyDeclaration"; + SyntaxKind[SyntaxKind["MethodSignature"] = 135] = "MethodSignature"; + SyntaxKind[SyntaxKind["MethodDeclaration"] = 136] = "MethodDeclaration"; + SyntaxKind[SyntaxKind["Constructor"] = 137] = "Constructor"; + SyntaxKind[SyntaxKind["GetAccessor"] = 138] = "GetAccessor"; + SyntaxKind[SyntaxKind["SetAccessor"] = 139] = "SetAccessor"; + SyntaxKind[SyntaxKind["CallSignature"] = 140] = "CallSignature"; + SyntaxKind[SyntaxKind["ConstructSignature"] = 141] = "ConstructSignature"; + SyntaxKind[SyntaxKind["IndexSignature"] = 142] = "IndexSignature"; // Type - SyntaxKind[SyntaxKind["TypeReference"] = 142] = "TypeReference"; - SyntaxKind[SyntaxKind["FunctionType"] = 143] = "FunctionType"; - SyntaxKind[SyntaxKind["ConstructorType"] = 144] = "ConstructorType"; - SyntaxKind[SyntaxKind["TypeQuery"] = 145] = "TypeQuery"; - SyntaxKind[SyntaxKind["TypeLiteral"] = 146] = "TypeLiteral"; - SyntaxKind[SyntaxKind["ArrayType"] = 147] = "ArrayType"; - SyntaxKind[SyntaxKind["TupleType"] = 148] = "TupleType"; - SyntaxKind[SyntaxKind["UnionType"] = 149] = "UnionType"; - SyntaxKind[SyntaxKind["ParenthesizedType"] = 150] = "ParenthesizedType"; + SyntaxKind[SyntaxKind["TypePredicate"] = 143] = "TypePredicate"; + SyntaxKind[SyntaxKind["TypeReference"] = 144] = "TypeReference"; + SyntaxKind[SyntaxKind["FunctionType"] = 145] = "FunctionType"; + SyntaxKind[SyntaxKind["ConstructorType"] = 146] = "ConstructorType"; + SyntaxKind[SyntaxKind["TypeQuery"] = 147] = "TypeQuery"; + SyntaxKind[SyntaxKind["TypeLiteral"] = 148] = "TypeLiteral"; + SyntaxKind[SyntaxKind["ArrayType"] = 149] = "ArrayType"; + SyntaxKind[SyntaxKind["TupleType"] = 150] = "TupleType"; + SyntaxKind[SyntaxKind["UnionType"] = 151] = "UnionType"; + SyntaxKind[SyntaxKind["ParenthesizedType"] = 152] = "ParenthesizedType"; // Binding patterns - SyntaxKind[SyntaxKind["ObjectBindingPattern"] = 151] = "ObjectBindingPattern"; - SyntaxKind[SyntaxKind["ArrayBindingPattern"] = 152] = "ArrayBindingPattern"; - SyntaxKind[SyntaxKind["BindingElement"] = 153] = "BindingElement"; + SyntaxKind[SyntaxKind["ObjectBindingPattern"] = 153] = "ObjectBindingPattern"; + SyntaxKind[SyntaxKind["ArrayBindingPattern"] = 154] = "ArrayBindingPattern"; + SyntaxKind[SyntaxKind["BindingElement"] = 155] = "BindingElement"; // Expression - SyntaxKind[SyntaxKind["ArrayLiteralExpression"] = 154] = "ArrayLiteralExpression"; - SyntaxKind[SyntaxKind["ObjectLiteralExpression"] = 155] = "ObjectLiteralExpression"; - SyntaxKind[SyntaxKind["PropertyAccessExpression"] = 156] = "PropertyAccessExpression"; - SyntaxKind[SyntaxKind["ElementAccessExpression"] = 157] = "ElementAccessExpression"; - SyntaxKind[SyntaxKind["CallExpression"] = 158] = "CallExpression"; - SyntaxKind[SyntaxKind["NewExpression"] = 159] = "NewExpression"; - SyntaxKind[SyntaxKind["TaggedTemplateExpression"] = 160] = "TaggedTemplateExpression"; - SyntaxKind[SyntaxKind["TypeAssertionExpression"] = 161] = "TypeAssertionExpression"; - SyntaxKind[SyntaxKind["ParenthesizedExpression"] = 162] = "ParenthesizedExpression"; - SyntaxKind[SyntaxKind["FunctionExpression"] = 163] = "FunctionExpression"; - SyntaxKind[SyntaxKind["ArrowFunction"] = 164] = "ArrowFunction"; - SyntaxKind[SyntaxKind["DeleteExpression"] = 165] = "DeleteExpression"; - SyntaxKind[SyntaxKind["TypeOfExpression"] = 166] = "TypeOfExpression"; - SyntaxKind[SyntaxKind["VoidExpression"] = 167] = "VoidExpression"; - SyntaxKind[SyntaxKind["PrefixUnaryExpression"] = 168] = "PrefixUnaryExpression"; - SyntaxKind[SyntaxKind["PostfixUnaryExpression"] = 169] = "PostfixUnaryExpression"; - SyntaxKind[SyntaxKind["BinaryExpression"] = 170] = "BinaryExpression"; - SyntaxKind[SyntaxKind["ConditionalExpression"] = 171] = "ConditionalExpression"; - SyntaxKind[SyntaxKind["TemplateExpression"] = 172] = "TemplateExpression"; - SyntaxKind[SyntaxKind["YieldExpression"] = 173] = "YieldExpression"; - SyntaxKind[SyntaxKind["SpreadElementExpression"] = 174] = "SpreadElementExpression"; - SyntaxKind[SyntaxKind["ClassExpression"] = 175] = "ClassExpression"; - SyntaxKind[SyntaxKind["OmittedExpression"] = 176] = "OmittedExpression"; - SyntaxKind[SyntaxKind["ExpressionWithTypeArguments"] = 177] = "ExpressionWithTypeArguments"; + SyntaxKind[SyntaxKind["ArrayLiteralExpression"] = 156] = "ArrayLiteralExpression"; + SyntaxKind[SyntaxKind["ObjectLiteralExpression"] = 157] = "ObjectLiteralExpression"; + SyntaxKind[SyntaxKind["PropertyAccessExpression"] = 158] = "PropertyAccessExpression"; + SyntaxKind[SyntaxKind["ElementAccessExpression"] = 159] = "ElementAccessExpression"; + SyntaxKind[SyntaxKind["CallExpression"] = 160] = "CallExpression"; + SyntaxKind[SyntaxKind["NewExpression"] = 161] = "NewExpression"; + SyntaxKind[SyntaxKind["TaggedTemplateExpression"] = 162] = "TaggedTemplateExpression"; + SyntaxKind[SyntaxKind["TypeAssertionExpression"] = 163] = "TypeAssertionExpression"; + SyntaxKind[SyntaxKind["ParenthesizedExpression"] = 164] = "ParenthesizedExpression"; + SyntaxKind[SyntaxKind["FunctionExpression"] = 165] = "FunctionExpression"; + SyntaxKind[SyntaxKind["ArrowFunction"] = 166] = "ArrowFunction"; + SyntaxKind[SyntaxKind["DeleteExpression"] = 167] = "DeleteExpression"; + SyntaxKind[SyntaxKind["TypeOfExpression"] = 168] = "TypeOfExpression"; + SyntaxKind[SyntaxKind["VoidExpression"] = 169] = "VoidExpression"; + SyntaxKind[SyntaxKind["PrefixUnaryExpression"] = 170] = "PrefixUnaryExpression"; + SyntaxKind[SyntaxKind["PostfixUnaryExpression"] = 171] = "PostfixUnaryExpression"; + SyntaxKind[SyntaxKind["BinaryExpression"] = 172] = "BinaryExpression"; + SyntaxKind[SyntaxKind["ConditionalExpression"] = 173] = "ConditionalExpression"; + SyntaxKind[SyntaxKind["TemplateExpression"] = 174] = "TemplateExpression"; + SyntaxKind[SyntaxKind["YieldExpression"] = 175] = "YieldExpression"; + SyntaxKind[SyntaxKind["SpreadElementExpression"] = 176] = "SpreadElementExpression"; + SyntaxKind[SyntaxKind["ClassExpression"] = 177] = "ClassExpression"; + SyntaxKind[SyntaxKind["OmittedExpression"] = 178] = "OmittedExpression"; + SyntaxKind[SyntaxKind["ExpressionWithTypeArguments"] = 179] = "ExpressionWithTypeArguments"; // Misc - SyntaxKind[SyntaxKind["TemplateSpan"] = 178] = "TemplateSpan"; - SyntaxKind[SyntaxKind["SemicolonClassElement"] = 179] = "SemicolonClassElement"; + SyntaxKind[SyntaxKind["TemplateSpan"] = 180] = "TemplateSpan"; + SyntaxKind[SyntaxKind["SemicolonClassElement"] = 181] = "SemicolonClassElement"; // Element - SyntaxKind[SyntaxKind["Block"] = 180] = "Block"; - SyntaxKind[SyntaxKind["VariableStatement"] = 181] = "VariableStatement"; - SyntaxKind[SyntaxKind["EmptyStatement"] = 182] = "EmptyStatement"; - SyntaxKind[SyntaxKind["ExpressionStatement"] = 183] = "ExpressionStatement"; - SyntaxKind[SyntaxKind["IfStatement"] = 184] = "IfStatement"; - SyntaxKind[SyntaxKind["DoStatement"] = 185] = "DoStatement"; - SyntaxKind[SyntaxKind["WhileStatement"] = 186] = "WhileStatement"; - SyntaxKind[SyntaxKind["ForStatement"] = 187] = "ForStatement"; - SyntaxKind[SyntaxKind["ForInStatement"] = 188] = "ForInStatement"; - SyntaxKind[SyntaxKind["ForOfStatement"] = 189] = "ForOfStatement"; - SyntaxKind[SyntaxKind["ContinueStatement"] = 190] = "ContinueStatement"; - SyntaxKind[SyntaxKind["BreakStatement"] = 191] = "BreakStatement"; - SyntaxKind[SyntaxKind["ReturnStatement"] = 192] = "ReturnStatement"; - SyntaxKind[SyntaxKind["WithStatement"] = 193] = "WithStatement"; - SyntaxKind[SyntaxKind["SwitchStatement"] = 194] = "SwitchStatement"; - SyntaxKind[SyntaxKind["LabeledStatement"] = 195] = "LabeledStatement"; - SyntaxKind[SyntaxKind["ThrowStatement"] = 196] = "ThrowStatement"; - SyntaxKind[SyntaxKind["TryStatement"] = 197] = "TryStatement"; - SyntaxKind[SyntaxKind["DebuggerStatement"] = 198] = "DebuggerStatement"; - SyntaxKind[SyntaxKind["VariableDeclaration"] = 199] = "VariableDeclaration"; - SyntaxKind[SyntaxKind["VariableDeclarationList"] = 200] = "VariableDeclarationList"; - SyntaxKind[SyntaxKind["FunctionDeclaration"] = 201] = "FunctionDeclaration"; - SyntaxKind[SyntaxKind["ClassDeclaration"] = 202] = "ClassDeclaration"; - SyntaxKind[SyntaxKind["InterfaceDeclaration"] = 203] = "InterfaceDeclaration"; - SyntaxKind[SyntaxKind["TypeAliasDeclaration"] = 204] = "TypeAliasDeclaration"; - SyntaxKind[SyntaxKind["EnumDeclaration"] = 205] = "EnumDeclaration"; - SyntaxKind[SyntaxKind["ModuleDeclaration"] = 206] = "ModuleDeclaration"; - SyntaxKind[SyntaxKind["ModuleBlock"] = 207] = "ModuleBlock"; - SyntaxKind[SyntaxKind["CaseBlock"] = 208] = "CaseBlock"; - SyntaxKind[SyntaxKind["ImportEqualsDeclaration"] = 209] = "ImportEqualsDeclaration"; - SyntaxKind[SyntaxKind["ImportDeclaration"] = 210] = "ImportDeclaration"; - SyntaxKind[SyntaxKind["ImportClause"] = 211] = "ImportClause"; - SyntaxKind[SyntaxKind["NamespaceImport"] = 212] = "NamespaceImport"; - SyntaxKind[SyntaxKind["NamedImports"] = 213] = "NamedImports"; - SyntaxKind[SyntaxKind["ImportSpecifier"] = 214] = "ImportSpecifier"; - SyntaxKind[SyntaxKind["ExportAssignment"] = 215] = "ExportAssignment"; - SyntaxKind[SyntaxKind["ExportDeclaration"] = 216] = "ExportDeclaration"; - SyntaxKind[SyntaxKind["NamedExports"] = 217] = "NamedExports"; - SyntaxKind[SyntaxKind["ExportSpecifier"] = 218] = "ExportSpecifier"; - SyntaxKind[SyntaxKind["MissingDeclaration"] = 219] = "MissingDeclaration"; + SyntaxKind[SyntaxKind["Block"] = 182] = "Block"; + SyntaxKind[SyntaxKind["VariableStatement"] = 183] = "VariableStatement"; + SyntaxKind[SyntaxKind["EmptyStatement"] = 184] = "EmptyStatement"; + SyntaxKind[SyntaxKind["ExpressionStatement"] = 185] = "ExpressionStatement"; + SyntaxKind[SyntaxKind["IfStatement"] = 186] = "IfStatement"; + SyntaxKind[SyntaxKind["DoStatement"] = 187] = "DoStatement"; + SyntaxKind[SyntaxKind["WhileStatement"] = 188] = "WhileStatement"; + SyntaxKind[SyntaxKind["ForStatement"] = 189] = "ForStatement"; + SyntaxKind[SyntaxKind["ForInStatement"] = 190] = "ForInStatement"; + SyntaxKind[SyntaxKind["ForOfStatement"] = 191] = "ForOfStatement"; + SyntaxKind[SyntaxKind["ContinueStatement"] = 192] = "ContinueStatement"; + SyntaxKind[SyntaxKind["BreakStatement"] = 193] = "BreakStatement"; + SyntaxKind[SyntaxKind["ReturnStatement"] = 194] = "ReturnStatement"; + SyntaxKind[SyntaxKind["WithStatement"] = 195] = "WithStatement"; + SyntaxKind[SyntaxKind["SwitchStatement"] = 196] = "SwitchStatement"; + SyntaxKind[SyntaxKind["LabeledStatement"] = 197] = "LabeledStatement"; + SyntaxKind[SyntaxKind["ThrowStatement"] = 198] = "ThrowStatement"; + SyntaxKind[SyntaxKind["TryStatement"] = 199] = "TryStatement"; + SyntaxKind[SyntaxKind["DebuggerStatement"] = 200] = "DebuggerStatement"; + SyntaxKind[SyntaxKind["VariableDeclaration"] = 201] = "VariableDeclaration"; + SyntaxKind[SyntaxKind["VariableDeclarationList"] = 202] = "VariableDeclarationList"; + SyntaxKind[SyntaxKind["FunctionDeclaration"] = 203] = "FunctionDeclaration"; + SyntaxKind[SyntaxKind["ClassDeclaration"] = 204] = "ClassDeclaration"; + SyntaxKind[SyntaxKind["InterfaceDeclaration"] = 205] = "InterfaceDeclaration"; + SyntaxKind[SyntaxKind["TypeAliasDeclaration"] = 206] = "TypeAliasDeclaration"; + SyntaxKind[SyntaxKind["EnumDeclaration"] = 207] = "EnumDeclaration"; + SyntaxKind[SyntaxKind["ModuleDeclaration"] = 208] = "ModuleDeclaration"; + SyntaxKind[SyntaxKind["ModuleBlock"] = 209] = "ModuleBlock"; + SyntaxKind[SyntaxKind["CaseBlock"] = 210] = "CaseBlock"; + SyntaxKind[SyntaxKind["ImportEqualsDeclaration"] = 211] = "ImportEqualsDeclaration"; + SyntaxKind[SyntaxKind["ImportDeclaration"] = 212] = "ImportDeclaration"; + SyntaxKind[SyntaxKind["ImportClause"] = 213] = "ImportClause"; + SyntaxKind[SyntaxKind["NamespaceImport"] = 214] = "NamespaceImport"; + SyntaxKind[SyntaxKind["NamedImports"] = 215] = "NamedImports"; + SyntaxKind[SyntaxKind["ImportSpecifier"] = 216] = "ImportSpecifier"; + SyntaxKind[SyntaxKind["ExportAssignment"] = 217] = "ExportAssignment"; + SyntaxKind[SyntaxKind["ExportDeclaration"] = 218] = "ExportDeclaration"; + SyntaxKind[SyntaxKind["NamedExports"] = 219] = "NamedExports"; + SyntaxKind[SyntaxKind["ExportSpecifier"] = 220] = "ExportSpecifier"; + SyntaxKind[SyntaxKind["MissingDeclaration"] = 221] = "MissingDeclaration"; // Module references - SyntaxKind[SyntaxKind["ExternalModuleReference"] = 220] = "ExternalModuleReference"; + SyntaxKind[SyntaxKind["ExternalModuleReference"] = 222] = "ExternalModuleReference"; // Clauses - SyntaxKind[SyntaxKind["CaseClause"] = 221] = "CaseClause"; - SyntaxKind[SyntaxKind["DefaultClause"] = 222] = "DefaultClause"; - SyntaxKind[SyntaxKind["HeritageClause"] = 223] = "HeritageClause"; - SyntaxKind[SyntaxKind["CatchClause"] = 224] = "CatchClause"; + SyntaxKind[SyntaxKind["CaseClause"] = 223] = "CaseClause"; + SyntaxKind[SyntaxKind["DefaultClause"] = 224] = "DefaultClause"; + SyntaxKind[SyntaxKind["HeritageClause"] = 225] = "HeritageClause"; + SyntaxKind[SyntaxKind["CatchClause"] = 226] = "CatchClause"; // Property assignments - SyntaxKind[SyntaxKind["PropertyAssignment"] = 225] = "PropertyAssignment"; - SyntaxKind[SyntaxKind["ShorthandPropertyAssignment"] = 226] = "ShorthandPropertyAssignment"; + SyntaxKind[SyntaxKind["PropertyAssignment"] = 227] = "PropertyAssignment"; + SyntaxKind[SyntaxKind["ShorthandPropertyAssignment"] = 228] = "ShorthandPropertyAssignment"; // Enum - SyntaxKind[SyntaxKind["EnumMember"] = 227] = "EnumMember"; + SyntaxKind[SyntaxKind["EnumMember"] = 229] = "EnumMember"; // Top-level nodes - SyntaxKind[SyntaxKind["SourceFile"] = 228] = "SourceFile"; + SyntaxKind[SyntaxKind["SourceFile"] = 230] = "SourceFile"; + // JSDoc nodes. + SyntaxKind[SyntaxKind["JSDocTypeExpression"] = 231] = "JSDocTypeExpression"; + // The * type. + SyntaxKind[SyntaxKind["JSDocAllType"] = 232] = "JSDocAllType"; + // The ? type. + SyntaxKind[SyntaxKind["JSDocUnknownType"] = 233] = "JSDocUnknownType"; + SyntaxKind[SyntaxKind["JSDocArrayType"] = 234] = "JSDocArrayType"; + SyntaxKind[SyntaxKind["JSDocUnionType"] = 235] = "JSDocUnionType"; + SyntaxKind[SyntaxKind["JSDocTupleType"] = 236] = "JSDocTupleType"; + SyntaxKind[SyntaxKind["JSDocNullableType"] = 237] = "JSDocNullableType"; + SyntaxKind[SyntaxKind["JSDocNonNullableType"] = 238] = "JSDocNonNullableType"; + SyntaxKind[SyntaxKind["JSDocRecordType"] = 239] = "JSDocRecordType"; + SyntaxKind[SyntaxKind["JSDocRecordMember"] = 240] = "JSDocRecordMember"; + SyntaxKind[SyntaxKind["JSDocTypeReference"] = 241] = "JSDocTypeReference"; + SyntaxKind[SyntaxKind["JSDocOptionalType"] = 242] = "JSDocOptionalType"; + SyntaxKind[SyntaxKind["JSDocFunctionType"] = 243] = "JSDocFunctionType"; + SyntaxKind[SyntaxKind["JSDocVariadicType"] = 244] = "JSDocVariadicType"; + SyntaxKind[SyntaxKind["JSDocConstructorType"] = 245] = "JSDocConstructorType"; + SyntaxKind[SyntaxKind["JSDocThisType"] = 246] = "JSDocThisType"; + SyntaxKind[SyntaxKind["JSDocComment"] = 247] = "JSDocComment"; + SyntaxKind[SyntaxKind["JSDocTag"] = 248] = "JSDocTag"; + SyntaxKind[SyntaxKind["JSDocParameterTag"] = 249] = "JSDocParameterTag"; + SyntaxKind[SyntaxKind["JSDocReturnTag"] = 250] = "JSDocReturnTag"; + SyntaxKind[SyntaxKind["JSDocTypeTag"] = 251] = "JSDocTypeTag"; + SyntaxKind[SyntaxKind["JSDocTemplateTag"] = 252] = "JSDocTemplateTag"; // Synthesized list - SyntaxKind[SyntaxKind["SyntaxList"] = 229] = "SyntaxList"; + SyntaxKind[SyntaxKind["SyntaxList"] = 253] = "SyntaxList"; // Enum value count - SyntaxKind[SyntaxKind["Count"] = 230] = "Count"; + SyntaxKind[SyntaxKind["Count"] = 254] = "Count"; // Markers SyntaxKind[SyntaxKind["FirstAssignment"] = 53] = "FirstAssignment"; SyntaxKind[SyntaxKind["LastAssignment"] = 64] = "LastAssignment"; SyntaxKind[SyntaxKind["FirstReservedWord"] = 66] = "FirstReservedWord"; SyntaxKind[SyntaxKind["LastReservedWord"] = 101] = "LastReservedWord"; SyntaxKind[SyntaxKind["FirstKeyword"] = 66] = "FirstKeyword"; - SyntaxKind[SyntaxKind["LastKeyword"] = 126] = "LastKeyword"; + SyntaxKind[SyntaxKind["LastKeyword"] = 127] = "LastKeyword"; SyntaxKind[SyntaxKind["FirstFutureReservedWord"] = 102] = "FirstFutureReservedWord"; SyntaxKind[SyntaxKind["LastFutureReservedWord"] = 110] = "LastFutureReservedWord"; - SyntaxKind[SyntaxKind["FirstTypeNode"] = 142] = "FirstTypeNode"; - SyntaxKind[SyntaxKind["LastTypeNode"] = 150] = "LastTypeNode"; + SyntaxKind[SyntaxKind["FirstTypeNode"] = 144] = "FirstTypeNode"; + SyntaxKind[SyntaxKind["LastTypeNode"] = 152] = "LastTypeNode"; SyntaxKind[SyntaxKind["FirstPunctuation"] = 14] = "FirstPunctuation"; SyntaxKind[SyntaxKind["LastPunctuation"] = 64] = "LastPunctuation"; SyntaxKind[SyntaxKind["FirstToken"] = 0] = "FirstToken"; - SyntaxKind[SyntaxKind["LastToken"] = 126] = "LastToken"; + SyntaxKind[SyntaxKind["LastToken"] = 127] = "LastToken"; SyntaxKind[SyntaxKind["FirstTriviaToken"] = 2] = "FirstTriviaToken"; SyntaxKind[SyntaxKind["LastTriviaToken"] = 6] = "LastTriviaToken"; SyntaxKind[SyntaxKind["FirstLiteralToken"] = 7] = "FirstLiteralToken"; @@ -297,7 +324,7 @@ var ts; SyntaxKind[SyntaxKind["LastTemplateToken"] = 13] = "LastTemplateToken"; SyntaxKind[SyntaxKind["FirstBinaryOperator"] = 24] = "FirstBinaryOperator"; SyntaxKind[SyntaxKind["LastBinaryOperator"] = 64] = "LastBinaryOperator"; - SyntaxKind[SyntaxKind["FirstNode"] = 127] = "FirstNode"; + SyntaxKind[SyntaxKind["FirstNode"] = 128] = "FirstNode"; })(ts.SyntaxKind || (ts.SyntaxKind = {})); var SyntaxKind = ts.SyntaxKind; (function (NodeFlags) { @@ -323,9 +350,7 @@ var ts; var NodeFlags = ts.NodeFlags; /* @internal */ (function (ParserContextFlags) { - // Set if this node was parsed in strict mode. Used for grammar error checks, as well as - // checking if the node can be reused in incremental settings. - ParserContextFlags[ParserContextFlags["StrictMode"] = 1] = "StrictMode"; + ParserContextFlags[ParserContextFlags["None"] = 0] = "None"; // If this node was parsed in a context where 'in-expressions' are not allowed. ParserContextFlags[ParserContextFlags["DisallowIn"] = 2] = "DisallowIn"; // If this node was parsed in the 'yield' context created when parsing a generator. @@ -338,14 +363,17 @@ var ts; // the parser only sets this directly on the node it creates right after encountering the // error. ParserContextFlags[ParserContextFlags["ThisNodeHasError"] = 32] = "ThisNodeHasError"; + // This node was parsed in a JavaScript file and can be processed differently. For example + // its type can be specified usign a JSDoc comment. + ParserContextFlags[ParserContextFlags["JavaScriptFile"] = 64] = "JavaScriptFile"; // Context flags set directly by the parser. - ParserContextFlags[ParserContextFlags["ParserGeneratedFlags"] = 63] = "ParserGeneratedFlags"; + ParserContextFlags[ParserContextFlags["ParserGeneratedFlags"] = 62] = "ParserGeneratedFlags"; // Context flags computed by aggregating child flags upwards. // Used during incremental parsing to determine if this node or any of its children had an // error. Computed only once and then cached. - ParserContextFlags[ParserContextFlags["ThisNodeOrAnySubNodesHasError"] = 64] = "ThisNodeOrAnySubNodesHasError"; + ParserContextFlags[ParserContextFlags["ThisNodeOrAnySubNodesHasError"] = 128] = "ThisNodeOrAnySubNodesHasError"; // Used to know if we've computed data from children and cached it in this node. - ParserContextFlags[ParserContextFlags["HasAggregatedChildData"] = 128] = "HasAggregatedChildData"; + ParserContextFlags[ParserContextFlags["HasAggregatedChildData"] = 256] = "HasAggregatedChildData"; })(ts.ParserContextFlags || (ts.ParserContextFlags = {})); var ParserContextFlags = ts.ParserContextFlags; /* @internal */ @@ -400,6 +428,7 @@ var ts; })(ts.SymbolAccessibility || (ts.SymbolAccessibility = {})); var SymbolAccessibility = ts.SymbolAccessibility; (function (SymbolFlags) { + SymbolFlags[SymbolFlags["None"] = 0] = "None"; SymbolFlags[SymbolFlags["FunctionScopedVariable"] = 1] = "FunctionScopedVariable"; SymbolFlags[SymbolFlags["BlockScopedVariable"] = 2] = "BlockScopedVariable"; SymbolFlags[SymbolFlags["Property"] = 4] = "Property"; @@ -462,12 +491,15 @@ var ts; SymbolFlags[SymbolFlags["AliasExcludes"] = 8388608] = "AliasExcludes"; SymbolFlags[SymbolFlags["ModuleMember"] = 8914931] = "ModuleMember"; SymbolFlags[SymbolFlags["ExportHasLocal"] = 944] = "ExportHasLocal"; - SymbolFlags[SymbolFlags["HasLocals"] = 255504] = "HasLocals"; SymbolFlags[SymbolFlags["HasExports"] = 1952] = "HasExports"; SymbolFlags[SymbolFlags["HasMembers"] = 6240] = "HasMembers"; - SymbolFlags[SymbolFlags["IsContainer"] = 262128] = "IsContainer"; + SymbolFlags[SymbolFlags["BlockScoped"] = 418] = "BlockScoped"; SymbolFlags[SymbolFlags["PropertyOrAccessor"] = 98308] = "PropertyOrAccessor"; SymbolFlags[SymbolFlags["Export"] = 7340032] = "Export"; + /* @internal */ + // The set of things we consider semantically classifiable. Used to speed up the LS during + // classification. + SymbolFlags[SymbolFlags["Classifiable"] = 788448] = "Classifiable"; })(ts.SymbolFlags || (ts.SymbolFlags = {})); var SymbolFlags = ts.SymbolFlags; /* @internal */ @@ -504,23 +536,24 @@ var ts; TypeFlags[TypeFlags["Tuple"] = 8192] = "Tuple"; TypeFlags[TypeFlags["Union"] = 16384] = "Union"; TypeFlags[TypeFlags["Anonymous"] = 32768] = "Anonymous"; + TypeFlags[TypeFlags["Instantiated"] = 65536] = "Instantiated"; /* @internal */ - TypeFlags[TypeFlags["FromSignature"] = 65536] = "FromSignature"; - TypeFlags[TypeFlags["ObjectLiteral"] = 131072] = "ObjectLiteral"; + TypeFlags[TypeFlags["FromSignature"] = 131072] = "FromSignature"; + TypeFlags[TypeFlags["ObjectLiteral"] = 262144] = "ObjectLiteral"; /* @internal */ - TypeFlags[TypeFlags["ContainsUndefinedOrNull"] = 262144] = "ContainsUndefinedOrNull"; + TypeFlags[TypeFlags["ContainsUndefinedOrNull"] = 524288] = "ContainsUndefinedOrNull"; /* @internal */ - TypeFlags[TypeFlags["ContainsObjectLiteral"] = 524288] = "ContainsObjectLiteral"; - TypeFlags[TypeFlags["ESSymbol"] = 1048576] = "ESSymbol"; + TypeFlags[TypeFlags["ContainsObjectLiteral"] = 1048576] = "ContainsObjectLiteral"; + TypeFlags[TypeFlags["ESSymbol"] = 2097152] = "ESSymbol"; /* @internal */ - TypeFlags[TypeFlags["Intrinsic"] = 1048703] = "Intrinsic"; + TypeFlags[TypeFlags["Intrinsic"] = 2097279] = "Intrinsic"; /* @internal */ - TypeFlags[TypeFlags["Primitive"] = 1049086] = "Primitive"; + TypeFlags[TypeFlags["Primitive"] = 2097662] = "Primitive"; TypeFlags[TypeFlags["StringLike"] = 258] = "StringLike"; TypeFlags[TypeFlags["NumberLike"] = 132] = "NumberLike"; TypeFlags[TypeFlags["ObjectType"] = 48128] = "ObjectType"; /* @internal */ - TypeFlags[TypeFlags["RequiresWidening"] = 786432] = "RequiresWidening"; + TypeFlags[TypeFlags["RequiresWidening"] = 1572864] = "RequiresWidening"; })(ts.TypeFlags || (ts.TypeFlags = {})); var TypeFlags = ts.TypeFlags; (function (SignatureKind) { @@ -706,6 +739,36 @@ var ts; Ternary[Ternary["True"] = -1] = "True"; })(ts.Ternary || (ts.Ternary = {})); var Ternary = ts.Ternary; + function createFileMap(getCanonicalFileName) { + var files = {}; + return { + get: get, + set: set, + contains: contains, + remove: remove, + forEachValue: forEachValueInMap + }; + function set(fileName, value) { + files[normalizeKey(fileName)] = value; + } + function get(fileName) { + return files[normalizeKey(fileName)]; + } + function contains(fileName) { + return hasProperty(files, normalizeKey(fileName)); + } + function remove(fileName) { + var key = normalizeKey(fileName); + delete files[key]; + } + function forEachValueInMap(f) { + forEachValue(files, f); + } + function normalizeKey(key) { + return getCanonicalFileName(normalizeSlashes(key)); + } + } + ts.createFileMap = createFileMap; (function (Comparison) { Comparison[Comparison["LessThan"] = -1] = "LessThan"; Comparison[Comparison["EqualTo"] = 0] = "EqualTo"; @@ -826,6 +889,16 @@ var ts; } } ts.addRange = addRange; + function rangeEquals(array1, array2, pos, end) { + while (pos < end) { + if (array1[pos] !== array2[pos]) { + return false; + } + pos++; + } + return true; + } + ts.rangeEquals = rangeEquals; /** * Returns the last element of an array if non-empty, undefined otherwise. */ @@ -995,8 +1068,10 @@ var ts; var end = start + length; Debug.assert(start >= 0, "start must be non-negative, is " + start); Debug.assert(length >= 0, "length must be non-negative, is " + length); - Debug.assert(start <= file.text.length, "start must be within the bounds of the file. " + start + " > " + file.text.length); - Debug.assert(end <= file.text.length, "end must be the bounds of the file. " + end + " > " + file.text.length); + if (file) { + Debug.assert(start <= file.text.length, "start must be within the bounds of the file. " + start + " > " + file.text.length); + Debug.assert(end <= file.text.length, "end must be the bounds of the file. " + end + " > " + file.text.length); + } var text = getLocaleSpecificMessage(message.key); if (arguments.length > 4) { text = formatStringFromArgs(text, arguments, 4); @@ -1191,7 +1266,7 @@ var ts; function getNormalizedPathComponents(path, currentDirectory) { path = normalizeSlashes(path); var rootLength = getRootLength(path); - if (rootLength == 0) { + if (rootLength === 0) { // If the path is not rooted it is relative to current directory path = combinePaths(normalizeSlashes(currentDirectory), path); rootLength = getRootLength(path); @@ -1466,6 +1541,9 @@ var ts; fileStream.Close(); } } + function getCanonicalPath(path) { + return path.toLowerCase(); + } function getNames(collection) { var result = []; for (var e = new Enumerator(collection); !e.atEnd(); e.moveNext()) { @@ -1473,23 +1551,28 @@ var ts; } return result.sort(); } - function readDirectory(path, extension) { + function readDirectory(path, extension, exclude) { var result = []; + exclude = ts.map(exclude, function (s) { return getCanonicalPath(ts.combinePaths(path, s)); }); visitDirectory(path); return result; function visitDirectory(path) { var folder = fso.GetFolder(path || "."); var files = getNames(folder.files); for (var _i = 0; _i < files.length; _i++) { - var name_1 = files[_i]; - if (!extension || ts.fileExtensionIs(name_1, extension)) { - result.push(ts.combinePaths(path, name_1)); + var current = files[_i]; + var name_1 = ts.combinePaths(path, current); + if ((!extension || ts.fileExtensionIs(name_1, extension)) && !ts.contains(exclude, getCanonicalPath(name_1))) { + result.push(name_1); } } var subfolders = getNames(folder.subfolders); for (var _a = 0; _a < subfolders.length; _a++) { var current = subfolders[_a]; - visitDirectory(ts.combinePaths(path, current)); + var name_2 = ts.combinePaths(path, current); + if (!ts.contains(exclude, getCanonicalPath(name_2))) { + visitDirectory(name_2); + } } } } @@ -1574,8 +1657,12 @@ var ts; } _fs.writeFileSync(fileName, data, "utf8"); } - function readDirectory(path, extension) { + function getCanonicalPath(path) { + return useCaseSensitiveFileNames ? path.toLowerCase() : path; + } + function readDirectory(path, extension, exclude) { var result = []; + exclude = ts.map(exclude, function (s) { return getCanonicalPath(ts.combinePaths(path, s)); }); visitDirectory(path); return result; function visitDirectory(path) { @@ -1584,14 +1671,16 @@ var ts; for (var _i = 0; _i < files.length; _i++) { var current = files[_i]; var name = ts.combinePaths(path, current); - var stat = _fs.lstatSync(name); - if (stat.isFile()) { - if (!extension || ts.fileExtensionIs(name, extension)) { - result.push(name); + if (!ts.contains(exclude, getCanonicalPath(name))) { + var stat = _fs.statSync(name); + if (stat.isFile()) { + if (!extension || ts.fileExtensionIs(name, extension)) { + result.push(name); + } + } + else if (stat.isDirectory()) { + directories.push(name); } - } - else if (stat.isDirectory()) { - directories.push(name); } } for (var _a = 0; _a < directories.length; _a++) { @@ -1790,7 +1879,7 @@ var ts; Unterminated_template_literal: { code: 1160, category: ts.DiagnosticCategory.Error, key: "Unterminated template literal." }, Unterminated_regular_expression_literal: { code: 1161, category: ts.DiagnosticCategory.Error, key: "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." }, - yield_expression_must_be_contained_within_a_generator_declaration: { code: 1163, category: ts.DiagnosticCategory.Error, key: "'yield' expression must be contained_within a generator declaration." }, + 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." }, Computed_property_names_are_not_allowed_in_enums: { code: 1164, category: ts.DiagnosticCategory.Error, key: "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." }, 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." }, @@ -1835,15 +1924,32 @@ var ts; Decorators_are_only_available_when_targeting_ECMAScript_5_and_higher: { code: 1205, category: ts.DiagnosticCategory.Error, key: "Decorators are only available when targeting ECMAScript 5 and higher." }, Decorators_are_not_valid_here: { code: 1206, category: ts.DiagnosticCategory.Error, key: "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/set accessors of the same name." }, - Cannot_compile_namespaces_when_the_separateCompilation_flag_is_provided: { code: 1208, category: ts.DiagnosticCategory.Error, key: "Cannot compile namespaces when the '--separateCompilation' flag is provided." }, - Ambient_const_enums_are_not_allowed_when_the_separateCompilation_flag_is_provided: { code: 1209, category: ts.DiagnosticCategory.Error, key: "Ambient const enums are not allowed when the '--separateCompilation' flag is provided." }, + 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." }, + 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." }, 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." }, 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" }, 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" }, 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 strict mode." }, - Type_expected_0_is_a_reserved_word_in_strict_mode: { code: 1215, category: ts.DiagnosticCategory.Error, key: "Type expected. '{0}' is a reserved word in strict mode" }, - Type_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_strict_mode: { code: 1216, category: ts.DiagnosticCategory.Error, key: "Type 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." }, + 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." }, 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'." }, + Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Specify_experimentalDecorators_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. Specify '--experimentalDecorators' to remove this warning." }, + Generators_are_only_available_when_targeting_ECMAScript_6_or_higher: { code: 1220, category: ts.DiagnosticCategory.Error, key: "Generators are only available when targeting ECMAScript 6 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." }, + 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." }, + _0_tag_already_specified: { code: 1223, category: ts.DiagnosticCategory.Error, key: "'{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." }, + Cannot_find_parameter_0: { code: 1225, category: ts.DiagnosticCategory.Error, key: "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}'." }, + 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}'." }, + 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." }, + A_type_predicate_cannot_reference_a_rest_parameter: { code: 1229, category: ts.DiagnosticCategory.Error, key: "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." }, + 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." }, + 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." }, + 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." }, + 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." }, + 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." }, Duplicate_identifier_0: { code: 2300, category: ts.DiagnosticCategory.Error, key: "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." }, Static_members_cannot_reference_class_type_parameters: { code: 2302, category: ts.DiagnosticCategory.Error, key: "Static members cannot reference class type parameters." }, @@ -2004,7 +2110,7 @@ var ts; 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'." }, 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." }, 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'." }, - Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_6_and_higher: { code: 2472, category: ts.DiagnosticCategory.Error, key: "Spread operator in 'new' expressions is only available when targeting ECMAScript 6 and higher." }, + 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." }, 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." }, 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." }, 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 import declaration or export assignment." }, @@ -2035,6 +2141,13 @@ var ts; A_rest_element_cannot_contain_a_binding_pattern: { code: 2501, category: ts.DiagnosticCategory.Error, key: "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." }, Cannot_find_namespace_0: { code: 2503, category: ts.DiagnosticCategory.Error, key: "Cannot find namespace '{0}'." }, + No_best_common_type_exists_among_yield_expressions: { code: 2504, category: ts.DiagnosticCategory.Error, key: "No best common type exists among yield expressions." }, + A_generator_cannot_have_a_void_type_annotation: { code: 2505, category: ts.DiagnosticCategory.Error, key: "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." }, + Type_0_is_not_a_constructor_function_type: { code: 2507, category: ts.DiagnosticCategory.Error, key: "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." }, + 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." }, + 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." }, Import_declaration_0_is_using_private_name_1: { code: 4000, category: ts.DiagnosticCategory.Error, key: "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}'." }, 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}'." }, @@ -2119,11 +2232,11 @@ var ts; Option_noEmit_cannot_be_specified_with_option_out_or_outDir: { code: 5040, category: ts.DiagnosticCategory.Error, key: "Option 'noEmit' cannot be specified with option 'out' or 'outDir'." }, Option_noEmit_cannot_be_specified_with_option_declaration: { code: 5041, category: ts.DiagnosticCategory.Error, key: "Option 'noEmit' cannot be specified with option 'declaration'." }, 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." }, - Option_sourceMap_cannot_be_specified_with_option_separateCompilation: { code: 5043, category: ts.DiagnosticCategory.Error, key: "Option 'sourceMap' cannot be specified with option 'separateCompilation'." }, - Option_declaration_cannot_be_specified_with_option_separateCompilation: { code: 5044, category: ts.DiagnosticCategory.Error, key: "Option 'declaration' cannot be specified with option 'separateCompilation'." }, - Option_noEmitOnError_cannot_be_specified_with_option_separateCompilation: { code: 5045, category: ts.DiagnosticCategory.Error, key: "Option 'noEmitOnError' cannot be specified with option 'separateCompilation'." }, - Option_out_cannot_be_specified_with_option_separateCompilation: { code: 5046, category: ts.DiagnosticCategory.Error, key: "Option 'out' cannot be specified with option 'separateCompilation'." }, - Option_separateCompilation_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES6_or_higher: { code: 5047, category: ts.DiagnosticCategory.Error, key: "Option 'separateCompilation' can only be used when either option'--module' is provided or option 'target' is 'ES6' or higher." }, + Option_sourceMap_cannot_be_specified_with_option_isolatedModules: { code: 5043, category: ts.DiagnosticCategory.Error, key: "Option 'sourceMap' cannot be specified with option 'isolatedModules'." }, + Option_declaration_cannot_be_specified_with_option_isolatedModules: { code: 5044, category: ts.DiagnosticCategory.Error, key: "Option 'declaration' cannot be specified with option 'isolatedModules'." }, + Option_noEmitOnError_cannot_be_specified_with_option_isolatedModules: { code: 5045, category: ts.DiagnosticCategory.Error, key: "Option 'noEmitOnError' cannot be specified with option 'isolatedModules'." }, + Option_out_cannot_be_specified_with_option_isolatedModules: { code: 5046, category: ts.DiagnosticCategory.Error, key: "Option 'out' cannot be specified with option 'isolatedModules'." }, + Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES6_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 'ES6' or higher." }, Option_sourceMap_cannot_be_specified_with_option_inlineSourceMap: { code: 5048, category: ts.DiagnosticCategory.Error, key: "Option 'sourceMap' cannot be specified with option 'inlineSourceMap'." }, Option_sourceRoot_cannot_be_specified_with_option_inlineSourceMap: { code: 5049, category: ts.DiagnosticCategory.Error, key: "Option 'sourceRoot' cannot be specified with option 'inlineSourceMap'." }, Option_mapRoot_cannot_be_specified_with_option_inlineSourceMap: { code: 5050, category: ts.DiagnosticCategory.Error, key: "Option 'mapRoot' cannot be specified with option 'inlineSourceMap'." }, @@ -2177,6 +2290,9 @@ var ts; Specifies_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix: { code: 6060, category: ts.DiagnosticCategory.Message, key: "Specifies 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" }, Argument_for_newLine_option_must_be_CRLF_or_LF: { code: 6062, category: ts.DiagnosticCategory.Error, key: "Argument for '--newLine' option must be 'CRLF' or 'LF'." }, + Option_experimentalDecorators_must_also_be_specified_when_option_emitDecoratorMetadata_is_specified: { code: 6064, category: ts.DiagnosticCategory.Error, key: "Option 'experimentalDecorators' must also be specified when option 'emitDecoratorMetadata' is specified." }, + Enables_experimental_support_for_ES7_decorators: { code: 6065, category: ts.DiagnosticCategory.Message, key: "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." }, Variable_0_implicitly_has_an_1_type: { code: 7005, category: ts.DiagnosticCategory.Error, key: "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." }, Member_0_implicitly_has_an_1_type: { code: 7008, category: ts.DiagnosticCategory.Error, key: "Member '{0}' implicitly has an '{1}' type." }, @@ -2189,9 +2305,10 @@ var ts; 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." }, Rest_parameter_0_implicitly_has_an_any_type: { code: 7019, category: ts.DiagnosticCategory.Error, key: "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." }, - _0_implicitly_has_type_any_because_it_is_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 is does not have a type annotation and is referenced directly or indirectly in its own initializer." }, + _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 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 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 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 type." }, You_cannot_rename_this_element: { code: 8000, category: ts.DiagnosticCategory.Error, key: "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." }, 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." }, @@ -2205,16 +2322,12 @@ var ts; 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." }, 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." }, 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." }, - can_only_be_used_in_a_ts_file: { code: 8013, category: ts.DiagnosticCategory.Error, key: "'?' can only be used in a .ts file." }, property_declarations_can_only_be_used_in_a_ts_file: { code: 8014, category: ts.DiagnosticCategory.Error, key: "'property declarations' 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." }, 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." }, decorators_can_only_be_used_in_a_ts_file: { code: 8017, category: ts.DiagnosticCategory.Error, key: "'decorators' can only be used in a .ts file." }, - yield_expressions_are_not_currently_supported: { code: 9000, category: ts.DiagnosticCategory.Error, key: "'yield' expressions are not currently supported." }, - Generators_are_not_currently_supported: { code: 9001, category: ts.DiagnosticCategory.Error, key: "Generators are not currently supported." }, Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_class_extends_clauses: { code: 9002, category: ts.DiagnosticCategory.Error, key: "Only identifiers/qualified-names with optional type arguments are currently supported in a class 'extends' clauses." }, - class_expressions_are_not_currently_supported: { code: 9003, category: ts.DiagnosticCategory.Error, key: "'class' expressions are not currently supported." }, - class_declarations_are_only_supported_directly_inside_a_module_or_as_a_top_level_declaration: { code: 9004, category: ts.DiagnosticCategory.Error, key: "'class' declarations are only supported directly inside a module or as a top level declaration." } + class_expressions_are_not_currently_supported: { code: 9003, category: ts.DiagnosticCategory.Error, key: "'class' expressions are not currently supported." } }; })(ts || (ts = {})); /// @@ -2244,7 +2357,7 @@ var ts; "false": 80 /* FalseKeyword */, "finally": 81 /* FinallyKeyword */, "for": 82 /* ForKeyword */, - "from": 125 /* FromKeyword */, + "from": 126 /* FromKeyword */, "function": 83 /* FunctionKeyword */, "get": 116 /* GetKeyword */, "if": 84 /* IfKeyword */, @@ -2253,36 +2366,37 @@ var ts; "in": 86 /* InKeyword */, "instanceof": 87 /* InstanceOfKeyword */, "interface": 103 /* InterfaceKeyword */, + "is": 117 /* IsKeyword */, "let": 104 /* LetKeyword */, - "module": 117 /* ModuleKeyword */, - "namespace": 118 /* NamespaceKeyword */, + "module": 118 /* ModuleKeyword */, + "namespace": 119 /* NamespaceKeyword */, "new": 88 /* NewKeyword */, "null": 89 /* NullKeyword */, - "number": 120 /* NumberKeyword */, + "number": 121 /* NumberKeyword */, "package": 105 /* PackageKeyword */, "private": 106 /* PrivateKeyword */, "protected": 107 /* ProtectedKeyword */, "public": 108 /* PublicKeyword */, - "require": 119 /* RequireKeyword */, + "require": 120 /* RequireKeyword */, "return": 90 /* ReturnKeyword */, - "set": 121 /* SetKeyword */, + "set": 122 /* SetKeyword */, "static": 109 /* StaticKeyword */, - "string": 122 /* StringKeyword */, + "string": 123 /* StringKeyword */, "super": 91 /* SuperKeyword */, "switch": 92 /* SwitchKeyword */, - "symbol": 123 /* SymbolKeyword */, + "symbol": 124 /* SymbolKeyword */, "this": 93 /* ThisKeyword */, "throw": 94 /* ThrowKeyword */, "true": 95 /* TrueKeyword */, "try": 96 /* TryKeyword */, - "type": 124 /* TypeKeyword */, + "type": 125 /* TypeKeyword */, "typeof": 97 /* TypeOfKeyword */, "var": 98 /* VarKeyword */, "void": 99 /* VoidKeyword */, "while": 100 /* WhileKeyword */, "with": 101 /* WithKeyword */, "yield": 110 /* YieldKeyword */, - "of": 126 /* OfKeyword */, + "of": 127 /* OfKeyword */, "{": 14 /* OpenBraceToken */, "}": 15 /* CloseBraceToken */, "(": 16 /* OpenParenToken */, @@ -2419,9 +2533,9 @@ var ts; } function makeReverseMap(source) { var result = []; - for (var name_2 in source) { - if (source.hasOwnProperty(name_2)) { - result[source[name_2]] = name_2; + for (var name_3 in source) { + if (source.hasOwnProperty(name_3)) { + result[source[name_3]] = name_3; } } return result; @@ -2542,8 +2656,31 @@ var ts; return ch >= 48 /* _0 */ && ch <= 55 /* _7 */; } ts.isOctalDigit = isOctalDigit; + function couldStartTrivia(text, pos) { + // Keep in sync with skipTrivia + var ch = text.charCodeAt(pos); + switch (ch) { + case 13 /* carriageReturn */: + case 10 /* lineFeed */: + case 9 /* tab */: + case 11 /* verticalTab */: + case 12 /* formFeed */: + case 32 /* space */: + case 47 /* slash */: + // starts of normal trivia + case 60 /* lessThan */: + case 61 /* equals */: + case 62 /* greaterThan */: + // Starts of conflict marker trivia + return true; + default: + return ch > 127 /* maxAsciiCharacter */; + } + } + ts.couldStartTrivia = couldStartTrivia; /* @internal */ function skipTrivia(text, pos, stopAfterLineBreak) { + // Keep in sync with couldStartTrivia while (true) { var ch = text.charCodeAt(pos); switch (ch) { @@ -2750,12 +2887,17 @@ var ts; ch > 127 /* maxAsciiCharacter */ && isUnicodeIdentifierPart(ch, languageVersion); } ts.isIdentifierPart = isIdentifierPart; - /** Creates a scanner over a (possibly unspecified) range of a piece of text. */ + /* @internal */ + // Creates a scanner over a (possibly unspecified) range of a piece of text. function createScanner(languageVersion, skipTrivia, text, onError, start, length) { - var pos; // Current position (end position of text of current token) - var end; // end of text - var startPos; // Start position of whitespace before current token - var tokenPos; // Start position of text of current token + // Current position (end position of text of current token) + var pos; + // end of text + var end; + // Start position of whitespace before current token + var startPos; + // Start position of text of current token + var tokenPos; var token; var tokenValue; var precedingLineBreak; @@ -3042,7 +3184,7 @@ var ts; error(ts.Diagnostics.Unexpected_end_of_text); isInvalidExtendedEscape = true; } - else if (text.charCodeAt(pos) == 125 /* closeBrace */) { + else if (text.charCodeAt(pos) === 125 /* closeBrace */) { // Only swallow the following character up if it's a '}'. pos++; } @@ -3599,16 +3741,16 @@ var ts; function getModuleInstanceState(node) { // A module is uninstantiated if it contains only // 1. interface declarations, type alias declarations - if (node.kind === 203 /* InterfaceDeclaration */ || node.kind === 204 /* TypeAliasDeclaration */) { + if (node.kind === 205 /* InterfaceDeclaration */ || node.kind === 206 /* TypeAliasDeclaration */) { return 0 /* NonInstantiated */; } else if (ts.isConstEnumDeclaration(node)) { return 2 /* ConstEnumOnly */; } - else if ((node.kind === 210 /* ImportDeclaration */ || node.kind === 209 /* ImportEqualsDeclaration */) && !(node.flags & 1 /* Export */)) { + else if ((node.kind === 212 /* ImportDeclaration */ || node.kind === 211 /* ImportEqualsDeclaration */) && !(node.flags & 1 /* Export */)) { return 0 /* NonInstantiated */; } - else if (node.kind === 207 /* ModuleBlock */) { + else if (node.kind === 209 /* ModuleBlock */) { var state = 0 /* NonInstantiated */; ts.forEachChild(node, function (n) { switch (getModuleInstanceState(n)) { @@ -3627,7 +3769,7 @@ var ts; }); return state; } - else if (node.kind === 206 /* ModuleDeclaration */) { + else if (node.kind === 208 /* ModuleDeclaration */) { return getModuleInstanceState(node.body); } else { @@ -3635,6 +3777,27 @@ var ts; } } 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"; + ContainerFlags[ContainerFlags["HasLocals"] = 4] = "HasLocals"; + // If the current node is a container that also container that also contains locals. Examples: + // + // Functions, Methods, Modules, Source-files. + ContainerFlags[ContainerFlags["IsContainerWithLocals"] = 5] = "IsContainerWithLocals"; + })(ContainerFlags || (ContainerFlags = {})); function bindSourceFile(file) { var start = new Date().getTime(); bindSourceFileWorker(file); @@ -3646,46 +3809,48 @@ var ts; var container; var blockScopeContainer; var lastContainer; + // 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). + var inStrictMode = !!file.externalModuleIndicator; var symbolCount = 0; var Symbol = ts.objectAllocator.getSymbolConstructor(); + var classifiableNames = {}; if (!file.locals) { - file.locals = {}; - container = file; - setBlockScopeContainer(file, false); bind(file); file.symbolCount = symbolCount; + file.classifiableNames = classifiableNames; } + return; function createSymbol(flags, name) { symbolCount++; return new Symbol(flags, name); } - function setBlockScopeContainer(node, cleanLocals) { - blockScopeContainer = node; - if (cleanLocals) { - blockScopeContainer.locals = undefined; - } - } - function addDeclarationToSymbol(symbol, node, symbolKind) { - symbol.flags |= symbolKind; - if (!symbol.declarations) - symbol.declarations = []; - symbol.declarations.push(node); - if (symbolKind & 1952 /* HasExports */ && !symbol.exports) - symbol.exports = {}; - if (symbolKind & 6240 /* HasMembers */ && !symbol.members) - symbol.members = {}; + function addDeclarationToSymbol(symbol, node, symbolFlags) { + symbol.flags |= symbolFlags; node.symbol = symbol; - if (symbolKind & 107455 /* Value */ && !symbol.valueDeclaration) + if (!symbol.declarations) { + symbol.declarations = []; + } + symbol.declarations.push(node); + if (symbolFlags & 1952 /* HasExports */ && !symbol.exports) { + symbol.exports = {}; + } + if (symbolFlags & 6240 /* HasMembers */ && !symbol.members) { + symbol.members = {}; + } + if (symbolFlags & 107455 /* Value */ && !symbol.valueDeclaration) { 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) { if (node.name) { - if (node.kind === 206 /* ModuleDeclaration */ && node.name.kind === 8 /* StringLiteral */) { + if (node.kind === 208 /* ModuleDeclaration */ && node.name.kind === 8 /* StringLiteral */) { return '"' + node.name.text + '"'; } - if (node.name.kind === 128 /* ComputedPropertyName */) { + if (node.name.kind === 129 /* ComputedPropertyName */) { var nameExpression = node.name.expression; ts.Debug.assert(ts.isWellKnownSymbolSyntactically(nameExpression)); return ts.getPropertyNameForKnownSymbolName(nameExpression.name.text); @@ -3693,35 +3858,58 @@ var ts; return node.name.text; } switch (node.kind) { - case 144 /* ConstructorType */: - case 136 /* Constructor */: + case 137 /* Constructor */: return "__constructor"; - case 143 /* FunctionType */: - case 139 /* CallSignature */: + case 145 /* FunctionType */: + case 140 /* CallSignature */: return "__call"; - case 140 /* ConstructSignature */: + case 146 /* ConstructorType */: + case 141 /* ConstructSignature */: return "__new"; - case 141 /* IndexSignature */: + case 142 /* IndexSignature */: return "__index"; - case 216 /* ExportDeclaration */: + case 218 /* ExportDeclaration */: return "__export"; - case 215 /* ExportAssignment */: + case 217 /* ExportAssignment */: return node.isExportEquals ? "export=" : "default"; - case 201 /* FunctionDeclaration */: - case 202 /* ClassDeclaration */: + case 203 /* FunctionDeclaration */: + case 204 /* ClassDeclaration */: return node.flags & 256 /* Default */ ? "default" : undefined; } } function getDisplayName(node) { return node.name ? ts.declarationNameToString(node.name) : getDeclarationName(node); } - function declareSymbol(symbols, parent, node, includes, excludes) { + function declareSymbol(symbolTable, parent, node, includes, excludes) { ts.Debug.assert(!ts.hasDynamicName(node)); // The exported symbol for an export default function/class node is always named "default" var name = node.flags & 256 /* Default */ && parent ? "default" : getDeclarationName(node); var symbol; if (name !== undefined) { - symbol = ts.hasProperty(symbols, name) ? symbols[name] : (symbols[name] = createSymbol(0, name)); + // 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 + // witht he '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. + // + // 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 = ts.hasProperty(symbolTable, name) + ? symbolTable[name] + : (symbolTable[name] = createSymbol(0 /* None */, name)); + if (name && (includes & 788448 /* Classifiable */)) { + classifiableNames[name] = name; + } if (symbol.flags & excludes) { if (node.name) { node.name.parent = node; @@ -3735,39 +3923,24 @@ var ts; file.bindDiagnostics.push(ts.createDiagnosticForNode(declaration.name || declaration, message, getDisplayName(declaration))); }); file.bindDiagnostics.push(ts.createDiagnosticForNode(node.name || node, message, getDisplayName(node))); - symbol = createSymbol(0, name); + symbol = createSymbol(0 /* None */, name); } } else { - symbol = createSymbol(0, "__missing"); + symbol = createSymbol(0 /* None */, "__missing"); } addDeclarationToSymbol(symbol, node, includes); symbol.parent = parent; - if ((node.kind === 202 /* ClassDeclaration */ || node.kind === 175 /* ClassExpression */) && symbol.exports) { - // 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 prototypeSymbol = createSymbol(4 /* Property */ | 134217728 /* Prototype */, "prototype"); - if (ts.hasProperty(symbol.exports, prototypeSymbol.name)) { - if (node.name) { - node.name.parent = node; - } - file.bindDiagnostics.push(ts.createDiagnosticForNode(symbol.exports[prototypeSymbol.name].declarations[0], ts.Diagnostics.Duplicate_identifier_0, prototypeSymbol.name)); - } - symbol.exports[prototypeSymbol.name] = prototypeSymbol; - prototypeSymbol.parent = symbol; - } return symbol; } - function declareModuleMember(node, symbolKind, symbolExcludes) { + function declareModuleMember(node, symbolFlags, symbolExcludes) { var hasExportModifier = ts.getCombinedNodeFlags(node) & 1 /* Export */; - if (symbolKind & 8388608 /* Alias */) { - if (node.kind === 218 /* ExportSpecifier */ || (node.kind === 209 /* ImportEqualsDeclaration */ && hasExportModifier)) { - declareSymbol(container.symbol.exports, container.symbol, node, symbolKind, symbolExcludes); + if (symbolFlags & 8388608 /* Alias */) { + if (node.kind === 220 /* ExportSpecifier */ || (node.kind === 211 /* ImportEqualsDeclaration */ && hasExportModifier)) { + return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); } else { - declareSymbol(container.locals, undefined, node, symbolKind, symbolExcludes); + return declareSymbol(container.locals, undefined, node, symbolFlags, symbolExcludes); } } else { @@ -3783,108 +3956,200 @@ var ts; // 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. if (hasExportModifier || container.flags & 65536 /* ExportContext */) { - var exportKind = (symbolKind & 107455 /* Value */ ? 1048576 /* ExportValue */ : 0) | - (symbolKind & 793056 /* Type */ ? 2097152 /* ExportType */ : 0) | - (symbolKind & 1536 /* Namespace */ ? 4194304 /* ExportNamespace */ : 0); + var exportKind = (symbolFlags & 107455 /* Value */ ? 1048576 /* ExportValue */ : 0) | + (symbolFlags & 793056 /* Type */ ? 2097152 /* ExportType */ : 0) | + (symbolFlags & 1536 /* Namespace */ ? 4194304 /* ExportNamespace */ : 0); var local = declareSymbol(container.locals, undefined, node, exportKind, symbolExcludes); - local.exportSymbol = declareSymbol(container.symbol.exports, container.symbol, node, symbolKind, symbolExcludes); + local.exportSymbol = declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); node.localSymbol = local; + return local; } else { - declareSymbol(container.locals, undefined, node, symbolKind, symbolExcludes); + return declareSymbol(container.locals, 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 bindChildren(node, symbolKind, isBlockScopeContainer) { - if (symbolKind & 255504 /* HasLocals */) { - node.locals = {}; - } + // 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 bindChildren(node) { + // Before we recurse into a node's chilren, 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 saveParent = parent; var saveContainer = container; var savedBlockScopeContainer = blockScopeContainer; + // This node will now be set as the parent of all of its children as we recurse into them. parent = node; - if (symbolKind & 262128 /* IsContainer */) { - container = node; + // 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 accidently move any stale data forward from + // a previous compilation. + var containerFlags = getContainerFlags(node); + if (containerFlags & 1 /* IsContainer */) { + container = blockScopeContainer = node; + if (containerFlags & 4 /* HasLocals */) { + container.locals = {}; + } addToContainerChain(container); } - if (isBlockScopeContainer) { - // in incremental scenarios we might reuse nodes that already have locals being allocated - // during the bind step these locals should be dropped to prevent using stale data. - // locals should always be dropped unless they were previously initialized by the binder - // these cases are: - // - node has locals (symbolKind & HasLocals) !== 0 - // - node is a source file - setBlockScopeContainer(node, (symbolKind & 255504 /* HasLocals */) === 0 && node.kind !== 228 /* SourceFile */); + else if (containerFlags & 2 /* IsBlockScopedContainer */) { + blockScopeContainer = node; + blockScopeContainer.locals = undefined; } ts.forEachChild(node, bind); container = saveContainer; parent = saveParent; blockScopeContainer = savedBlockScopeContainer; } - function addToContainerChain(node) { - if (lastContainer) { - lastContainer.nextContainer = node; + function getContainerFlags(node) { + switch (node.kind) { + case 177 /* ClassExpression */: + case 204 /* ClassDeclaration */: + case 205 /* InterfaceDeclaration */: + case 207 /* EnumDeclaration */: + case 148 /* TypeLiteral */: + case 157 /* ObjectLiteralExpression */: + return 1 /* IsContainer */; + case 140 /* CallSignature */: + case 141 /* ConstructSignature */: + case 142 /* IndexSignature */: + case 136 /* MethodDeclaration */: + case 135 /* MethodSignature */: + case 203 /* FunctionDeclaration */: + case 137 /* Constructor */: + case 138 /* GetAccessor */: + case 139 /* SetAccessor */: + case 145 /* FunctionType */: + case 146 /* ConstructorType */: + case 165 /* FunctionExpression */: + case 166 /* ArrowFunction */: + case 208 /* ModuleDeclaration */: + case 230 /* SourceFile */: + case 206 /* TypeAliasDeclaration */: + return 5 /* IsContainerWithLocals */; + case 226 /* CatchClause */: + case 189 /* ForStatement */: + case 190 /* ForInStatement */: + case 191 /* ForOfStatement */: + case 210 /* CaseBlock */: + return 2 /* IsBlockScopedContainer */; + case 182 /* 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. Othewise '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 */; } - lastContainer = node; + return 0 /* None */; } - function bindDeclaration(node, symbolKind, symbolExcludes, isBlockScopeContainer) { - switch (container.kind) { - case 206 /* ModuleDeclaration */: - declareModuleMember(node, symbolKind, symbolExcludes); - break; - case 228 /* SourceFile */: - if (ts.isExternalModule(container)) { - declareModuleMember(node, symbolKind, symbolExcludes); - break; - } - case 143 /* FunctionType */: - case 144 /* ConstructorType */: - case 139 /* CallSignature */: - case 140 /* ConstructSignature */: - case 141 /* IndexSignature */: - case 135 /* MethodDeclaration */: - case 134 /* MethodSignature */: - case 136 /* Constructor */: - case 137 /* GetAccessor */: - case 138 /* SetAccessor */: - case 201 /* FunctionDeclaration */: - case 163 /* FunctionExpression */: - case 164 /* ArrowFunction */: - declareSymbol(container.locals, undefined, node, symbolKind, symbolExcludes); - break; - case 175 /* ClassExpression */: - case 202 /* ClassDeclaration */: - if (node.flags & 128 /* Static */) { - declareSymbol(container.symbol.exports, container.symbol, node, symbolKind, symbolExcludes); - break; - } - case 146 /* TypeLiteral */: - case 155 /* ObjectLiteralExpression */: - case 203 /* InterfaceDeclaration */: - declareSymbol(container.symbol.members, container.symbol, node, symbolKind, symbolExcludes); - break; - case 205 /* EnumDeclaration */: - declareSymbol(container.symbol.exports, container.symbol, node, symbolKind, symbolExcludes); - break; + function addToContainerChain(next) { + if (lastContainer) { + lastContainer.nextContainer = next; } - bindChildren(node, symbolKind, isBlockScopeContainer); + lastContainer = next; + } + function declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes) { + // Just call this directly so that the return type of this function stays "void". + 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 208 /* ModuleDeclaration */: + return declareModuleMember(node, symbolFlags, symbolExcludes); + case 230 /* SourceFile */: + return declareSourceFileMember(node, symbolFlags, symbolExcludes); + case 177 /* ClassExpression */: + case 204 /* ClassDeclaration */: + return declareClassMember(node, symbolFlags, symbolExcludes); + case 207 /* EnumDeclaration */: + return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); + case 148 /* TypeLiteral */: + case 157 /* ObjectLiteralExpression */: + case 205 /* InterfaceDeclaration */: + // 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 145 /* FunctionType */: + case 146 /* ConstructorType */: + case 140 /* CallSignature */: + case 141 /* ConstructSignature */: + case 142 /* IndexSignature */: + case 136 /* MethodDeclaration */: + case 135 /* MethodSignature */: + case 137 /* Constructor */: + case 138 /* GetAccessor */: + case 139 /* SetAccessor */: + case 203 /* FunctionDeclaration */: + case 165 /* FunctionExpression */: + case 166 /* ArrowFunction */: + case 206 /* TypeAliasDeclaration */: + // 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, undefined, node, symbolFlags, symbolExcludes); + } + } + function declareClassMember(node, symbolFlags, symbolExcludes) { + return node.flags & 128 /* 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, undefined, node, symbolFlags, symbolExcludes); } function isAmbientContext(node) { while (node) { - if (node.flags & 2 /* Ambient */) + if (node.flags & 2 /* Ambient */) { return true; + } node = node.parent; } return false; } function hasExportDeclarations(node) { - var body = node.kind === 228 /* SourceFile */ ? node : node.body; - if (body.kind === 228 /* SourceFile */ || body.kind === 207 /* ModuleBlock */) { + var body = node.kind === 230 /* SourceFile */ ? node : node.body; + if (body.kind === 230 /* SourceFile */ || body.kind === 209 /* ModuleBlock */) { for (var _i = 0, _a = body.statements; _i < _a.length; _i++) { var stat = _a[_i]; - if (stat.kind === 216 /* ExportDeclaration */ || stat.kind === 215 /* ExportAssignment */) { + if (stat.kind === 218 /* ExportDeclaration */ || stat.kind === 217 /* ExportAssignment */) { return true; } } @@ -3904,15 +4169,15 @@ var ts; function bindModuleDeclaration(node) { setExportContextFlag(node); if (node.name.kind === 8 /* StringLiteral */) { - bindDeclaration(node, 512 /* ValueModule */, 106639 /* ValueModuleExcludes */, true); + declareSymbolAndAddToSymbolTable(node, 512 /* ValueModule */, 106639 /* ValueModuleExcludes */); } else { var state = getModuleInstanceState(node); if (state === 0 /* NonInstantiated */) { - bindDeclaration(node, 1024 /* NamespaceModule */, 0 /* NamespaceModuleExcludes */, true); + declareSymbolAndAddToSymbolTable(node, 1024 /* NamespaceModule */, 0 /* NamespaceModuleExcludes */); } else { - bindDeclaration(node, 512 /* ValueModule */, 106639 /* ValueModuleExcludes */, true); + declareSymbolAndAddToSymbolTable(node, 512 /* ValueModule */, 106639 /* ValueModuleExcludes */); var currentModuleIsConstEnumOnly = state === 2 /* ConstEnumOnly */; if (node.symbol.constEnumOnlyModule === undefined) { // non-merged case - use the current state @@ -3934,28 +4199,61 @@ var ts; // 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 */); - bindChildren(node, 131072 /* Signature */, false); var typeLiteralSymbol = createSymbol(2048 /* TypeLiteral */, "__type"); addDeclarationToSymbol(typeLiteralSymbol, node, 2048 /* TypeLiteral */); - typeLiteralSymbol.members = {}; - typeLiteralSymbol.members[node.kind === 143 /* FunctionType */ ? "__call" : "__new"] = symbol; + typeLiteralSymbol.members = (_a = {}, _a[symbol.name] = symbol, _a); + var _a; } - function bindAnonymousDeclaration(node, symbolKind, name, isBlockScopeContainer) { - var symbol = createSymbol(symbolKind, name); - addDeclarationToSymbol(symbol, node, symbolKind); - bindChildren(node, symbolKind, isBlockScopeContainer); + function bindObjectLiteralExpression(node) { + var ElementKind; + (function (ElementKind) { + ElementKind[ElementKind["Property"] = 1] = "Property"; + ElementKind[ElementKind["Accessor"] = 2] = "Accessor"; + })(ElementKind || (ElementKind = {})); + if (inStrictMode) { + var seen = {}; + for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { + var prop = _a[_i]; + if (prop.name.kind !== 65 /* Identifier */) { + continue; + } + var identifier = prop.name; + // ECMA-262 11.1.5 Object Initialiser + // 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 === 227 /* PropertyAssignment */ || prop.kind === 228 /* ShorthandPropertyAssignment */ || prop.kind === 136 /* MethodDeclaration */ + ? 1 /* Property */ + : 2 /* Accessor */; + var existingKind = seen[identifier.text]; + if (!existingKind) { + seen[identifier.text] = currentKind; + continue; + } + if (currentKind === 1 /* Property */ && existingKind === 1 /* Property */) { + var span = ts.getErrorSpanForNode(file, identifier); + file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, ts.Diagnostics.An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode)); + } + } + } + return bindAnonymousDeclaration(node, 4096 /* ObjectLiteral */, "__object"); } - function bindCatchVariableDeclaration(node) { - bindChildren(node, 0, true); + function bindAnonymousDeclaration(node, symbolFlags, name) { + var symbol = createSymbol(symbolFlags, name); + addDeclarationToSymbol(symbol, node, symbolFlags); } - function bindBlockScopedDeclaration(node, symbolKind, symbolExcludes) { + function bindBlockScopedDeclaration(node, symbolFlags, symbolExcludes) { switch (blockScopeContainer.kind) { - case 206 /* ModuleDeclaration */: - declareModuleMember(node, symbolKind, symbolExcludes); + case 208 /* ModuleDeclaration */: + declareModuleMember(node, symbolFlags, symbolExcludes); break; - case 228 /* SourceFile */: + case 230 /* SourceFile */: if (ts.isExternalModule(container)) { - declareModuleMember(node, symbolKind, symbolExcludes); + declareModuleMember(node, symbolFlags, symbolExcludes); break; } // fall through. @@ -3964,211 +4262,394 @@ var ts; blockScopeContainer.locals = {}; addToContainerChain(blockScopeContainer); } - declareSymbol(blockScopeContainer.locals, undefined, node, symbolKind, symbolExcludes); + declareSymbol(blockScopeContainer.locals, undefined, node, symbolFlags, symbolExcludes); } - bindChildren(node, symbolKind, false); } 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 >= 102 /* FirstFutureReservedWord */ && + node.originalKeywordKind <= 110 /* LastFutureReservedWord */ && + !ts.isIdentifierName(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.getAncestor(node, 204 /* ClassDeclaration */) || ts.getAncestor(node, 177 /* ClassExpression */)) { + 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 === 65 /* 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 = ts.getErrorSpanForNode(file, node.expression); + file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, ts.Diagnostics.delete_cannot_be_called_on_an_identifier_in_strict_mode)); + } + } + function isEvalOrArgumentsIdentifier(node) { + return node.kind === 65 /* Identifier */ && + (node.text === "eval" || node.text === "arguments"); + } + function checkStrictModeEvalOrArguments(contextNode, name) { + if (name && name.kind === 65 /* 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 = ts.getErrorSpanForNode(file, name); + file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.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.getAncestor(node, 204 /* ClassDeclaration */) || ts.getAncestor(node, 177 /* ClassExpression */)) { + 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 checkStrictModeNumericLiteral(node) { + if (inStrictMode && node.flags & 16384 /* OctalLiteral */) { + 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 === 38 /* PlusPlusToken */ || node.operator === 39 /* MinusMinusToken */) { + checkStrictModeEvalOrArguments(node, node.operand); + } + } + } + function checkStrictModeWithStatement(node) { + // Grammar checking for withStatement + if (inStrictMode) { + grammarErrorOnFirstToken(node, ts.Diagnostics.with_statements_are_not_allowed_in_strict_mode); + } + } + function grammarErrorOnFirstToken(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) { node.parent = parent; + var savedInStrictMode = inStrictMode; + if (!savedInStrictMode) { + updateStrictMode(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. + bindChildren(node); + inStrictMode = savedInStrictMode; + } + function updateStrictMode(node) { switch (node.kind) { - case 129 /* TypeParameter */: - bindDeclaration(node, 262144 /* TypeParameter */, 530912 /* TypeParameterExcludes */, false); - break; - case 130 /* Parameter */: - bindParameter(node); - break; - case 199 /* VariableDeclaration */: - case 153 /* BindingElement */: - if (ts.isBindingPattern(node.name)) { - bindChildren(node, 0, false); + case 230 /* SourceFile */: + case 209 /* ModuleBlock */: + updateStrictModeStatementList(node.statements); + return; + case 182 /* Block */: + if (ts.isFunctionLike(node.parent)) { + updateStrictModeStatementList(node.statements); } - else 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 - bindDeclaration(node, 1 /* FunctionScopedVariable */, 107455 /* ParameterExcludes */, false); - } - else { - bindDeclaration(node, 1 /* FunctionScopedVariable */, 107454 /* FunctionScopedVariableExcludes */, false); - } - break; - case 133 /* PropertyDeclaration */: - case 132 /* PropertySignature */: - bindPropertyOrMethodOrAccessor(node, 4 /* Property */ | (node.questionToken ? 536870912 /* Optional */ : 0), 107455 /* PropertyExcludes */, false); - break; - case 225 /* PropertyAssignment */: - case 226 /* ShorthandPropertyAssignment */: - bindPropertyOrMethodOrAccessor(node, 4 /* Property */, 107455 /* PropertyExcludes */, false); - break; - case 227 /* EnumMember */: - bindPropertyOrMethodOrAccessor(node, 8 /* EnumMember */, 107455 /* EnumMemberExcludes */, false); - break; - case 139 /* CallSignature */: - case 140 /* ConstructSignature */: - case 141 /* IndexSignature */: - bindDeclaration(node, 131072 /* Signature */, 0, false); - break; - case 135 /* MethodDeclaration */: - case 134 /* MethodSignature */: + return; + case 204 /* ClassDeclaration */: + case 177 /* ClassExpression */: + // All classes are automatically in strict mode in ES6. + inStrictMode = true; + return; + } + } + function updateStrictModeStatementList(statements) { + for (var _i = 0; _i < statements.length; _i++) { + var statement = statements[_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) { + case 65 /* Identifier */: + return checkStrictModeIdentifier(node); + case 172 /* BinaryExpression */: + return checkStrictModeBinaryExpression(node); + case 226 /* CatchClause */: + return checkStrictModeCatchClause(node); + case 167 /* DeleteExpression */: + return checkStrictModeDeleteExpression(node); + case 7 /* NumericLiteral */: + return checkStrictModeNumericLiteral(node); + case 171 /* PostfixUnaryExpression */: + return checkStrictModePostfixUnaryExpression(node); + case 170 /* PrefixUnaryExpression */: + return checkStrictModePrefixUnaryExpression(node); + case 195 /* WithStatement */: + return checkStrictModeWithStatement(node); + case 130 /* TypeParameter */: + return declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 530912 /* TypeParameterExcludes */); + case 131 /* Parameter */: + return bindParameter(node); + case 201 /* VariableDeclaration */: + case 155 /* BindingElement */: + return bindVariableDeclarationOrBindingElement(node); + case 134 /* PropertyDeclaration */: + case 133 /* PropertySignature */: + return bindPropertyOrMethodOrAccessor(node, 4 /* Property */ | (node.questionToken ? 536870912 /* Optional */ : 0 /* None */), 107455 /* PropertyExcludes */); + case 227 /* PropertyAssignment */: + case 228 /* ShorthandPropertyAssignment */: + return bindPropertyOrMethodOrAccessor(node, 4 /* Property */, 107455 /* PropertyExcludes */); + case 229 /* EnumMember */: + return bindPropertyOrMethodOrAccessor(node, 8 /* EnumMember */, 107455 /* EnumMemberExcludes */); + case 140 /* CallSignature */: + case 141 /* ConstructSignature */: + case 142 /* IndexSignature */: + return declareSymbolAndAddToSymbolTable(node, 131072 /* Signature */, 0 /* None */); + case 136 /* MethodDeclaration */: + case 135 /* 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. - bindPropertyOrMethodOrAccessor(node, 8192 /* Method */ | (node.questionToken ? 536870912 /* Optional */ : 0), ts.isObjectLiteralMethod(node) ? 107455 /* PropertyExcludes */ : 99263 /* MethodExcludes */, true); - break; - case 201 /* FunctionDeclaration */: - bindDeclaration(node, 16 /* Function */, 106927 /* FunctionExcludes */, true); - break; - case 136 /* Constructor */: - bindDeclaration(node, 16384 /* Constructor */, 0, true); - break; - case 137 /* GetAccessor */: - bindPropertyOrMethodOrAccessor(node, 32768 /* GetAccessor */, 41919 /* GetAccessorExcludes */, true); - break; - case 138 /* SetAccessor */: - bindPropertyOrMethodOrAccessor(node, 65536 /* SetAccessor */, 74687 /* SetAccessorExcludes */, true); - break; - case 143 /* FunctionType */: - case 144 /* ConstructorType */: - bindFunctionOrConstructorType(node); - break; - case 146 /* TypeLiteral */: - bindAnonymousDeclaration(node, 2048 /* TypeLiteral */, "__type", false); - break; - case 155 /* ObjectLiteralExpression */: - bindAnonymousDeclaration(node, 4096 /* ObjectLiteral */, "__object", false); - break; - case 163 /* FunctionExpression */: - case 164 /* ArrowFunction */: - bindAnonymousDeclaration(node, 16 /* Function */, "__function", true); - break; - case 175 /* ClassExpression */: - bindAnonymousDeclaration(node, 32 /* Class */, "__class", false); - break; - case 224 /* CatchClause */: - bindCatchVariableDeclaration(node); - break; - case 202 /* ClassDeclaration */: - bindBlockScopedDeclaration(node, 32 /* Class */, 899583 /* ClassExcludes */); - break; - case 203 /* InterfaceDeclaration */: - bindDeclaration(node, 64 /* Interface */, 792992 /* InterfaceExcludes */, false); - break; - case 204 /* TypeAliasDeclaration */: - bindDeclaration(node, 524288 /* TypeAlias */, 793056 /* TypeAliasExcludes */, false); - break; - case 205 /* EnumDeclaration */: - if (ts.isConst(node)) { - bindDeclaration(node, 128 /* ConstEnum */, 899967 /* ConstEnumExcludes */, false); - } - else { - bindDeclaration(node, 256 /* RegularEnum */, 899327 /* RegularEnumExcludes */, false); - } - break; - case 206 /* ModuleDeclaration */: - bindModuleDeclaration(node); - break; - case 209 /* ImportEqualsDeclaration */: - case 212 /* NamespaceImport */: - case 214 /* ImportSpecifier */: - case 218 /* ExportSpecifier */: - bindDeclaration(node, 8388608 /* Alias */, 8388608 /* AliasExcludes */, false); - break; - case 211 /* ImportClause */: - if (node.name) { - bindDeclaration(node, 8388608 /* Alias */, 8388608 /* AliasExcludes */, false); - } - else { - bindChildren(node, 0, false); - } - break; - case 216 /* ExportDeclaration */: - if (!node.exportClause) { - // All export * declarations are collected in an __export symbol - declareSymbol(container.symbol.exports, container.symbol, node, 1073741824 /* ExportStar */, 0); - } - bindChildren(node, 0, false); - break; - case 215 /* ExportAssignment */: - if (node.expression.kind === 65 /* Identifier */) { - // An export default clause with an identifier exports all meanings of that identifier - declareSymbol(container.symbol.exports, container.symbol, node, 8388608 /* Alias */, 107455 /* PropertyExcludes */ | 8388608 /* AliasExcludes */); - } - else { - // An export default clause with an expression exports a value - declareSymbol(container.symbol.exports, container.symbol, node, 4 /* Property */, 107455 /* PropertyExcludes */ | 8388608 /* AliasExcludes */); - } - bindChildren(node, 0, false); - break; - case 228 /* SourceFile */: - setExportContextFlag(node); - if (ts.isExternalModule(node)) { - bindAnonymousDeclaration(node, 512 /* ValueModule */, '"' + ts.removeFileExtension(node.fileName) + '"', true); - break; - } - case 180 /* Block */: - // do not treat function block a block-scope container - // all block-scope locals that reside in this block should go to the function locals. - // Otherwise this won't be considered as redeclaration of a block scoped local: - // function foo() { - // let x; - // let x; - // } - // 'let x' will be placed into the function locals and 'let x' - into the locals of the block - bindChildren(node, 0, !ts.isFunctionLike(node.parent)); - break; - case 224 /* CatchClause */: - case 187 /* ForStatement */: - case 188 /* ForInStatement */: - case 189 /* ForOfStatement */: - case 208 /* CaseBlock */: - bindChildren(node, 0, true); - break; - default: - var saveParent = parent; - parent = node; - ts.forEachChild(node, bind); - parent = saveParent; + return bindPropertyOrMethodOrAccessor(node, 8192 /* Method */ | (node.questionToken ? 536870912 /* Optional */ : 0 /* None */), ts.isObjectLiteralMethod(node) ? 107455 /* PropertyExcludes */ : 99263 /* MethodExcludes */); + case 203 /* FunctionDeclaration */: + checkStrictModeFunctionName(node); + return declareSymbolAndAddToSymbolTable(node, 16 /* Function */, 106927 /* FunctionExcludes */); + case 137 /* Constructor */: + return declareSymbolAndAddToSymbolTable(node, 16384 /* Constructor */, 0 /* None */); + case 138 /* GetAccessor */: + return bindPropertyOrMethodOrAccessor(node, 32768 /* GetAccessor */, 41919 /* GetAccessorExcludes */); + case 139 /* SetAccessor */: + return bindPropertyOrMethodOrAccessor(node, 65536 /* SetAccessor */, 74687 /* SetAccessorExcludes */); + case 145 /* FunctionType */: + case 146 /* ConstructorType */: + return bindFunctionOrConstructorType(node); + case 148 /* TypeLiteral */: + return bindAnonymousDeclaration(node, 2048 /* TypeLiteral */, "__type"); + case 157 /* ObjectLiteralExpression */: + return bindObjectLiteralExpression(node); + case 165 /* FunctionExpression */: + case 166 /* ArrowFunction */: + checkStrictModeFunctionName(node); + return bindAnonymousDeclaration(node, 16 /* Function */, "__function"); + case 177 /* ClassExpression */: + case 204 /* ClassDeclaration */: + return bindClassLikeDeclaration(node); + case 205 /* InterfaceDeclaration */: + return bindBlockScopedDeclaration(node, 64 /* Interface */, 792992 /* InterfaceExcludes */); + case 206 /* TypeAliasDeclaration */: + return bindBlockScopedDeclaration(node, 524288 /* TypeAlias */, 793056 /* TypeAliasExcludes */); + case 207 /* EnumDeclaration */: + return bindEnumDeclaration(node); + case 208 /* ModuleDeclaration */: + return bindModuleDeclaration(node); + case 211 /* ImportEqualsDeclaration */: + case 214 /* NamespaceImport */: + case 216 /* ImportSpecifier */: + case 220 /* ExportSpecifier */: + return declareSymbolAndAddToSymbolTable(node, 8388608 /* Alias */, 8388608 /* AliasExcludes */); + case 213 /* ImportClause */: + return bindImportClause(node); + case 218 /* ExportDeclaration */: + return bindExportDeclaration(node); + case 217 /* ExportAssignment */: + return bindExportAssignment(node); + case 230 /* SourceFile */: + return bindSourceFileIfExternalModule(); + } + } + function bindSourceFileIfExternalModule() { + setExportContextFlag(file); + if (ts.isExternalModule(file)) { + 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 if (node.expression.kind === 65 /* Identifier */) { + // An export default clause with an identifier exports all meanings of that identifier + declareSymbol(container.symbol.exports, container.symbol, node, 8388608 /* Alias */, 107455 /* PropertyExcludes */ | 8388608 /* AliasExcludes */); + } + else { + // An export default clause with an expression exports a value + declareSymbol(container.symbol.exports, container.symbol, node, 4 /* Property */, 107455 /* PropertyExcludes */ | 8388608 /* AliasExcludes */); + } + } + function bindExportDeclaration(node) { + if (!container.symbol || !container.symbol.exports) { + // Export * in some sort of block construct + bindAnonymousDeclaration(node, 1073741824 /* ExportStar */, getDeclarationName(node)); + } + else if (!node.exportClause) { + // All export * declarations are collected in an __export symbol + declareSymbol(container.symbol.exports, container.symbol, node, 1073741824 /* ExportStar */, 0 /* None */); + } + } + function bindImportClause(node) { + if (node.name) { + declareSymbolAndAddToSymbolTable(node, 8388608 /* Alias */, 8388608 /* AliasExcludes */); + } + } + function bindClassLikeDeclaration(node) { + if (node.kind === 204 /* ClassDeclaration */) { + bindBlockScopedDeclaration(node, 32 /* Class */, 899583 /* ClassExcludes */); + } + else { + bindAnonymousDeclaration(node, 32 /* Class */, "__class"); + } + 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 */ | 134217728 /* Prototype */, "prototype"); + if (ts.hasProperty(symbol.exports, prototypeSymbol.name)) { + if (node.name) { + node.name.parent = node; + } + file.bindDiagnostics.push(ts.createDiagnosticForNode(symbol.exports[prototypeSymbol.name].declarations[0], ts.Diagnostics.Duplicate_identifier_0, prototypeSymbol.name)); + } + symbol.exports[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) { + // 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), false); + bindAnonymousDeclaration(node, 1 /* FunctionScopedVariable */, getDestructuringParameterName(node)); } else { - bindDeclaration(node, 1 /* FunctionScopedVariable */, 107455 /* ParameterExcludes */, false); + declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 107455 /* ParameterExcludes */); } // If this is a property-parameter, then also declare the property symbol into the // containing class. if (node.flags & 112 /* AccessibilityModifier */ && - node.parent.kind === 136 /* Constructor */ && - (node.parent.parent.kind === 202 /* ClassDeclaration */ || node.parent.parent.kind === 175 /* ClassExpression */)) { + node.parent.kind === 137 /* Constructor */ && + (node.parent.parent.kind === 204 /* ClassDeclaration */ || node.parent.parent.kind === 177 /* ClassExpression */)) { var classDeclaration = node.parent.parent; declareSymbol(classDeclaration.symbol.members, classDeclaration.symbol, node, 4 /* Property */, 107455 /* PropertyExcludes */); } } - function bindPropertyOrMethodOrAccessor(node, symbolKind, symbolExcludes, isBlockScopeContainer) { - if (ts.hasDynamicName(node)) { - bindAnonymousDeclaration(node, symbolKind, "__computed", isBlockScopeContainer); - } - else { - bindDeclaration(node, symbolKind, symbolExcludes, isBlockScopeContainer); - } + function bindPropertyOrMethodOrAccessor(node, symbolFlags, symbolExcludes) { + return ts.hasDynamicName(node) + ? bindAnonymousDeclaration(node, symbolFlags, "__computed") + : declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes); } } })(ts || (ts = {})); @@ -4190,7 +4671,7 @@ var ts; // Pool writers to avoid needing to allocate them for every symbol we write. var stringWriters = []; function getSingleLineStringWriter() { - if (stringWriters.length == 0) { + if (stringWriters.length === 0) { var str = ""; var writeText = function (text) { return str += text; }; return { @@ -4226,11 +4707,11 @@ var ts; // Returns true if this node contains a parse error anywhere underneath it. function containsParseError(node) { aggregateChildData(node); - return (node.parserContextFlags & 64 /* ThisNodeOrAnySubNodesHasError */) !== 0; + return (node.parserContextFlags & 128 /* ThisNodeOrAnySubNodesHasError */) !== 0; } ts.containsParseError = containsParseError; function aggregateChildData(node) { - if (!(node.parserContextFlags & 128 /* HasAggregatedChildData */)) { + if (!(node.parserContextFlags & 256 /* HasAggregatedChildData */)) { // A node is considered to contain a parse error if: // a) the parser explicitly marked that it had an error // b) any of it's children reported that it had an error. @@ -4238,16 +4719,16 @@ var ts; ts.forEachChild(node, containsParseError); // If so, mark ourselves accordingly. if (thisNodeOrAnySubNodesHasError) { - node.parserContextFlags |= 64 /* ThisNodeOrAnySubNodesHasError */; + node.parserContextFlags |= 128 /* ThisNodeOrAnySubNodesHasError */; } // Also mark that we've propogated the child information to this node. This way we can // always consult the bit directly on this node without needing to check its children // again. - node.parserContextFlags |= 128 /* HasAggregatedChildData */; + node.parserContextFlags |= 256 /* HasAggregatedChildData */; } } function getSourceFileOfNode(node) { - while (node && node.kind !== 228 /* SourceFile */) { + while (node && node.kind !== 230 /* SourceFile */) { node = node.parent; } return node; @@ -4357,15 +4838,15 @@ var ts; return current; } switch (current.kind) { - case 228 /* SourceFile */: - case 208 /* CaseBlock */: - case 224 /* CatchClause */: - case 206 /* ModuleDeclaration */: - case 187 /* ForStatement */: - case 188 /* ForInStatement */: - case 189 /* ForOfStatement */: + case 230 /* SourceFile */: + case 210 /* CaseBlock */: + case 226 /* CatchClause */: + case 208 /* ModuleDeclaration */: + case 189 /* ForStatement */: + case 190 /* ForInStatement */: + case 191 /* ForOfStatement */: return current; - case 180 /* Block */: + case 182 /* Block */: // function block is not considered block-scope container // see comment in binder.ts: bind(...), case for SyntaxKind.Block if (!isFunctionLike(current.parent)) { @@ -4378,9 +4859,9 @@ var ts; ts.getEnclosingBlockScopeContainer = getEnclosingBlockScopeContainer; function isCatchClauseVariableDeclaration(declaration) { return declaration && - declaration.kind === 199 /* VariableDeclaration */ && + declaration.kind === 201 /* VariableDeclaration */ && declaration.parent && - declaration.parent.kind === 224 /* CatchClause */; + declaration.parent.kind === 226 /* CatchClause */; } ts.isCatchClauseVariableDeclaration = isCatchClauseVariableDeclaration; // Return display name of an identifier @@ -4419,7 +4900,7 @@ var ts; function getErrorSpanForNode(sourceFile, node) { var errorNode = node; switch (node.kind) { - case 228 /* SourceFile */: + case 230 /* SourceFile */: var pos_1 = ts.skipTrivia(sourceFile.text, 0, false); if (pos_1 === sourceFile.text.length) { // file is empty - return span for the beginning of the file @@ -4428,16 +4909,16 @@ var ts; return getSpanOfTokenAtPosition(sourceFile, pos_1); // This list is a work in progress. Add missing node kinds to improve their error // spans. - case 199 /* VariableDeclaration */: - case 153 /* BindingElement */: - case 202 /* ClassDeclaration */: - case 175 /* ClassExpression */: - case 203 /* InterfaceDeclaration */: - case 206 /* ModuleDeclaration */: - case 205 /* EnumDeclaration */: - case 227 /* EnumMember */: - case 201 /* FunctionDeclaration */: - case 163 /* FunctionExpression */: + case 201 /* VariableDeclaration */: + case 155 /* BindingElement */: + case 204 /* ClassDeclaration */: + case 177 /* ClassExpression */: + case 205 /* InterfaceDeclaration */: + case 208 /* ModuleDeclaration */: + case 207 /* EnumDeclaration */: + case 229 /* EnumMember */: + case 203 /* FunctionDeclaration */: + case 165 /* FunctionExpression */: errorNode = node.name; break; } @@ -4461,11 +4942,11 @@ var ts; } ts.isDeclarationFile = isDeclarationFile; function isConstEnumDeclaration(node) { - return node.kind === 205 /* EnumDeclaration */ && isConst(node); + return node.kind === 207 /* EnumDeclaration */ && isConst(node); } ts.isConstEnumDeclaration = isConstEnumDeclaration; function walkUpBindingElementsAndPatterns(node) { - while (node && (node.kind === 153 /* BindingElement */ || isBindingPattern(node))) { + while (node && (node.kind === 155 /* BindingElement */ || isBindingPattern(node))) { node = node.parent; } return node; @@ -4480,14 +4961,14 @@ var ts; function getCombinedNodeFlags(node) { node = walkUpBindingElementsAndPatterns(node); var flags = node.flags; - if (node.kind === 199 /* VariableDeclaration */) { + if (node.kind === 201 /* VariableDeclaration */) { node = node.parent; } - if (node && node.kind === 200 /* VariableDeclarationList */) { + if (node && node.kind === 202 /* VariableDeclarationList */) { flags |= node.flags; node = node.parent; } - if (node && node.kind === 181 /* VariableStatement */) { + if (node && node.kind === 183 /* VariableStatement */) { flags |= node.flags; } return flags; @@ -4502,12 +4983,12 @@ var ts; } ts.isLet = isLet; function isPrologueDirective(node) { - return node.kind === 183 /* ExpressionStatement */ && node.expression.kind === 8 /* StringLiteral */; + return node.kind === 185 /* ExpressionStatement */ && node.expression.kind === 8 /* StringLiteral */; } ts.isPrologueDirective = isPrologueDirective; function getLeadingCommentRangesOfNode(node, sourceFileOfNode) { // If parameter/type parameter, the prev token trailing comments are part of this node too - if (node.kind === 130 /* Parameter */ || node.kind === 129 /* TypeParameter */) { + if (node.kind === 131 /* Parameter */ || node.kind === 130 /* TypeParameter */) { // e.g. (/** blah */ a, /** blah */ b); // e.g.: ( // /** blah */ a, @@ -4530,45 +5011,165 @@ var ts; } ts.getJsDocComments = getJsDocComments; ts.fullTripleSlashReferencePathRegEx = /^(\/\/\/\s*/; + function isTypeNode(node) { + if (144 /* FirstTypeNode */ <= node.kind && node.kind <= 152 /* LastTypeNode */) { + return true; + } + switch (node.kind) { + case 112 /* AnyKeyword */: + case 121 /* NumberKeyword */: + case 123 /* StringKeyword */: + case 113 /* BooleanKeyword */: + case 124 /* SymbolKeyword */: + return true; + case 99 /* VoidKeyword */: + return node.parent.kind !== 169 /* VoidExpression */; + case 8 /* StringLiteral */: + // Specialized signatures can have string literals as their parameters' type names + return node.parent.kind === 131 /* Parameter */; + case 179 /* ExpressionWithTypeArguments */: + return !isExpressionWithTypeArgumentsInClassExtendsClause(node); + // Identifiers and qualified names may be type nodes, depending on their context. Climb + // above them to find the lowest container + case 65 /* Identifier */: + // If the identifier is the RHS of a qualified name, then it's a type iff its parent is. + if (node.parent.kind === 128 /* QualifiedName */ && node.parent.right === node) { + node = node.parent; + } + else if (node.parent.kind === 158 /* PropertyAccessExpression */ && node.parent.name === node) { + node = node.parent; + } + // fall through + case 128 /* QualifiedName */: + case 158 /* PropertyAccessExpression */: + // At this point, node is either a qualified name or an identifier + ts.Debug.assert(node.kind === 65 /* Identifier */ || node.kind === 128 /* QualifiedName */ || node.kind === 158 /* PropertyAccessExpression */, "'node' was expected to be a qualified name, identifier or property access in 'isTypeNode'."); + var parent_1 = node.parent; + if (parent_1.kind === 147 /* TypeQuery */) { + return false; + } + // Do not recursively call isTypeNode on the parent. In the example: + // + // let a: A.B.C; + // + // Calling isTypeNode would consider the qualified name A.B a type node. Only C or + // A.B.C is a type node. + if (144 /* FirstTypeNode */ <= parent_1.kind && parent_1.kind <= 152 /* LastTypeNode */) { + return true; + } + switch (parent_1.kind) { + case 179 /* ExpressionWithTypeArguments */: + return !isExpressionWithTypeArgumentsInClassExtendsClause(parent_1); + case 130 /* TypeParameter */: + return node === parent_1.constraint; + case 134 /* PropertyDeclaration */: + case 133 /* PropertySignature */: + case 131 /* Parameter */: + case 201 /* VariableDeclaration */: + return node === parent_1.type; + case 203 /* FunctionDeclaration */: + case 165 /* FunctionExpression */: + case 166 /* ArrowFunction */: + case 137 /* Constructor */: + case 136 /* MethodDeclaration */: + case 135 /* MethodSignature */: + case 138 /* GetAccessor */: + case 139 /* SetAccessor */: + return node === parent_1.type; + case 140 /* CallSignature */: + case 141 /* ConstructSignature */: + case 142 /* IndexSignature */: + return node === parent_1.type; + case 163 /* TypeAssertionExpression */: + return node === parent_1.type; + case 160 /* CallExpression */: + case 161 /* NewExpression */: + return parent_1.typeArguments && ts.indexOf(parent_1.typeArguments, node) >= 0; + case 162 /* TaggedTemplateExpression */: + // TODO (drosen): TaggedTemplateExpressions may eventually support type arguments. + return false; + } + } + return false; + } + ts.isTypeNode = isTypeNode; // 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) { return traverse(body); function traverse(node) { switch (node.kind) { - case 192 /* ReturnStatement */: + case 194 /* ReturnStatement */: return visitor(node); - case 208 /* CaseBlock */: - case 180 /* Block */: - case 184 /* IfStatement */: - case 185 /* DoStatement */: - case 186 /* WhileStatement */: - case 187 /* ForStatement */: - case 188 /* ForInStatement */: - case 189 /* ForOfStatement */: - case 193 /* WithStatement */: - case 194 /* SwitchStatement */: - case 221 /* CaseClause */: - case 222 /* DefaultClause */: - case 195 /* LabeledStatement */: - case 197 /* TryStatement */: - case 224 /* CatchClause */: + case 210 /* CaseBlock */: + case 182 /* Block */: + case 186 /* IfStatement */: + case 187 /* DoStatement */: + case 188 /* WhileStatement */: + case 189 /* ForStatement */: + case 190 /* ForInStatement */: + case 191 /* ForOfStatement */: + case 195 /* WithStatement */: + case 196 /* SwitchStatement */: + case 223 /* CaseClause */: + case 224 /* DefaultClause */: + case 197 /* LabeledStatement */: + case 199 /* TryStatement */: + case 226 /* CatchClause */: return ts.forEachChild(node, traverse); } } } ts.forEachReturnStatement = forEachReturnStatement; + function forEachYieldExpression(body, visitor) { + return traverse(body); + function traverse(node) { + switch (node.kind) { + case 175 /* YieldExpression */: + visitor(node); + var operand = node.expression; + if (operand) { + traverse(operand); + } + case 207 /* EnumDeclaration */: + case 205 /* InterfaceDeclaration */: + case 208 /* ModuleDeclaration */: + case 206 /* TypeAliasDeclaration */: + case 204 /* ClassDeclaration */: + // These are not allowed inside a generator now, but eventually they may be allowed + // as local types. Regardless, any yield statements contained within them should be + // skipped in this traversal. + return; + default: + if (isFunctionLike(node)) { + var name_4 = node.name; + if (name_4 && name_4.kind === 129 /* ComputedPropertyName */) { + // Note that we will not include methods/accessors of a class because they would require + // first descending into the class. This is by design. + traverse(name_4.expression); + return; + } + } + else if (!isTypeNode(node)) { + // This is the general case, which should include mostly expressions and statements. + // Also includes NodeArrays. + ts.forEachChild(node, traverse); + } + } + } + } + ts.forEachYieldExpression = forEachYieldExpression; function isVariableLike(node) { if (node) { switch (node.kind) { - case 153 /* BindingElement */: - case 227 /* EnumMember */: - case 130 /* Parameter */: - case 225 /* PropertyAssignment */: - case 133 /* PropertyDeclaration */: - case 132 /* PropertySignature */: - case 226 /* ShorthandPropertyAssignment */: - case 199 /* VariableDeclaration */: + case 155 /* BindingElement */: + case 229 /* EnumMember */: + case 131 /* Parameter */: + case 227 /* PropertyAssignment */: + case 134 /* PropertyDeclaration */: + case 133 /* PropertySignature */: + case 228 /* ShorthandPropertyAssignment */: + case 201 /* VariableDeclaration */: return true; } } @@ -4578,30 +5179,36 @@ var ts; function isAccessor(node) { if (node) { switch (node.kind) { - case 137 /* GetAccessor */: - case 138 /* SetAccessor */: + case 138 /* GetAccessor */: + case 139 /* SetAccessor */: return true; } } return false; } ts.isAccessor = isAccessor; + function isClassLike(node) { + if (node) { + return node.kind === 204 /* ClassDeclaration */ || node.kind === 177 /* ClassExpression */; + } + } + ts.isClassLike = isClassLike; function isFunctionLike(node) { if (node) { switch (node.kind) { - case 136 /* Constructor */: - case 163 /* FunctionExpression */: - case 201 /* FunctionDeclaration */: - case 164 /* ArrowFunction */: - case 135 /* MethodDeclaration */: - case 134 /* MethodSignature */: - case 137 /* GetAccessor */: - case 138 /* SetAccessor */: - case 139 /* CallSignature */: - case 140 /* ConstructSignature */: - case 141 /* IndexSignature */: - case 143 /* FunctionType */: - case 144 /* ConstructorType */: + case 137 /* Constructor */: + case 165 /* FunctionExpression */: + case 203 /* FunctionDeclaration */: + case 166 /* ArrowFunction */: + case 136 /* MethodDeclaration */: + case 135 /* MethodSignature */: + case 138 /* GetAccessor */: + case 139 /* SetAccessor */: + case 140 /* CallSignature */: + case 141 /* ConstructSignature */: + case 142 /* IndexSignature */: + case 145 /* FunctionType */: + case 146 /* ConstructorType */: return true; } } @@ -4609,11 +5216,11 @@ var ts; } ts.isFunctionLike = isFunctionLike; function isFunctionBlock(node) { - return node && node.kind === 180 /* Block */ && isFunctionLike(node.parent); + return node && node.kind === 182 /* Block */ && isFunctionLike(node.parent); } ts.isFunctionBlock = isFunctionBlock; function isObjectLiteralMethod(node) { - return node && node.kind === 135 /* MethodDeclaration */ && node.parent.kind === 155 /* ObjectLiteralExpression */; + return node && node.kind === 136 /* MethodDeclaration */ && node.parent.kind === 157 /* ObjectLiteralExpression */; } ts.isObjectLiteralMethod = isObjectLiteralMethod; function getContainingFunction(node) { @@ -4632,12 +5239,12 @@ var ts; return undefined; } switch (node.kind) { - case 128 /* ComputedPropertyName */: + case 129 /* ComputedPropertyName */: // If the grandparent node is an object literal (as opposed to a class), // 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 (node.parent.parent.kind === 202 /* ClassDeclaration */) { + if (node.parent.parent.kind === 204 /* ClassDeclaration */) { return node; } // If this is a computed property, then the parent should not @@ -4647,9 +5254,9 @@ var ts; // the *body* of the container. node = node.parent; break; - case 131 /* Decorator */: + case 132 /* Decorator */: // Decorators are always applied outside of the body of a class or method. - if (node.parent.kind === 130 /* Parameter */ && isClassElement(node.parent.parent)) { + if (node.parent.kind === 131 /* Parameter */ && 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; @@ -4660,23 +5267,23 @@ var ts; node = node.parent; } break; - case 164 /* ArrowFunction */: + case 166 /* ArrowFunction */: if (!includeArrowFunctions) { continue; } // Fall through - case 201 /* FunctionDeclaration */: - case 163 /* FunctionExpression */: - case 206 /* ModuleDeclaration */: - case 133 /* PropertyDeclaration */: - case 132 /* PropertySignature */: - case 135 /* MethodDeclaration */: - case 134 /* MethodSignature */: - case 136 /* Constructor */: - case 137 /* GetAccessor */: - case 138 /* SetAccessor */: - case 205 /* EnumDeclaration */: - case 228 /* SourceFile */: + case 203 /* FunctionDeclaration */: + case 165 /* FunctionExpression */: + case 208 /* ModuleDeclaration */: + case 134 /* PropertyDeclaration */: + case 133 /* PropertySignature */: + case 136 /* MethodDeclaration */: + case 135 /* MethodSignature */: + case 137 /* Constructor */: + case 138 /* GetAccessor */: + case 139 /* SetAccessor */: + case 207 /* EnumDeclaration */: + case 230 /* SourceFile */: return node; } } @@ -4688,12 +5295,12 @@ var ts; if (!node) return node; switch (node.kind) { - case 128 /* ComputedPropertyName */: + case 129 /* ComputedPropertyName */: // If the grandparent node is an object literal (as opposed to a class), // then the computed property is not a 'super' container. // A computed property name in a class needs to be a super container // so that we can error on it. - if (node.parent.parent.kind === 202 /* ClassDeclaration */) { + if (node.parent.parent.kind === 204 /* ClassDeclaration */) { return node; } // If this is a computed property, then the parent should not @@ -4703,9 +5310,9 @@ var ts; // the *body* of the container. node = node.parent; break; - case 131 /* Decorator */: + case 132 /* Decorator */: // Decorators are always applied outside of the body of a class or method. - if (node.parent.kind === 130 /* Parameter */ && isClassElement(node.parent.parent)) { + if (node.parent.kind === 131 /* Parameter */ && 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; @@ -4716,26 +5323,26 @@ var ts; node = node.parent; } break; - case 201 /* FunctionDeclaration */: - case 163 /* FunctionExpression */: - case 164 /* ArrowFunction */: + case 203 /* FunctionDeclaration */: + case 165 /* FunctionExpression */: + case 166 /* ArrowFunction */: if (!includeFunctions) { continue; } - case 133 /* PropertyDeclaration */: - case 132 /* PropertySignature */: - case 135 /* MethodDeclaration */: - case 134 /* MethodSignature */: - case 136 /* Constructor */: - case 137 /* GetAccessor */: - case 138 /* SetAccessor */: + case 134 /* PropertyDeclaration */: + case 133 /* PropertySignature */: + case 136 /* MethodDeclaration */: + case 135 /* MethodSignature */: + case 137 /* Constructor */: + case 138 /* GetAccessor */: + case 139 /* SetAccessor */: return node; } } } ts.getSuperContainer = getSuperContainer; function getInvokedExpression(node) { - if (node.kind === 160 /* TaggedTemplateExpression */) { + if (node.kind === 162 /* TaggedTemplateExpression */) { return node.tag; } // Will either be a CallExpression or NewExpression. @@ -4744,44 +5351,44 @@ var ts; ts.getInvokedExpression = getInvokedExpression; function nodeCanBeDecorated(node) { switch (node.kind) { - case 202 /* ClassDeclaration */: + case 204 /* ClassDeclaration */: // classes are valid targets return true; - case 133 /* PropertyDeclaration */: + case 134 /* PropertyDeclaration */: // property declarations are valid if their parent is a class declaration. - return node.parent.kind === 202 /* ClassDeclaration */; - case 130 /* Parameter */: + return node.parent.kind === 204 /* ClassDeclaration */; + case 131 /* Parameter */: // if the parameter's parent has a body and its grandparent is a class declaration, this is a valid target; - return node.parent.body && node.parent.parent.kind === 202 /* ClassDeclaration */; - case 137 /* GetAccessor */: - case 138 /* SetAccessor */: - case 135 /* MethodDeclaration */: + return node.parent.body && node.parent.parent.kind === 204 /* ClassDeclaration */; + case 138 /* GetAccessor */: + case 139 /* SetAccessor */: + case 136 /* MethodDeclaration */: // if this method has a body and its parent is a class declaration, this is a valid target. - return node.body && node.parent.kind === 202 /* ClassDeclaration */; + return node.body && node.parent.kind === 204 /* ClassDeclaration */; } return false; } ts.nodeCanBeDecorated = nodeCanBeDecorated; function nodeIsDecorated(node) { switch (node.kind) { - case 202 /* ClassDeclaration */: + case 204 /* ClassDeclaration */: if (node.decorators) { return true; } return false; - case 133 /* PropertyDeclaration */: - case 130 /* Parameter */: + case 134 /* PropertyDeclaration */: + case 131 /* Parameter */: if (node.decorators) { return true; } return false; - case 137 /* GetAccessor */: + case 138 /* GetAccessor */: if (node.body && node.decorators) { return true; } return false; - case 135 /* MethodDeclaration */: - case 138 /* SetAccessor */: + case 136 /* MethodDeclaration */: + case 139 /* SetAccessor */: if (node.body && node.decorators) { return true; } @@ -4792,10 +5399,10 @@ var ts; ts.nodeIsDecorated = nodeIsDecorated; function childIsDecorated(node) { switch (node.kind) { - case 202 /* ClassDeclaration */: + case 204 /* ClassDeclaration */: return ts.forEach(node.members, nodeOrChildIsDecorated); - case 135 /* MethodDeclaration */: - case 138 /* SetAccessor */: + case 136 /* MethodDeclaration */: + case 139 /* SetAccessor */: return ts.forEach(node.parameters, nodeIsDecorated); } return false; @@ -4813,83 +5420,86 @@ var ts; case 95 /* TrueKeyword */: case 80 /* FalseKeyword */: case 9 /* RegularExpressionLiteral */: - case 154 /* ArrayLiteralExpression */: - case 155 /* ObjectLiteralExpression */: - case 156 /* PropertyAccessExpression */: - case 157 /* ElementAccessExpression */: - case 158 /* CallExpression */: - case 159 /* NewExpression */: - case 160 /* TaggedTemplateExpression */: - case 161 /* TypeAssertionExpression */: - case 162 /* ParenthesizedExpression */: - case 163 /* FunctionExpression */: - case 175 /* ClassExpression */: - case 164 /* ArrowFunction */: - case 167 /* VoidExpression */: - case 165 /* DeleteExpression */: - case 166 /* TypeOfExpression */: - case 168 /* PrefixUnaryExpression */: - case 169 /* PostfixUnaryExpression */: - case 170 /* BinaryExpression */: - case 171 /* ConditionalExpression */: - case 174 /* SpreadElementExpression */: - case 172 /* TemplateExpression */: + case 156 /* ArrayLiteralExpression */: + case 157 /* ObjectLiteralExpression */: + case 158 /* PropertyAccessExpression */: + case 159 /* ElementAccessExpression */: + case 160 /* CallExpression */: + case 161 /* NewExpression */: + case 162 /* TaggedTemplateExpression */: + case 163 /* TypeAssertionExpression */: + case 164 /* ParenthesizedExpression */: + case 165 /* FunctionExpression */: + case 177 /* ClassExpression */: + case 166 /* ArrowFunction */: + case 169 /* VoidExpression */: + case 167 /* DeleteExpression */: + case 168 /* TypeOfExpression */: + case 170 /* PrefixUnaryExpression */: + case 171 /* PostfixUnaryExpression */: + case 172 /* BinaryExpression */: + case 173 /* ConditionalExpression */: + case 176 /* SpreadElementExpression */: + case 174 /* TemplateExpression */: case 10 /* NoSubstitutionTemplateLiteral */: - case 176 /* OmittedExpression */: + case 178 /* OmittedExpression */: + case 175 /* YieldExpression */: return true; - case 127 /* QualifiedName */: - while (node.parent.kind === 127 /* QualifiedName */) { + case 128 /* QualifiedName */: + while (node.parent.kind === 128 /* QualifiedName */) { node = node.parent; } - return node.parent.kind === 145 /* TypeQuery */; + return node.parent.kind === 147 /* TypeQuery */; case 65 /* Identifier */: - if (node.parent.kind === 145 /* TypeQuery */) { + if (node.parent.kind === 147 /* TypeQuery */) { return true; } // fall through case 7 /* NumericLiteral */: case 8 /* StringLiteral */: - var parent_1 = node.parent; - switch (parent_1.kind) { - case 199 /* VariableDeclaration */: - case 130 /* Parameter */: - case 133 /* PropertyDeclaration */: - case 132 /* PropertySignature */: - case 227 /* EnumMember */: - case 225 /* PropertyAssignment */: - case 153 /* BindingElement */: - return parent_1.initializer === node; - case 183 /* ExpressionStatement */: - case 184 /* IfStatement */: - case 185 /* DoStatement */: - case 186 /* WhileStatement */: - case 192 /* ReturnStatement */: - case 193 /* WithStatement */: - case 194 /* SwitchStatement */: - case 221 /* CaseClause */: - case 196 /* ThrowStatement */: - case 194 /* SwitchStatement */: - return parent_1.expression === node; - case 187 /* ForStatement */: - var forStatement = parent_1; - return (forStatement.initializer === node && forStatement.initializer.kind !== 200 /* VariableDeclarationList */) || + var parent_2 = node.parent; + switch (parent_2.kind) { + case 201 /* VariableDeclaration */: + case 131 /* Parameter */: + case 134 /* PropertyDeclaration */: + case 133 /* PropertySignature */: + case 229 /* EnumMember */: + case 227 /* PropertyAssignment */: + case 155 /* BindingElement */: + return parent_2.initializer === node; + case 185 /* ExpressionStatement */: + case 186 /* IfStatement */: + case 187 /* DoStatement */: + case 188 /* WhileStatement */: + case 194 /* ReturnStatement */: + case 195 /* WithStatement */: + case 196 /* SwitchStatement */: + case 223 /* CaseClause */: + case 198 /* ThrowStatement */: + case 196 /* SwitchStatement */: + return parent_2.expression === node; + case 189 /* ForStatement */: + var forStatement = parent_2; + return (forStatement.initializer === node && forStatement.initializer.kind !== 202 /* VariableDeclarationList */) || forStatement.condition === node || forStatement.incrementor === node; - case 188 /* ForInStatement */: - case 189 /* ForOfStatement */: - var forInStatement = parent_1; - return (forInStatement.initializer === node && forInStatement.initializer.kind !== 200 /* VariableDeclarationList */) || + case 190 /* ForInStatement */: + case 191 /* ForOfStatement */: + var forInStatement = parent_2; + return (forInStatement.initializer === node && forInStatement.initializer.kind !== 202 /* VariableDeclarationList */) || forInStatement.expression === node; - case 161 /* TypeAssertionExpression */: - return node === parent_1.expression; - case 178 /* TemplateSpan */: - return node === parent_1.expression; - case 128 /* ComputedPropertyName */: - return node === parent_1.expression; - case 131 /* Decorator */: + case 163 /* TypeAssertionExpression */: + return node === parent_2.expression; + case 180 /* TemplateSpan */: + return node === parent_2.expression; + case 129 /* ComputedPropertyName */: + return node === parent_2.expression; + case 132 /* Decorator */: return true; + case 179 /* ExpressionWithTypeArguments */: + return parent_2.expression === node && isExpressionWithTypeArgumentsInClassExtendsClause(parent_2); default: - if (isExpression(parent_1)) { + if (isExpression(parent_2)) { return true; } } @@ -4904,7 +5514,7 @@ var ts; } ts.isInstantiatedModule = isInstantiatedModule; function isExternalModuleImportEqualsDeclaration(node) { - return node.kind === 209 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 220 /* ExternalModuleReference */; + return node.kind === 211 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 222 /* ExternalModuleReference */; } ts.isExternalModuleImportEqualsDeclaration = isExternalModuleImportEqualsDeclaration; function getExternalModuleImportEqualsDeclarationExpression(node) { @@ -4913,50 +5523,110 @@ var ts; } ts.getExternalModuleImportEqualsDeclarationExpression = getExternalModuleImportEqualsDeclarationExpression; function isInternalModuleImportEqualsDeclaration(node) { - return node.kind === 209 /* ImportEqualsDeclaration */ && node.moduleReference.kind !== 220 /* ExternalModuleReference */; + return node.kind === 211 /* ImportEqualsDeclaration */ && node.moduleReference.kind !== 222 /* ExternalModuleReference */; } ts.isInternalModuleImportEqualsDeclaration = isInternalModuleImportEqualsDeclaration; function getExternalModuleName(node) { - if (node.kind === 210 /* ImportDeclaration */) { + if (node.kind === 212 /* ImportDeclaration */) { return node.moduleSpecifier; } - if (node.kind === 209 /* ImportEqualsDeclaration */) { + if (node.kind === 211 /* ImportEqualsDeclaration */) { var reference = node.moduleReference; - if (reference.kind === 220 /* ExternalModuleReference */) { + if (reference.kind === 222 /* ExternalModuleReference */) { return reference.expression; } } - if (node.kind === 216 /* ExportDeclaration */) { + if (node.kind === 218 /* ExportDeclaration */) { return node.moduleSpecifier; } } ts.getExternalModuleName = getExternalModuleName; - function hasDotDotDotToken(node) { - return node && node.kind === 130 /* Parameter */ && node.dotDotDotToken !== undefined; - } - ts.hasDotDotDotToken = hasDotDotDotToken; function hasQuestionToken(node) { if (node) { switch (node.kind) { - case 130 /* Parameter */: + case 131 /* Parameter */: return node.questionToken !== undefined; - case 135 /* MethodDeclaration */: - case 134 /* MethodSignature */: + case 136 /* MethodDeclaration */: + case 135 /* MethodSignature */: return node.questionToken !== undefined; - case 226 /* ShorthandPropertyAssignment */: - case 225 /* PropertyAssignment */: - case 133 /* PropertyDeclaration */: - case 132 /* PropertySignature */: + case 228 /* ShorthandPropertyAssignment */: + case 227 /* PropertyAssignment */: + case 134 /* PropertyDeclaration */: + case 133 /* PropertySignature */: return node.questionToken !== undefined; } } return false; } ts.hasQuestionToken = hasQuestionToken; - function hasRestParameters(s) { - return s.parameters.length > 0 && ts.lastOrUndefined(s.parameters).dotDotDotToken !== undefined; + function isJSDocConstructSignature(node) { + return node.kind === 243 /* JSDocFunctionType */ && + node.parameters.length > 0 && + node.parameters[0].type.kind === 245 /* JSDocConstructorType */; } - ts.hasRestParameters = hasRestParameters; + ts.isJSDocConstructSignature = isJSDocConstructSignature; + function getJSDocTag(node, kind) { + if (node && node.jsDocComment) { + for (var _i = 0, _a = node.jsDocComment.tags; _i < _a.length; _i++) { + var tag = _a[_i]; + if (tag.kind === kind) { + return tag; + } + } + } + } + function getJSDocTypeTag(node) { + return getJSDocTag(node, 251 /* JSDocTypeTag */); + } + ts.getJSDocTypeTag = getJSDocTypeTag; + function getJSDocReturnTag(node) { + return getJSDocTag(node, 250 /* JSDocReturnTag */); + } + ts.getJSDocReturnTag = getJSDocReturnTag; + function getJSDocTemplateTag(node) { + return getJSDocTag(node, 252 /* JSDocTemplateTag */); + } + ts.getJSDocTemplateTag = getJSDocTemplateTag; + function getCorrespondingJSDocParameterTag(parameter) { + if (parameter.name && parameter.name.kind === 65 /* Identifier */) { + // If it's a parameter, see if the parent has a jsdoc comment with an @param + // annotation. + var parameterName = parameter.name.text; + var docComment = parameter.parent.jsDocComment; + if (docComment) { + return ts.forEach(docComment.tags, function (t) { + if (t.kind === 249 /* JSDocParameterTag */) { + var parameterTag = t; + var name_5 = parameterTag.preParameterName || parameterTag.postParameterName; + if (name_5.text === parameterName) { + return t; + } + } + }); + } + } + } + ts.getCorrespondingJSDocParameterTag = getCorrespondingJSDocParameterTag; + function hasRestParameter(s) { + return isRestParameter(ts.lastOrUndefined(s.parameters)); + } + ts.hasRestParameter = hasRestParameter; + function isRestParameter(node) { + if (node) { + if (node.parserContextFlags & 64 /* JavaScriptFile */) { + if (node.type && node.type.kind === 244 /* JSDocVariadicType */) { + return true; + } + var paramTag = getCorrespondingJSDocParameterTag(node); + if (paramTag && paramTag.typeExpression) { + return paramTag.typeExpression.type.kind === 244 /* JSDocVariadicType */; + } + } + return node.dotDotDotToken !== undefined; + } + return false; + } + ts.isRestParameter = isRestParameter; function isLiteralKind(kind) { return 7 /* FirstLiteralToken */ <= kind && kind <= 10 /* LastLiteralToken */; } @@ -4970,7 +5640,7 @@ var ts; } ts.isTemplateLiteralKind = isTemplateLiteralKind; function isBindingPattern(node) { - return !!node && (node.kind === 152 /* ArrayBindingPattern */ || node.kind === 151 /* ObjectBindingPattern */); + return !!node && (node.kind === 154 /* ArrayBindingPattern */ || node.kind === 153 /* ObjectBindingPattern */); } ts.isBindingPattern = isBindingPattern; function isInAmbientContext(node) { @@ -4985,33 +5655,33 @@ var ts; ts.isInAmbientContext = isInAmbientContext; function isDeclaration(node) { switch (node.kind) { - case 164 /* ArrowFunction */: - case 153 /* BindingElement */: - case 202 /* ClassDeclaration */: - case 136 /* Constructor */: - case 205 /* EnumDeclaration */: - case 227 /* EnumMember */: - case 218 /* ExportSpecifier */: - case 201 /* FunctionDeclaration */: - case 163 /* FunctionExpression */: - case 137 /* GetAccessor */: - case 211 /* ImportClause */: - case 209 /* ImportEqualsDeclaration */: - case 214 /* ImportSpecifier */: - case 203 /* InterfaceDeclaration */: - case 135 /* MethodDeclaration */: - case 134 /* MethodSignature */: - case 206 /* ModuleDeclaration */: - case 212 /* NamespaceImport */: - case 130 /* Parameter */: - case 225 /* PropertyAssignment */: - case 133 /* PropertyDeclaration */: - case 132 /* PropertySignature */: - case 138 /* SetAccessor */: - case 226 /* ShorthandPropertyAssignment */: - case 204 /* TypeAliasDeclaration */: - case 129 /* TypeParameter */: - case 199 /* VariableDeclaration */: + case 166 /* ArrowFunction */: + case 155 /* BindingElement */: + case 204 /* ClassDeclaration */: + case 137 /* Constructor */: + case 207 /* EnumDeclaration */: + case 229 /* EnumMember */: + case 220 /* ExportSpecifier */: + case 203 /* FunctionDeclaration */: + case 165 /* FunctionExpression */: + case 138 /* GetAccessor */: + case 213 /* ImportClause */: + case 211 /* ImportEqualsDeclaration */: + case 216 /* ImportSpecifier */: + case 205 /* InterfaceDeclaration */: + case 136 /* MethodDeclaration */: + case 135 /* MethodSignature */: + case 208 /* ModuleDeclaration */: + case 214 /* NamespaceImport */: + case 131 /* Parameter */: + case 227 /* PropertyAssignment */: + case 134 /* PropertyDeclaration */: + case 133 /* PropertySignature */: + case 139 /* SetAccessor */: + case 228 /* ShorthandPropertyAssignment */: + case 206 /* TypeAliasDeclaration */: + case 130 /* TypeParameter */: + case 201 /* VariableDeclaration */: return true; } return false; @@ -5019,25 +5689,25 @@ var ts; ts.isDeclaration = isDeclaration; function isStatement(n) { switch (n.kind) { - case 191 /* BreakStatement */: - case 190 /* ContinueStatement */: - case 198 /* DebuggerStatement */: - case 185 /* DoStatement */: - case 183 /* ExpressionStatement */: - case 182 /* EmptyStatement */: - case 188 /* ForInStatement */: - case 189 /* ForOfStatement */: - case 187 /* ForStatement */: - case 184 /* IfStatement */: - case 195 /* LabeledStatement */: - case 192 /* ReturnStatement */: - case 194 /* SwitchStatement */: + case 193 /* BreakStatement */: + case 192 /* ContinueStatement */: + case 200 /* DebuggerStatement */: + case 187 /* DoStatement */: + case 185 /* ExpressionStatement */: + case 184 /* EmptyStatement */: + case 190 /* ForInStatement */: + case 191 /* ForOfStatement */: + case 189 /* ForStatement */: + case 186 /* IfStatement */: + case 197 /* LabeledStatement */: + case 194 /* ReturnStatement */: + case 196 /* SwitchStatement */: case 94 /* ThrowKeyword */: - case 197 /* TryStatement */: - case 181 /* VariableStatement */: - case 186 /* WhileStatement */: - case 193 /* WithStatement */: - case 215 /* ExportAssignment */: + case 199 /* TryStatement */: + case 183 /* VariableStatement */: + case 188 /* WhileStatement */: + case 195 /* WithStatement */: + case 217 /* ExportAssignment */: return true; default: return false; @@ -5046,13 +5716,13 @@ var ts; ts.isStatement = isStatement; function isClassElement(n) { switch (n.kind) { - case 136 /* Constructor */: - case 133 /* PropertyDeclaration */: - case 135 /* MethodDeclaration */: - case 137 /* GetAccessor */: - case 138 /* SetAccessor */: - case 134 /* MethodSignature */: - case 141 /* IndexSignature */: + case 137 /* Constructor */: + case 134 /* PropertyDeclaration */: + case 136 /* MethodDeclaration */: + case 138 /* GetAccessor */: + case 139 /* SetAccessor */: + case 135 /* MethodSignature */: + case 142 /* IndexSignature */: return true; default: return false; @@ -5065,7 +5735,7 @@ var ts; return false; } var parent = name.parent; - if (parent.kind === 214 /* ImportSpecifier */ || parent.kind === 218 /* ExportSpecifier */) { + if (parent.kind === 216 /* ImportSpecifier */ || parent.kind === 220 /* ExportSpecifier */) { if (parent.propertyName) { return true; } @@ -5076,6 +5746,41 @@ var ts; return false; } ts.isDeclarationName = isDeclarationName; + // Return true if the given identifier is classified as an IdentifierName + function isIdentifierName(node) { + var parent = node.parent; + switch (parent.kind) { + case 134 /* PropertyDeclaration */: + case 133 /* PropertySignature */: + case 136 /* MethodDeclaration */: + case 135 /* MethodSignature */: + case 138 /* GetAccessor */: + case 139 /* SetAccessor */: + case 229 /* EnumMember */: + case 227 /* PropertyAssignment */: + case 158 /* PropertyAccessExpression */: + // Name in member declaration or property name in property access + return parent.name === node; + case 128 /* QualifiedName */: + // Name on right hand side of dot in a type query + if (parent.right === node) { + while (parent.kind === 128 /* QualifiedName */) { + parent = parent.parent; + } + return parent.kind === 147 /* TypeQuery */; + } + return false; + case 155 /* BindingElement */: + case 216 /* ImportSpecifier */: + // Property name in binding element or import specifier + return parent.propertyName === node; + case 220 /* ExportSpecifier */: + // Any name in an export specifier + return true; + } + return false; + } + ts.isIdentifierName = isIdentifierName; // An alias symbol is created by one of the following declarations: // import = ... // import from ... @@ -5085,12 +5790,12 @@ var ts; // export = ... // export default ... function isAliasSymbolDeclaration(node) { - return node.kind === 209 /* ImportEqualsDeclaration */ || - node.kind === 211 /* ImportClause */ && !!node.name || - node.kind === 212 /* NamespaceImport */ || - node.kind === 214 /* ImportSpecifier */ || - node.kind === 218 /* ExportSpecifier */ || - node.kind === 215 /* ExportAssignment */ && node.expression.kind === 65 /* Identifier */; + return node.kind === 211 /* ImportEqualsDeclaration */ || + node.kind === 213 /* ImportClause */ && !!node.name || + node.kind === 214 /* NamespaceImport */ || + node.kind === 216 /* ImportSpecifier */ || + node.kind === 220 /* ExportSpecifier */ || + node.kind === 217 /* ExportAssignment */ && node.expression.kind === 65 /* Identifier */; } ts.isAliasSymbolDeclaration = isAliasSymbolDeclaration; function getClassExtendsHeritageClauseElement(node) { @@ -5173,7 +5878,7 @@ var ts; } ts.getFileReferenceFromReferencePath = getFileReferenceFromReferencePath; function isKeyword(token) { - return 66 /* FirstKeyword */ <= token && token <= 126 /* LastKeyword */; + return 66 /* FirstKeyword */ <= token && token <= 127 /* LastKeyword */; } ts.isKeyword = isKeyword; function isTrivia(token) { @@ -5189,7 +5894,7 @@ var ts; */ function hasDynamicName(declaration) { return declaration.name && - declaration.name.kind === 128 /* ComputedPropertyName */ && + declaration.name.kind === 129 /* ComputedPropertyName */ && !isWellKnownSymbolSyntactically(declaration.name.expression); } ts.hasDynamicName = hasDynamicName; @@ -5199,14 +5904,14 @@ var ts; * where Symbol is literally the word "Symbol", and name is any identifierName */ function isWellKnownSymbolSyntactically(node) { - return node.kind === 156 /* PropertyAccessExpression */ && isESSymbolIdentifier(node.expression); + return node.kind === 158 /* PropertyAccessExpression */ && isESSymbolIdentifier(node.expression); } ts.isWellKnownSymbolSyntactically = isWellKnownSymbolSyntactically; function getPropertyNameForPropertyNameNode(name) { if (name.kind === 65 /* Identifier */ || name.kind === 8 /* StringLiteral */ || name.kind === 7 /* NumericLiteral */) { return name.text; } - if (name.kind === 128 /* ComputedPropertyName */) { + if (name.kind === 129 /* ComputedPropertyName */) { var nameExpression = name.expression; if (isWellKnownSymbolSyntactically(nameExpression)) { var rightHandSideName = nameExpression.name.text; @@ -5244,18 +5949,18 @@ var ts; ts.isModifier = isModifier; function isParameterDeclaration(node) { var root = getRootDeclaration(node); - return root.kind === 130 /* Parameter */; + return root.kind === 131 /* Parameter */; } ts.isParameterDeclaration = isParameterDeclaration; function getRootDeclaration(node) { - while (node.kind === 153 /* BindingElement */) { + while (node.kind === 155 /* BindingElement */) { node = node.parent.parent; } return node; } ts.getRootDeclaration = getRootDeclaration; function nodeStartsNewLexicalEnvironment(n) { - return isFunctionLike(n) || n.kind === 206 /* ModuleDeclaration */ || n.kind === 228 /* SourceFile */; + return isFunctionLike(n) || n.kind === 208 /* ModuleDeclaration */ || n.kind === 230 /* SourceFile */; } ts.nodeStartsNewLexicalEnvironment = nodeStartsNewLexicalEnvironment; function nodeIsSynthesized(node) { @@ -5491,7 +6196,7 @@ var ts; ts.getLineOfLocalPosition = getLineOfLocalPosition; function getFirstConstructorWithBody(node) { return ts.forEach(node.members, function (member) { - if (member.kind === 136 /* Constructor */ && nodeIsPresent(member.body)) { + if (member.kind === 137 /* Constructor */ && nodeIsPresent(member.body)) { return member; } }); @@ -5502,7 +6207,7 @@ var ts; if ((isExternalModule(sourceFile) || !compilerOptions.out)) { // 1. in-browser single file compilation scenario // 2. non .js file - return compilerOptions.separateCompilation || !ts.fileExtensionIs(sourceFile.fileName, ".js"); + return compilerOptions.isolatedModules || !ts.fileExtensionIs(sourceFile.fileName, ".js"); } return false; } @@ -5516,10 +6221,10 @@ var ts; var setAccessor; if (hasDynamicName(accessor)) { firstAccessor = accessor; - if (accessor.kind === 137 /* GetAccessor */) { + if (accessor.kind === 138 /* GetAccessor */) { getAccessor = accessor; } - else if (accessor.kind === 138 /* SetAccessor */) { + else if (accessor.kind === 139 /* SetAccessor */) { setAccessor = accessor; } else { @@ -5528,7 +6233,7 @@ var ts; } else { ts.forEach(declarations, function (member) { - if ((member.kind === 137 /* GetAccessor */ || member.kind === 138 /* SetAccessor */) + if ((member.kind === 138 /* GetAccessor */ || member.kind === 139 /* SetAccessor */) && (member.flags & 128 /* Static */) === (accessor.flags & 128 /* Static */)) { var memberName = getPropertyNameForPropertyNameNode(member.name); var accessorName = getPropertyNameForPropertyNameNode(accessor.name); @@ -5539,10 +6244,10 @@ var ts; else if (!secondAccessor) { secondAccessor = member; } - if (member.kind === 137 /* GetAccessor */ && !getAccessor) { + if (member.kind === 138 /* GetAccessor */ && !getAccessor) { getAccessor = member; } - if (member.kind === 138 /* SetAccessor */ && !setAccessor) { + if (member.kind === 139 /* SetAccessor */ && !setAccessor) { setAccessor = member; } } @@ -5690,22 +6395,22 @@ var ts; function isLeftHandSideExpression(expr) { if (expr) { switch (expr.kind) { - case 156 /* PropertyAccessExpression */: - case 157 /* ElementAccessExpression */: - case 159 /* NewExpression */: - case 158 /* CallExpression */: - case 160 /* TaggedTemplateExpression */: - case 154 /* ArrayLiteralExpression */: - case 162 /* ParenthesizedExpression */: - case 155 /* ObjectLiteralExpression */: - case 175 /* ClassExpression */: - case 163 /* FunctionExpression */: + case 158 /* PropertyAccessExpression */: + case 159 /* ElementAccessExpression */: + case 161 /* NewExpression */: + case 160 /* CallExpression */: + case 162 /* TaggedTemplateExpression */: + case 156 /* ArrayLiteralExpression */: + case 164 /* ParenthesizedExpression */: + case 157 /* ObjectLiteralExpression */: + case 177 /* ClassExpression */: + case 165 /* FunctionExpression */: case 65 /* Identifier */: case 9 /* RegularExpressionLiteral */: case 7 /* NumericLiteral */: case 8 /* StringLiteral */: case 10 /* NoSubstitutionTemplateLiteral */: - case 172 /* TemplateExpression */: + case 174 /* TemplateExpression */: case 80 /* FalseKeyword */: case 89 /* NullKeyword */: case 93 /* ThisKeyword */: @@ -5721,6 +6426,12 @@ var ts; return token >= 53 /* FirstAssignment */ && token <= 64 /* LastAssignment */; } ts.isAssignmentOperator = isAssignmentOperator; + function isExpressionWithTypeArgumentsInClassExtendsClause(node) { + return node.kind === 179 /* ExpressionWithTypeArguments */ && + node.parent.token === 79 /* ExtendsKeyword */ && + node.parent.parent.kind === 204 /* ClassDeclaration */; + } + ts.isExpressionWithTypeArgumentsInClassExtendsClause = isExpressionWithTypeArgumentsInClassExtendsClause; // Returns false if this heritage clause element's expression contains something unsupported // (i.e. not a name or dotted name). function isSupportedExpressionWithTypeArguments(node) { @@ -5731,7 +6442,7 @@ var ts; if (node.kind === 65 /* Identifier */) { return true; } - else if (node.kind === 156 /* PropertyAccessExpression */) { + else if (node.kind === 158 /* PropertyAccessExpression */) { return isSupportedExpressionWithTypeArgumentsRest(node.expression); } else { @@ -5739,14 +6450,18 @@ var ts; } } function isRightSideOfQualifiedNameOrPropertyAccess(node) { - return (node.parent.kind === 127 /* QualifiedName */ && node.parent.right === node) || - (node.parent.kind === 156 /* PropertyAccessExpression */ && node.parent.name === node); + return (node.parent.kind === 128 /* QualifiedName */ && node.parent.right === node) || + (node.parent.kind === 158 /* PropertyAccessExpression */ && node.parent.name === node); } ts.isRightSideOfQualifiedNameOrPropertyAccess = isRightSideOfQualifiedNameOrPropertyAccess; function getLocalSymbolForExportDefault(symbol) { return symbol && symbol.valueDeclaration && (symbol.valueDeclaration.flags & 256 /* Default */) ? symbol.valueDeclaration.localSymbol : undefined; } ts.getLocalSymbolForExportDefault = getLocalSymbolForExportDefault; + function isJavaScript(fileName) { + return ts.fileExtensionIs(fileName, ".js"); + } + ts.isJavaScript = isJavaScript; /** * Replace each instance of non-ascii characters by one, two, three, or four escape sequences * representing the UTF-8 encoding of the character, and return the expanded char code list. @@ -5814,6 +6529,21 @@ var ts; return result; } ts.convertToBase64 = convertToBase64; + var carriageReturnLineFeed = "\r\n"; + var lineFeed = "\n"; + function getNewLineCharacter(options) { + if (options.newLine === 0 /* CarriageReturnLineFeed */) { + return carriageReturnLineFeed; + } + else if (options.newLine === 1 /* LineFeed */) { + return lineFeed; + } + else if (ts.sys) { + return ts.sys.newLine; + } + return carriageReturnLineFeed; + } + ts.getNewLineCharacter = getNewLineCharacter; })(ts || (ts = {})); var ts; (function (ts) { @@ -5862,6 +6592,12 @@ var ts; 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; } @@ -6020,12 +6756,22 @@ var ts; return createTextChangeRange(createTextSpanFromBounds(oldStartN, oldEndN), newEndN - oldStartN); } ts.collapseTextChangeRangesAcrossMultipleVersions = collapseTextChangeRangesAcrossMultipleVersions; + function getTypeParameterOwner(d) { + if (d && d.kind === 130 /* TypeParameter */) { + for (var current = d; current; current = current.parent) { + if (ts.isFunctionLike(current) || ts.isClassLike(current) || current.kind === 205 /* InterfaceDeclaration */) { + return current; + } + } + } + } + ts.getTypeParameterOwner = getTypeParameterOwner; })(ts || (ts = {})); /// /// var ts; (function (ts) { - var nodeConstructors = new Array(230 /* Count */); + var nodeConstructors = new Array(254 /* Count */); /* @internal */ ts.parseTime = 0; function getNodeConstructor(kind) { return nodeConstructors[kind] || (nodeConstructors[kind] = ts.objectAllocator.getNodeConstructor(kind)); @@ -6070,20 +6816,20 @@ var ts; var visitNodes = cbNodeArray ? visitNodeArray : visitEachNode; var cbNodes = cbNodeArray || cbNode; switch (node.kind) { - case 127 /* QualifiedName */: + case 128 /* QualifiedName */: return visitNode(cbNode, node.left) || visitNode(cbNode, node.right); - case 129 /* TypeParameter */: + case 130 /* TypeParameter */: return visitNode(cbNode, node.name) || visitNode(cbNode, node.constraint) || visitNode(cbNode, node.expression); - case 130 /* Parameter */: - case 133 /* PropertyDeclaration */: - case 132 /* PropertySignature */: - case 225 /* PropertyAssignment */: - case 226 /* ShorthandPropertyAssignment */: - case 199 /* VariableDeclaration */: - case 153 /* BindingElement */: + case 131 /* Parameter */: + case 134 /* PropertyDeclaration */: + case 133 /* PropertySignature */: + case 227 /* PropertyAssignment */: + case 228 /* ShorthandPropertyAssignment */: + case 201 /* VariableDeclaration */: + case 155 /* BindingElement */: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.propertyName) || @@ -6092,24 +6838,24 @@ var ts; visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.type) || visitNode(cbNode, node.initializer); - case 143 /* FunctionType */: - case 144 /* ConstructorType */: - case 139 /* CallSignature */: - case 140 /* ConstructSignature */: - case 141 /* IndexSignature */: + case 145 /* FunctionType */: + case 146 /* ConstructorType */: + case 140 /* CallSignature */: + case 141 /* ConstructSignature */: + case 142 /* IndexSignature */: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNodes(cbNodes, node.typeParameters) || visitNodes(cbNodes, node.parameters) || visitNode(cbNode, node.type); - case 135 /* MethodDeclaration */: - case 134 /* MethodSignature */: - case 136 /* Constructor */: - case 137 /* GetAccessor */: - case 138 /* SetAccessor */: - case 163 /* FunctionExpression */: - case 201 /* FunctionDeclaration */: - case 164 /* ArrowFunction */: + case 136 /* MethodDeclaration */: + case 135 /* MethodSignature */: + case 137 /* Constructor */: + case 138 /* GetAccessor */: + case 139 /* SetAccessor */: + case 165 /* FunctionExpression */: + case 203 /* FunctionDeclaration */: + case 166 /* ArrowFunction */: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.asteriskToken) || @@ -6120,221 +6866,268 @@ var ts; visitNode(cbNode, node.type) || visitNode(cbNode, node.equalsGreaterThanToken) || visitNode(cbNode, node.body); - case 142 /* TypeReference */: + case 144 /* TypeReference */: return visitNode(cbNode, node.typeName) || visitNodes(cbNodes, node.typeArguments); - case 145 /* TypeQuery */: + case 143 /* TypePredicate */: + return visitNode(cbNode, node.parameterName) || + visitNode(cbNode, node.type); + case 147 /* TypeQuery */: return visitNode(cbNode, node.exprName); - case 146 /* TypeLiteral */: + case 148 /* TypeLiteral */: return visitNodes(cbNodes, node.members); - case 147 /* ArrayType */: + case 149 /* ArrayType */: return visitNode(cbNode, node.elementType); - case 148 /* TupleType */: + case 150 /* TupleType */: return visitNodes(cbNodes, node.elementTypes); - case 149 /* UnionType */: + case 151 /* UnionType */: return visitNodes(cbNodes, node.types); - case 150 /* ParenthesizedType */: + case 152 /* ParenthesizedType */: return visitNode(cbNode, node.type); - case 151 /* ObjectBindingPattern */: - case 152 /* ArrayBindingPattern */: + case 153 /* ObjectBindingPattern */: + case 154 /* ArrayBindingPattern */: return visitNodes(cbNodes, node.elements); - case 154 /* ArrayLiteralExpression */: + case 156 /* ArrayLiteralExpression */: return visitNodes(cbNodes, node.elements); - case 155 /* ObjectLiteralExpression */: + case 157 /* ObjectLiteralExpression */: return visitNodes(cbNodes, node.properties); - case 156 /* PropertyAccessExpression */: + case 158 /* PropertyAccessExpression */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.dotToken) || visitNode(cbNode, node.name); - case 157 /* ElementAccessExpression */: + case 159 /* ElementAccessExpression */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.argumentExpression); - case 158 /* CallExpression */: - case 159 /* NewExpression */: + case 160 /* CallExpression */: + case 161 /* NewExpression */: return visitNode(cbNode, node.expression) || visitNodes(cbNodes, node.typeArguments) || visitNodes(cbNodes, node.arguments); - case 160 /* TaggedTemplateExpression */: + case 162 /* TaggedTemplateExpression */: return visitNode(cbNode, node.tag) || visitNode(cbNode, node.template); - case 161 /* TypeAssertionExpression */: + case 163 /* TypeAssertionExpression */: return visitNode(cbNode, node.type) || visitNode(cbNode, node.expression); - case 162 /* ParenthesizedExpression */: + case 164 /* ParenthesizedExpression */: return visitNode(cbNode, node.expression); - case 165 /* DeleteExpression */: + case 167 /* DeleteExpression */: return visitNode(cbNode, node.expression); - case 166 /* TypeOfExpression */: + case 168 /* TypeOfExpression */: return visitNode(cbNode, node.expression); - case 167 /* VoidExpression */: + case 169 /* VoidExpression */: return visitNode(cbNode, node.expression); - case 168 /* PrefixUnaryExpression */: + case 170 /* PrefixUnaryExpression */: return visitNode(cbNode, node.operand); - case 173 /* YieldExpression */: + case 175 /* YieldExpression */: return visitNode(cbNode, node.asteriskToken) || visitNode(cbNode, node.expression); - case 169 /* PostfixUnaryExpression */: + case 171 /* PostfixUnaryExpression */: return visitNode(cbNode, node.operand); - case 170 /* BinaryExpression */: + case 172 /* BinaryExpression */: return visitNode(cbNode, node.left) || visitNode(cbNode, node.operatorToken) || visitNode(cbNode, node.right); - case 171 /* ConditionalExpression */: + case 173 /* ConditionalExpression */: return visitNode(cbNode, node.condition) || visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.whenTrue) || visitNode(cbNode, node.colonToken) || visitNode(cbNode, node.whenFalse); - case 174 /* SpreadElementExpression */: + case 176 /* SpreadElementExpression */: return visitNode(cbNode, node.expression); - case 180 /* Block */: - case 207 /* ModuleBlock */: + case 182 /* Block */: + case 209 /* ModuleBlock */: return visitNodes(cbNodes, node.statements); - case 228 /* SourceFile */: + case 230 /* SourceFile */: return visitNodes(cbNodes, node.statements) || visitNode(cbNode, node.endOfFileToken); - case 181 /* VariableStatement */: + case 183 /* VariableStatement */: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.declarationList); - case 200 /* VariableDeclarationList */: + case 202 /* VariableDeclarationList */: return visitNodes(cbNodes, node.declarations); - case 183 /* ExpressionStatement */: + case 185 /* ExpressionStatement */: return visitNode(cbNode, node.expression); - case 184 /* IfStatement */: + case 186 /* IfStatement */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.thenStatement) || visitNode(cbNode, node.elseStatement); - case 185 /* DoStatement */: + case 187 /* DoStatement */: return visitNode(cbNode, node.statement) || visitNode(cbNode, node.expression); - case 186 /* WhileStatement */: + case 188 /* WhileStatement */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.statement); - case 187 /* ForStatement */: + case 189 /* ForStatement */: return visitNode(cbNode, node.initializer) || visitNode(cbNode, node.condition) || visitNode(cbNode, node.incrementor) || visitNode(cbNode, node.statement); - case 188 /* ForInStatement */: + case 190 /* ForInStatement */: return visitNode(cbNode, node.initializer) || visitNode(cbNode, node.expression) || visitNode(cbNode, node.statement); - case 189 /* ForOfStatement */: + case 191 /* ForOfStatement */: return visitNode(cbNode, node.initializer) || visitNode(cbNode, node.expression) || visitNode(cbNode, node.statement); - case 190 /* ContinueStatement */: - case 191 /* BreakStatement */: + case 192 /* ContinueStatement */: + case 193 /* BreakStatement */: return visitNode(cbNode, node.label); - case 192 /* ReturnStatement */: + case 194 /* ReturnStatement */: return visitNode(cbNode, node.expression); - case 193 /* WithStatement */: + case 195 /* WithStatement */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.statement); - case 194 /* SwitchStatement */: + case 196 /* SwitchStatement */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.caseBlock); - case 208 /* CaseBlock */: + case 210 /* CaseBlock */: return visitNodes(cbNodes, node.clauses); - case 221 /* CaseClause */: + case 223 /* CaseClause */: return visitNode(cbNode, node.expression) || visitNodes(cbNodes, node.statements); - case 222 /* DefaultClause */: + case 224 /* DefaultClause */: return visitNodes(cbNodes, node.statements); - case 195 /* LabeledStatement */: + case 197 /* LabeledStatement */: return visitNode(cbNode, node.label) || visitNode(cbNode, node.statement); - case 196 /* ThrowStatement */: + case 198 /* ThrowStatement */: return visitNode(cbNode, node.expression); - case 197 /* TryStatement */: + case 199 /* TryStatement */: return visitNode(cbNode, node.tryBlock) || visitNode(cbNode, node.catchClause) || visitNode(cbNode, node.finallyBlock); - case 224 /* CatchClause */: + case 226 /* CatchClause */: return visitNode(cbNode, node.variableDeclaration) || visitNode(cbNode, node.block); - case 131 /* Decorator */: + case 132 /* Decorator */: return visitNode(cbNode, node.expression); - case 202 /* ClassDeclaration */: - case 175 /* ClassExpression */: + case 204 /* ClassDeclaration */: + case 177 /* 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 203 /* InterfaceDeclaration */: + case 205 /* 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 204 /* TypeAliasDeclaration */: + case 206 /* TypeAliasDeclaration */: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.name) || + visitNodes(cbNodes, node.typeParameters) || visitNode(cbNode, node.type); - case 205 /* EnumDeclaration */: + case 207 /* EnumDeclaration */: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNodes, node.members); - case 227 /* EnumMember */: + case 229 /* EnumMember */: return visitNode(cbNode, node.name) || visitNode(cbNode, node.initializer); - case 206 /* ModuleDeclaration */: + case 208 /* ModuleDeclaration */: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.body); - case 209 /* ImportEqualsDeclaration */: + case 211 /* ImportEqualsDeclaration */: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.moduleReference); - case 210 /* ImportDeclaration */: + case 212 /* ImportDeclaration */: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.importClause) || visitNode(cbNode, node.moduleSpecifier); - case 211 /* ImportClause */: + case 213 /* ImportClause */: return visitNode(cbNode, node.name) || visitNode(cbNode, node.namedBindings); - case 212 /* NamespaceImport */: + case 214 /* NamespaceImport */: return visitNode(cbNode, node.name); - case 213 /* NamedImports */: - case 217 /* NamedExports */: + case 215 /* NamedImports */: + case 219 /* NamedExports */: return visitNodes(cbNodes, node.elements); - case 216 /* ExportDeclaration */: + case 218 /* ExportDeclaration */: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.exportClause) || visitNode(cbNode, node.moduleSpecifier); - case 214 /* ImportSpecifier */: - case 218 /* ExportSpecifier */: + case 216 /* ImportSpecifier */: + case 220 /* ExportSpecifier */: return visitNode(cbNode, node.propertyName) || visitNode(cbNode, node.name); - case 215 /* ExportAssignment */: + case 217 /* ExportAssignment */: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.expression); - case 172 /* TemplateExpression */: + case 174 /* TemplateExpression */: return visitNode(cbNode, node.head) || visitNodes(cbNodes, node.templateSpans); - case 178 /* TemplateSpan */: + case 180 /* TemplateSpan */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.literal); - case 128 /* ComputedPropertyName */: + case 129 /* ComputedPropertyName */: return visitNode(cbNode, node.expression); - case 223 /* HeritageClause */: + case 225 /* HeritageClause */: return visitNodes(cbNodes, node.types); - case 177 /* ExpressionWithTypeArguments */: + case 179 /* ExpressionWithTypeArguments */: return visitNode(cbNode, node.expression) || visitNodes(cbNodes, node.typeArguments); - case 220 /* ExternalModuleReference */: + case 222 /* ExternalModuleReference */: return visitNode(cbNode, node.expression); - case 219 /* MissingDeclaration */: + case 221 /* MissingDeclaration */: return visitNodes(cbNodes, node.decorators); + case 231 /* JSDocTypeExpression */: + return visitNode(cbNode, node.type); + case 235 /* JSDocUnionType */: + return visitNodes(cbNodes, node.types); + case 236 /* JSDocTupleType */: + return visitNodes(cbNodes, node.types); + case 234 /* JSDocArrayType */: + return visitNode(cbNode, node.elementType); + case 238 /* JSDocNonNullableType */: + return visitNode(cbNode, node.type); + case 237 /* JSDocNullableType */: + return visitNode(cbNode, node.type); + case 239 /* JSDocRecordType */: + return visitNodes(cbNodes, node.members); + case 241 /* JSDocTypeReference */: + return visitNode(cbNode, node.name) || + visitNodes(cbNodes, node.typeArguments); + case 242 /* JSDocOptionalType */: + return visitNode(cbNode, node.type); + case 243 /* JSDocFunctionType */: + return visitNodes(cbNodes, node.parameters) || + visitNode(cbNode, node.type); + case 244 /* JSDocVariadicType */: + return visitNode(cbNode, node.type); + case 245 /* JSDocConstructorType */: + return visitNode(cbNode, node.type); + case 246 /* JSDocThisType */: + return visitNode(cbNode, node.type); + case 240 /* JSDocRecordMember */: + return visitNode(cbNode, node.name) || + visitNode(cbNode, node.type); + case 247 /* JSDocComment */: + return visitNodes(cbNodes, node.tags); + case 249 /* JSDocParameterTag */: + return visitNode(cbNode, node.preParameterName) || + visitNode(cbNode, node.typeExpression) || + visitNode(cbNode, node.postParameterName); + case 250 /* JSDocReturnTag */: + return visitNode(cbNode, node.typeExpression); + case 251 /* JSDocTypeTag */: + return visitNode(cbNode, node.typeExpression); + case 252 /* JSDocTemplateTag */: + return visitNodes(cbNodes, node.typeParameters); } } ts.forEachChild = forEachChild; @@ -6359,6 +7152,17 @@ var ts; return IncrementalParser.updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks); } ts.updateSourceFile = updateSourceFile; + /* @internal */ + function parseIsolatedJSDocComment(content, start, length) { + return Parser.JSDocParser.parseIsolatedJSDocComment(content, start, length); + } + 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. @@ -6369,6 +7173,7 @@ var ts; var scanner = ts.createScanner(2 /* Latest */, true); var disallowInAndDecoratorContext = 2 /* DisallowIn */ | 16 /* Decorator */; var sourceFile; + var parseDiagnostics; var syntaxCursor; var token; var sourceText; @@ -6422,7 +7227,7 @@ var ts; // 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 = 0; + 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: @@ -6452,44 +7257,89 @@ var ts; // attached to the EOF token. var parseErrorBeforeNextFinishedNode = false; function parseSourceFile(fileName, _sourceText, languageVersion, _syntaxCursor, setParentNodes) { + initializeState(fileName, _sourceText, languageVersion, _syntaxCursor); + var result = parseSourceFileWorker(fileName, languageVersion, setParentNodes); + clearState(); + return result; + } + Parser.parseSourceFile = parseSourceFile; + function initializeState(fileName, _sourceText, languageVersion, _syntaxCursor) { sourceText = _sourceText; syntaxCursor = _syntaxCursor; + parseDiagnostics = []; parsingContext = 0; identifiers = {}; identifierCount = 0; nodeCount = 0; - contextFlags = 0; + contextFlags = ts.isJavaScript(fileName) ? 64 /* JavaScriptFile */ : 0 /* None */; parseErrorBeforeNextFinishedNode = false; - createSourceFile(fileName, languageVersion); // Initialize and prime the scanner before parsing the source elements. scanner.setText(sourceText); scanner.setOnError(scanError); scanner.setScriptTarget(languageVersion); + } + 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 accidently hold onto it for too long. + parseDiagnostics = undefined; + sourceFile = undefined; + identifiers = undefined; + syntaxCursor = undefined; + sourceText = undefined; + } + function parseSourceFileWorker(fileName, languageVersion, setParentNodes) { + sourceFile = createSourceFile(fileName, languageVersion); + // Prime the scanner. token = nextToken(); processReferenceComments(sourceFile); - sourceFile.statements = parseList(0 /* SourceElements */, true, parseSourceElement); + 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); } - syntaxCursor = undefined; - // Clear out the text the scanner is pointing at, so it doesn't keep anything alive unnecessarily. - scanner.setText(""); - scanner.setOnError(undefined); - var result = sourceFile; - // Clear any data. We don't want to accidently hold onto it for too long. - sourceFile = undefined; - identifiers = undefined; - syntaxCursor = undefined; - sourceText = undefined; - return result; + // If this is a javascript file, proactively see if we can get JSDoc comments for + // relevant nodes in the file. We'll use these to provide typing informaion if they're + // available. + if (ts.isJavaScript(fileName)) { + addJSDocComments(); + } + return sourceFile; + } + function addJSDocComments() { + forEachChild(sourceFile, visit); + return; + function visit(node) { + // Add additional cases as necessary depending on how we see JSDoc comments used + // in the wild. + switch (node.kind) { + case 183 /* VariableStatement */: + case 203 /* FunctionDeclaration */: + case 131 /* Parameter */: + addJSDocComment(node); + } + forEachChild(node, visit); + } + } + function addJSDocComment(node) { + var comments = ts.getLeadingCommentRangesOfNode(node, sourceFile); + if (comments) { + for (var _i = 0; _i < comments.length; _i++) { + var comment = comments[_i]; + var jsDocComment = JSDocParser.parseJSDocComment(node, comment.pos, comment.end - comment.pos); + if (jsDocComment) { + node.jsDocComment = jsDocComment; + } + } + } } - Parser.parseSourceFile = parseSourceFile; function fixupParentReferences(sourceFile) { // 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 @@ -6511,16 +7361,17 @@ var ts; } } } + Parser.fixupParentReferences = fixupParentReferences; function createSourceFile(fileName, languageVersion) { - sourceFile = createNode(228 /* SourceFile */, 0); + var sourceFile = createNode(230 /* SourceFile */, 0); sourceFile.pos = 0; sourceFile.end = sourceText.length; sourceFile.text = sourceText; - sourceFile.parseDiagnostics = []; sourceFile.bindDiagnostics = []; sourceFile.languageVersion = languageVersion; sourceFile.fileName = ts.normalizePath(fileName); sourceFile.flags = ts.fileExtensionIs(sourceFile.fileName, ".d.ts") ? 2048 /* DeclarationFile */ : 0; + return sourceFile; } function setContextFlag(val, flag) { if (val) { @@ -6530,9 +7381,6 @@ var ts; contextFlags &= ~flag; } } - function setStrictModeContext(val) { - setContextFlag(val, 1 /* StrictMode */); - } function setDisallowInContext(val) { setContextFlag(val, 2 /* DisallowIn */); } @@ -6609,9 +7457,6 @@ var ts; function inYieldContext() { return (contextFlags & 4 /* Yield */) !== 0; } - function inStrictModeContext() { - return (contextFlags & 1 /* StrictMode */) !== 0; - } function inGeneratorParameterContext() { return (contextFlags & 8 /* GeneratorParameter */) !== 0; } @@ -6628,9 +7473,9 @@ var ts; } 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(sourceFile.parseDiagnostics); + var lastError = ts.lastOrUndefined(parseDiagnostics); if (!lastError || start !== lastError.start) { - sourceFile.parseDiagnostics.push(ts.createFileDiagnostic(sourceFile, start, length, message, arg0)); + 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. @@ -6665,7 +7510,7 @@ var ts; // 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 = token; - var saveParseDiagnosticsLength = sourceFile.parseDiagnostics.length; + 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/restorating of these flags happens naturally through the recursive @@ -6683,7 +7528,7 @@ var ts; // then unconditionally restore us to where we were. if (!result || isLookAhead) { token = saveToken; - sourceFile.parseDiagnostics.length = saveParseDiagnosticsLength; + parseDiagnostics.length = saveParseDiagnosticsLength; parseErrorBeforeNextFinishedNode = saveParseErrorBeforeNextFinishedNode; } return result; @@ -6779,8 +7624,8 @@ var ts; node.end = pos; return node; } - function finishNode(node) { - node.end = scanner.getStartPos(); + function finishNode(node, end) { + node.end = end === undefined ? scanner.getStartPos() : end; if (contextFlags) { node.parserContextFlags = contextFlags; } @@ -6836,15 +7681,24 @@ var ts; token === 8 /* StringLiteral */ || token === 7 /* NumericLiteral */; } - function parsePropertyName() { + function parsePropertyNameWorker(allowComputedPropertyNames) { if (token === 8 /* StringLiteral */ || token === 7 /* NumericLiteral */) { return parseLiteralNode(true); } - if (token === 18 /* OpenBracketToken */) { + if (allowComputedPropertyNames && token === 18 /* OpenBracketToken */) { return parseComputedPropertyName(); } return parseIdentifierName(); } + function parsePropertyName() { + return parsePropertyNameWorker(true); + } + function parseSimplePropertyName() { + return parsePropertyNameWorker(false); + } + function isSimplePropertyName() { + return token === 8 /* StringLiteral */ || token === 7 /* NumericLiteral */ || isIdentifierOrKeyword(); + } function parseComputedPropertyName() { // PropertyName[Yield,GeneratorParameter] : // LiteralPropertyName @@ -6854,7 +7708,7 @@ var ts; // ComputedPropertyName[Yield] : // [ AssignmentExpression[In, ?Yield] ] // - var node = createNode(128 /* ComputedPropertyName */); + var node = createNode(129 /* ComputedPropertyName */); parseExpected(18 /* OpenBracketToken */); // We parse any expression (including a comma expression). But the grammar // says that only an assignment expression is allowed, so the grammar checker @@ -6912,30 +7766,34 @@ var ts; } switch (parsingContext) { case 0 /* SourceElements */: - case 1 /* ModuleElements */: - return isSourceElement(inErrorRecovery); - case 2 /* BlockStatements */: - case 4 /* SwitchClauseStatements */: - return isStartOfStatement(inErrorRecovery); - case 3 /* SwitchClauses */: + 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 === 22 /* SemicolonToken */ && inErrorRecovery) && isStartOfStatement(); + case 2 /* SwitchClauses */: return token === 67 /* CaseKeyword */ || token === 73 /* DefaultKeyword */; - case 5 /* TypeMembers */: + case 4 /* TypeMembers */: return isStartOfTypeMember(); - case 6 /* ClassMembers */: + 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 === 22 /* SemicolonToken */ && !inErrorRecovery); - case 7 /* EnumMembers */: + 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 === 18 /* OpenBracketToken */ || isLiteralPropertyName(); - case 13 /* ObjectLiteralMembers */: + case 12 /* ObjectLiteralMembers */: return token === 18 /* OpenBracketToken */ || token === 35 /* AsteriskToken */ || isLiteralPropertyName(); - case 10 /* ObjectBindingElements */: + case 9 /* ObjectBindingElements */: return isLiteralPropertyName(); - case 8 /* HeritageClauseElement */: + 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 === 14 /* OpenBraceToken */) { @@ -6950,24 +7808,30 @@ var ts; // element during recovery. return isIdentifier() && !isHeritageClauseExtendsOrImplementsKeyword(); } - case 9 /* VariableDeclarations */: + case 8 /* VariableDeclarations */: return isIdentifierOrPattern(); - case 11 /* ArrayBindingElements */: + case 10 /* ArrayBindingElements */: return token === 23 /* CommaToken */ || token === 21 /* DotDotDotToken */ || isIdentifierOrPattern(); - case 16 /* TypeParameters */: + case 15 /* TypeParameters */: return isIdentifier(); - case 12 /* ArgumentExpressions */: - case 14 /* ArrayLiteralMembers */: + case 11 /* ArgumentExpressions */: + case 13 /* ArrayLiteralMembers */: return token === 23 /* CommaToken */ || token === 21 /* DotDotDotToken */ || isStartOfExpression(); - case 15 /* Parameters */: + case 14 /* Parameters */: return isStartOfParameter(); - case 17 /* TypeArguments */: - case 18 /* TupleElementTypes */: + case 16 /* TypeArguments */: + case 17 /* TupleElementTypes */: return token === 23 /* CommaToken */ || isStartOfType(); - case 19 /* HeritageClauses */: + case 18 /* HeritageClauses */: return isHeritageClause(); - case 20 /* ImportOrExportSpecifiers */: + case 19 /* ImportOrExportSpecifiers */: return isIdentifierOrKeyword(); + case 20 /* JSDocFunctionParameters */: + case 21 /* JSDocTypeArguments */: + case 23 /* JSDocTupleTypes */: + return JSDocParser.isJSDocType(); + case 22 /* JSDocRecordMembers */: + return isSimplePropertyName(); } ts.Debug.fail("Non-exhaustive case in 'isListElement'."); } @@ -7008,40 +7872,47 @@ var ts; return true; } switch (kind) { - case 1 /* ModuleElements */: - case 2 /* BlockStatements */: - case 3 /* SwitchClauses */: - case 5 /* TypeMembers */: - case 6 /* ClassMembers */: - case 7 /* EnumMembers */: - case 13 /* ObjectLiteralMembers */: - case 10 /* ObjectBindingElements */: - case 20 /* ImportOrExportSpecifiers */: + case 1 /* BlockStatements */: + case 2 /* SwitchClauses */: + case 4 /* TypeMembers */: + case 5 /* ClassMembers */: + case 6 /* EnumMembers */: + case 12 /* ObjectLiteralMembers */: + case 9 /* ObjectBindingElements */: + case 19 /* ImportOrExportSpecifiers */: return token === 15 /* CloseBraceToken */; - case 4 /* SwitchClauseStatements */: + case 3 /* SwitchClauseStatements */: return token === 15 /* CloseBraceToken */ || token === 67 /* CaseKeyword */ || token === 73 /* DefaultKeyword */; - case 8 /* HeritageClauseElement */: + case 7 /* HeritageClauseElement */: return token === 14 /* OpenBraceToken */ || token === 79 /* ExtendsKeyword */ || token === 102 /* ImplementsKeyword */; - case 9 /* VariableDeclarations */: + case 8 /* VariableDeclarations */: return isVariableDeclaratorListTerminator(); - case 16 /* TypeParameters */: + case 15 /* TypeParameters */: // Tokens other than '>' are here for better error recovery return token === 25 /* GreaterThanToken */ || token === 16 /* OpenParenToken */ || token === 14 /* OpenBraceToken */ || token === 79 /* ExtendsKeyword */ || token === 102 /* ImplementsKeyword */; - case 12 /* ArgumentExpressions */: + case 11 /* ArgumentExpressions */: // Tokens other than ')' are here for better error recovery return token === 17 /* CloseParenToken */ || token === 22 /* SemicolonToken */; - case 14 /* ArrayLiteralMembers */: - case 18 /* TupleElementTypes */: - case 11 /* ArrayBindingElements */: + case 13 /* ArrayLiteralMembers */: + case 17 /* TupleElementTypes */: + case 10 /* ArrayBindingElements */: return token === 19 /* CloseBracketToken */; - case 15 /* Parameters */: + case 14 /* Parameters */: // Tokens other than ')' and ']' (the latter for index signatures) are here for better error recovery return token === 17 /* CloseParenToken */ || token === 19 /* CloseBracketToken */ /*|| token === SyntaxKind.OpenBraceToken*/; - case 17 /* TypeArguments */: + case 16 /* TypeArguments */: // Tokens other than '>' are here for better error recovery return token === 25 /* GreaterThanToken */ || token === 16 /* OpenParenToken */; - case 19 /* HeritageClauses */: + case 18 /* HeritageClauses */: return token === 14 /* OpenBraceToken */ || token === 15 /* CloseBraceToken */; + case 20 /* JSDocFunctionParameters */: + return token === 17 /* CloseParenToken */ || token === 51 /* ColonToken */ || token === 15 /* CloseBraceToken */; + case 21 /* JSDocTypeArguments */: + return token === 25 /* GreaterThanToken */ || token === 15 /* CloseBraceToken */; + case 23 /* JSDocTupleTypes */: + return token === 19 /* CloseBracketToken */ || token === 15 /* CloseBraceToken */; + case 22 /* JSDocRecordMembers */: + return token === 15 /* CloseBraceToken */; } } function isVariableDeclaratorListTerminator() { @@ -7067,7 +7938,7 @@ var ts; } // True if positioned at element or terminator of the current list or any enclosing list function isInSomeParsingContext() { - for (var kind = 0; kind < 21 /* Count */; kind++) { + for (var kind = 0; kind < 24 /* Count */; kind++) { if (parsingContext & (1 << kind)) { if (isListElement(kind, true) || isListTerminator(kind)) { return true; @@ -7077,47 +7948,25 @@ var ts; return false; } // Parses a list of elements - function parseList(kind, checkForStrictMode, parseElement) { + function parseList(kind, parseElement) { var saveParsingContext = parsingContext; parsingContext |= 1 << kind; var result = []; result.pos = getNodePos(); - var savedStrictModeContext = inStrictModeContext(); while (!isListTerminator(kind)) { if (isListElement(kind, false)) { var element = parseListElement(kind, parseElement); result.push(element); - // test elements only if we are not already in strict mode - if (checkForStrictMode && !inStrictModeContext()) { - if (ts.isPrologueDirective(element)) { - if (isUseStrictPrologueDirective(sourceFile, element)) { - setStrictModeContext(true); - checkForStrictMode = false; - } - } - else { - checkForStrictMode = false; - } - } continue; } if (abortParsingListOrMoveToNextToken(kind)) { break; } } - setStrictModeContext(savedStrictModeContext); result.end = getNodeEnd(); parsingContext = saveParsingContext; return result; } - /// Should be called only on prologue directives (isPrologueDirective(node) should be true) - function isUseStrictPrologueDirective(sourceFile, node) { - ts.Debug.assert(ts.isPrologueDirective(node)); - var nodeText = ts.getSourceTextOfNodeFromSourceFile(sourceFile, 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 parseListElement(parsingContext, parseElement) { var node = currentNode(parsingContext); if (node) { @@ -7165,7 +8014,7 @@ var ts; // differently depending on what mode it is in. // // This also applies to all our other context flags as well. - var nodeContextFlags = node.parserContextFlags & 63 /* ParserGeneratedFlags */; + var nodeContextFlags = node.parserContextFlags & 62 /* ParserGeneratedFlags */; if (nodeContextFlags !== contextFlags) { return undefined; } @@ -7184,37 +8033,36 @@ var ts; } function canReuseNode(node, parsingContext) { switch (parsingContext) { - case 1 /* ModuleElements */: - return isReusableModuleElement(node); - case 6 /* ClassMembers */: + case 5 /* ClassMembers */: return isReusableClassMember(node); - case 3 /* SwitchClauses */: + case 2 /* SwitchClauses */: return isReusableSwitchClause(node); - case 2 /* BlockStatements */: - case 4 /* SwitchClauseStatements */: + case 0 /* SourceElements */: + case 1 /* BlockStatements */: + case 3 /* SwitchClauseStatements */: return isReusableStatement(node); - case 7 /* EnumMembers */: + case 6 /* EnumMembers */: return isReusableEnumMember(node); - case 5 /* TypeMembers */: + case 4 /* TypeMembers */: return isReusableTypeMember(node); - case 9 /* VariableDeclarations */: + case 8 /* VariableDeclarations */: return isReusableVariableDeclaration(node); - case 15 /* Parameters */: + case 14 /* Parameters */: return isReusableParameter(node); // 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 19 /* HeritageClauses */: + case 18 /* HeritageClauses */: // This would probably be safe to reuse. There is no speculative parsing with // heritage clauses. - case 16 /* TypeParameters */: + case 15 /* 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 18 /* TupleElementTypes */: + case 17 /* 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 @@ -7222,51 +8070,41 @@ var ts; // 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 17 /* TypeArguments */: + case 16 /* 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 12 /* ArgumentExpressions */: + 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 13 /* ObjectLiteralMembers */: + 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 8 /* HeritageClauseElement */: - } - return false; - } - function isReusableModuleElement(node) { - if (node) { - switch (node.kind) { - case 210 /* ImportDeclaration */: - case 209 /* ImportEqualsDeclaration */: - case 216 /* ExportDeclaration */: - case 215 /* ExportAssignment */: - case 202 /* ClassDeclaration */: - case 203 /* InterfaceDeclaration */: - case 206 /* ModuleDeclaration */: - case 205 /* EnumDeclaration */: - return true; - } - return isReusableStatement(node); + case 7 /* HeritageClauseElement */: } return false; } function isReusableClassMember(node) { if (node) { switch (node.kind) { - case 136 /* Constructor */: - case 141 /* IndexSignature */: - case 135 /* MethodDeclaration */: - case 137 /* GetAccessor */: - case 138 /* SetAccessor */: - case 133 /* PropertyDeclaration */: - case 179 /* SemicolonClassElement */: + case 137 /* Constructor */: + case 142 /* IndexSignature */: + case 138 /* GetAccessor */: + case 139 /* SetAccessor */: + case 134 /* PropertyDeclaration */: + case 181 /* SemicolonClassElement */: return true; + case 136 /* 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 === 65 /* Identifier */ && + methodDeclaration.name.originalKeywordKind === 114 /* ConstructorKeyword */; + return !nameIsConstructor; } } return false; @@ -7274,8 +8112,8 @@ var ts; function isReusableSwitchClause(node) { if (node) { switch (node.kind) { - case 221 /* CaseClause */: - case 222 /* DefaultClause */: + case 223 /* CaseClause */: + case 224 /* DefaultClause */: return true; } } @@ -7284,49 +8122,58 @@ var ts; function isReusableStatement(node) { if (node) { switch (node.kind) { - case 201 /* FunctionDeclaration */: - case 181 /* VariableStatement */: - case 180 /* Block */: - case 184 /* IfStatement */: - case 183 /* ExpressionStatement */: - case 196 /* ThrowStatement */: - case 192 /* ReturnStatement */: - case 194 /* SwitchStatement */: - case 191 /* BreakStatement */: - case 190 /* ContinueStatement */: - case 188 /* ForInStatement */: - case 189 /* ForOfStatement */: - case 187 /* ForStatement */: - case 186 /* WhileStatement */: - case 193 /* WithStatement */: - case 182 /* EmptyStatement */: - case 197 /* TryStatement */: - case 195 /* LabeledStatement */: - case 185 /* DoStatement */: - case 198 /* DebuggerStatement */: + case 203 /* FunctionDeclaration */: + case 183 /* VariableStatement */: + case 182 /* Block */: + case 186 /* IfStatement */: + case 185 /* ExpressionStatement */: + case 198 /* ThrowStatement */: + case 194 /* ReturnStatement */: + case 196 /* SwitchStatement */: + case 193 /* BreakStatement */: + case 192 /* ContinueStatement */: + case 190 /* ForInStatement */: + case 191 /* ForOfStatement */: + case 189 /* ForStatement */: + case 188 /* WhileStatement */: + case 195 /* WithStatement */: + case 184 /* EmptyStatement */: + case 199 /* TryStatement */: + case 197 /* LabeledStatement */: + case 187 /* DoStatement */: + case 200 /* DebuggerStatement */: + case 212 /* ImportDeclaration */: + case 211 /* ImportEqualsDeclaration */: + case 218 /* ExportDeclaration */: + case 217 /* ExportAssignment */: + case 208 /* ModuleDeclaration */: + case 204 /* ClassDeclaration */: + case 205 /* InterfaceDeclaration */: + case 207 /* EnumDeclaration */: + case 206 /* TypeAliasDeclaration */: return true; } } return false; } function isReusableEnumMember(node) { - return node.kind === 227 /* EnumMember */; + return node.kind === 229 /* EnumMember */; } function isReusableTypeMember(node) { if (node) { switch (node.kind) { - case 140 /* ConstructSignature */: - case 134 /* MethodSignature */: - case 141 /* IndexSignature */: - case 132 /* PropertySignature */: - case 139 /* CallSignature */: + case 141 /* ConstructSignature */: + case 135 /* MethodSignature */: + case 142 /* IndexSignature */: + case 133 /* PropertySignature */: + case 140 /* CallSignature */: return true; } } return false; } function isReusableVariableDeclaration(node) { - if (node.kind !== 199 /* VariableDeclaration */) { + if (node.kind !== 201 /* VariableDeclaration */) { return false; } // Very subtle incremental parsing bug. Consider the following code: @@ -7347,7 +8194,7 @@ var ts; return variableDeclarator.initializer === undefined; } function isReusableParameter(node) { - if (node.kind !== 130 /* Parameter */) { + if (node.kind !== 131 /* Parameter */) { return false; } // See the comment in isReusableVariableDeclaration for why we do this. @@ -7366,26 +8213,29 @@ var ts; function parsingContextErrors(context) { switch (context) { case 0 /* SourceElements */: return ts.Diagnostics.Declaration_or_statement_expected; - case 1 /* ModuleElements */: return ts.Diagnostics.Declaration_or_statement_expected; - case 2 /* BlockStatements */: return ts.Diagnostics.Statement_expected; - case 3 /* SwitchClauses */: return ts.Diagnostics.case_or_default_expected; - case 4 /* SwitchClauseStatements */: return ts.Diagnostics.Statement_expected; - case 5 /* TypeMembers */: return ts.Diagnostics.Property_or_signature_expected; - case 6 /* ClassMembers */: return ts.Diagnostics.Unexpected_token_A_constructor_method_accessor_or_property_was_expected; - case 7 /* EnumMembers */: return ts.Diagnostics.Enum_member_expected; - case 8 /* HeritageClauseElement */: return ts.Diagnostics.Expression_expected; - case 9 /* VariableDeclarations */: return ts.Diagnostics.Variable_declaration_expected; - case 10 /* ObjectBindingElements */: return ts.Diagnostics.Property_destructuring_pattern_expected; - case 11 /* ArrayBindingElements */: return ts.Diagnostics.Array_element_destructuring_pattern_expected; - case 12 /* ArgumentExpressions */: return ts.Diagnostics.Argument_expression_expected; - case 13 /* ObjectLiteralMembers */: return ts.Diagnostics.Property_assignment_expected; - case 14 /* ArrayLiteralMembers */: return ts.Diagnostics.Expression_or_comma_expected; - case 15 /* Parameters */: return ts.Diagnostics.Parameter_declaration_expected; - case 16 /* TypeParameters */: return ts.Diagnostics.Type_parameter_declaration_expected; - case 17 /* TypeArguments */: return ts.Diagnostics.Type_argument_expected; - case 18 /* TupleElementTypes */: return ts.Diagnostics.Type_expected; - case 19 /* HeritageClauses */: return ts.Diagnostics.Unexpected_token_expected; - case 20 /* ImportOrExportSpecifiers */: return ts.Diagnostics.Identifier_expected; + case 1 /* BlockStatements */: return ts.Diagnostics.Declaration_or_statement_expected; + case 2 /* SwitchClauses */: return ts.Diagnostics.case_or_default_expected; + case 3 /* SwitchClauseStatements */: return ts.Diagnostics.Statement_expected; + case 4 /* TypeMembers */: return ts.Diagnostics.Property_or_signature_expected; + case 5 /* ClassMembers */: return ts.Diagnostics.Unexpected_token_A_constructor_method_accessor_or_property_was_expected; + case 6 /* EnumMembers */: return ts.Diagnostics.Enum_member_expected; + case 7 /* HeritageClauseElement */: return ts.Diagnostics.Expression_expected; + case 8 /* VariableDeclarations */: return ts.Diagnostics.Variable_declaration_expected; + case 9 /* ObjectBindingElements */: return ts.Diagnostics.Property_destructuring_pattern_expected; + case 10 /* ArrayBindingElements */: return ts.Diagnostics.Array_element_destructuring_pattern_expected; + case 11 /* ArgumentExpressions */: return ts.Diagnostics.Argument_expression_expected; + case 12 /* ObjectLiteralMembers */: return ts.Diagnostics.Property_assignment_expected; + case 13 /* ArrayLiteralMembers */: return ts.Diagnostics.Expression_or_comma_expected; + case 14 /* Parameters */: return ts.Diagnostics.Parameter_declaration_expected; + case 15 /* TypeParameters */: return ts.Diagnostics.Type_parameter_declaration_expected; + case 16 /* TypeArguments */: return ts.Diagnostics.Type_argument_expected; + case 17 /* TupleElementTypes */: return ts.Diagnostics.Type_expected; + case 18 /* HeritageClauses */: return ts.Diagnostics.Unexpected_token_expected; + case 19 /* ImportOrExportSpecifiers */: return ts.Diagnostics.Identifier_expected; + case 20 /* JSDocFunctionParameters */: return ts.Diagnostics.Parameter_declaration_expected; + case 21 /* JSDocTypeArguments */: return ts.Diagnostics.Type_argument_expected; + case 23 /* JSDocTupleTypes */: return ts.Diagnostics.Type_expected; + case 22 /* JSDocRecordMembers */: return ts.Diagnostics.Property_assignment_expected; } } ; @@ -7459,7 +8309,7 @@ var ts; function parseEntityName(allowReservedWords, diagnosticMessage) { var entity = parseIdentifier(diagnosticMessage); while (parseOptional(20 /* DotToken */)) { - var node = createNode(127 /* QualifiedName */, entity.pos); + var node = createNode(128 /* QualifiedName */, entity.pos); node.left = entity; node.right = parseRightSideOfDot(allowReservedWords); entity = finishNode(node); @@ -7467,38 +8317,38 @@ var ts; return entity; } function parseRightSideOfDot(allowIdentifierNames) { - // Technically a keyword is valid here as all keywords are identifier names. - // However, often we'll encounter this in error situations when the keyword + // 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. - // keyword identifierNameOrKeyword + // identifierOrKeyword identifierNameOrKeyword // // Note: the newlines are important here. For example, if that above code // were rewritten into: // - // name.keyword + // name.identifierOrKeyword // identifierNameOrKeyword // // Then we would consider it valid. That's because ASI would take effect and - // the code would be implicitly: "name.keyword; identifierNameOrKeyword". + // 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 keyword. - if (scanner.hasPrecedingLineBreak() && scanner.isReservedWord()) { + // line terminator after the identifier or keyword. + if (scanner.hasPrecedingLineBreak() && isIdentifierOrKeyword()) { 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 woudl be quite confusing. + // be an identifier and the error would be quite confusing. return createMissingNode(65 /* Identifier */, true, ts.Diagnostics.Identifier_expected); } } return allowIdentifierNames ? parseIdentifierName() : parseIdentifier(); } function parseTemplateExpression() { - var template = createNode(172 /* TemplateExpression */); + var template = createNode(174 /* TemplateExpression */); template.head = parseLiteralNode(); ts.Debug.assert(template.head.kind === 11 /* TemplateHead */, "Template head has wrong token kind"); var templateSpans = []; @@ -7511,7 +8361,7 @@ var ts; return finishNode(template); } function parseTemplateSpan() { - var span = createNode(178 /* TemplateSpan */); + var span = createNode(180 /* TemplateSpan */); span.expression = allowInAnd(parseExpression); var literal; if (token === 15 /* CloseBraceToken */) { @@ -7551,22 +8401,30 @@ var ts; return node; } // TYPES - function parseTypeReference() { - var node = createNode(142 /* TypeReference */); - node.typeName = parseEntityName(false, ts.Diagnostics.Type_expected); + function parseTypeReferenceOrTypePredicate() { + var typeName = parseEntityName(false, ts.Diagnostics.Type_expected); + if (typeName.kind === 65 /* Identifier */ && token === 117 /* IsKeyword */ && !scanner.hasPrecedingLineBreak()) { + nextToken(); + var node_1 = createNode(143 /* TypePredicate */, typeName.pos); + node_1.parameterName = typeName; + node_1.type = parseType(); + return finishNode(node_1); + } + var node = createNode(144 /* TypeReference */, typeName.pos); + node.typeName = typeName; if (!scanner.hasPrecedingLineBreak() && token === 24 /* LessThanToken */) { - node.typeArguments = parseBracketedList(17 /* TypeArguments */, parseType, 24 /* LessThanToken */, 25 /* GreaterThanToken */); + node.typeArguments = parseBracketedList(16 /* TypeArguments */, parseType, 24 /* LessThanToken */, 25 /* GreaterThanToken */); } return finishNode(node); } function parseTypeQuery() { - var node = createNode(145 /* TypeQuery */); + var node = createNode(147 /* TypeQuery */); parseExpected(97 /* TypeOfKeyword */); node.exprName = parseEntityName(true); return finishNode(node); } function parseTypeParameter() { - var node = createNode(129 /* TypeParameter */); + var node = createNode(130 /* TypeParameter */); node.name = parseIdentifier(); if (parseOptional(79 /* ExtendsKeyword */)) { // It's not uncommon for people to write improper constraints to a generic. If the @@ -7591,7 +8449,7 @@ var ts; } function parseTypeParameters() { if (token === 24 /* LessThanToken */) { - return parseBracketedList(16 /* TypeParameters */, parseTypeParameter, 24 /* LessThanToken */, 25 /* GreaterThanToken */); + return parseBracketedList(15 /* TypeParameters */, parseTypeParameter, 24 /* LessThanToken */, 25 /* GreaterThanToken */); } } function parseParameterType() { @@ -7612,7 +8470,7 @@ var ts; } } function parseParameter() { - var node = createNode(130 /* Parameter */); + var node = createNode(131 /* Parameter */); node.decorators = parseDecorators(); setModifiers(node, parseModifiers()); node.dotDotDotToken = parseOptionalToken(21 /* DotDotDotToken */); @@ -7683,7 +8541,7 @@ var ts; var savedGeneratorParameterContext = inGeneratorParameterContext(); setYieldContext(yieldAndGeneratorParameterContext); setGeneratorParameterContext(yieldAndGeneratorParameterContext); - var result = parseDelimitedList(15 /* Parameters */, parseParameter); + var result = parseDelimitedList(14 /* Parameters */, parseParameter); setYieldContext(savedYieldContext); setGeneratorParameterContext(savedGeneratorParameterContext); if (!parseExpected(17 /* CloseParenToken */) && requireCompleteParameterList) { @@ -7709,7 +8567,7 @@ var ts; } function parseSignatureMember(kind) { var node = createNode(kind); - if (kind === 140 /* ConstructSignature */) { + if (kind === 141 /* ConstructSignature */) { parseExpected(88 /* NewKeyword */); } fillSignature(51 /* ColonToken */, false, false, node); @@ -7773,10 +8631,10 @@ var ts; return token === 51 /* ColonToken */ || token === 23 /* CommaToken */ || token === 19 /* CloseBracketToken */; } function parseIndexSignatureDeclaration(fullStart, decorators, modifiers) { - var node = createNode(141 /* IndexSignature */, fullStart); + var node = createNode(142 /* IndexSignature */, fullStart); node.decorators = decorators; setModifiers(node, modifiers); - node.parameters = parseBracketedList(15 /* Parameters */, parseParameter, 18 /* OpenBracketToken */, 19 /* CloseBracketToken */); + node.parameters = parseBracketedList(14 /* Parameters */, parseParameter, 18 /* OpenBracketToken */, 19 /* CloseBracketToken */); node.type = parseTypeAnnotation(); parseTypeMemberSemicolon(); return finishNode(node); @@ -7786,7 +8644,7 @@ var ts; var name = parsePropertyName(); var questionToken = parseOptionalToken(50 /* QuestionToken */); if (token === 16 /* OpenParenToken */ || token === 24 /* LessThanToken */) { - var method = createNode(134 /* MethodSignature */, fullStart); + var method = createNode(135 /* MethodSignature */, fullStart); method.name = name; method.questionToken = questionToken; // Method signatues don't exist in expression contexts. So they have neither @@ -7796,7 +8654,7 @@ var ts; return finishNode(method); } else { - var property = createNode(132 /* PropertySignature */, fullStart); + var property = createNode(133 /* PropertySignature */, fullStart); property.name = name; property.questionToken = questionToken; property.type = parseTypeAnnotation(); @@ -7838,7 +8696,7 @@ var ts; switch (token) { case 16 /* OpenParenToken */: case 24 /* LessThanToken */: - return parseSignatureMember(139 /* CallSignature */); + return parseSignatureMember(140 /* CallSignature */); case 18 /* OpenBracketToken */: // Indexer or computed property return isIndexSignature() @@ -7846,7 +8704,7 @@ var ts; : parsePropertyOrMethodSignature(); case 88 /* NewKeyword */: if (lookAhead(isStartOfConstructSignature)) { - return parseSignatureMember(140 /* ConstructSignature */); + return parseSignatureMember(141 /* ConstructSignature */); } // fall through. case 8 /* StringLiteral */: @@ -7883,14 +8741,14 @@ var ts; return token === 16 /* OpenParenToken */ || token === 24 /* LessThanToken */; } function parseTypeLiteral() { - var node = createNode(146 /* TypeLiteral */); + var node = createNode(148 /* TypeLiteral */); node.members = parseObjectTypeMembers(); return finishNode(node); } function parseObjectTypeMembers() { var members; if (parseExpected(14 /* OpenBraceToken */)) { - members = parseList(5 /* TypeMembers */, false, parseTypeMember); + members = parseList(4 /* TypeMembers */, parseTypeMember); parseExpected(15 /* CloseBraceToken */); } else { @@ -7899,12 +8757,12 @@ var ts; return members; } function parseTupleType() { - var node = createNode(148 /* TupleType */); - node.elementTypes = parseBracketedList(18 /* TupleElementTypes */, parseType, 18 /* OpenBracketToken */, 19 /* CloseBracketToken */); + var node = createNode(150 /* TupleType */); + node.elementTypes = parseBracketedList(17 /* TupleElementTypes */, parseType, 18 /* OpenBracketToken */, 19 /* CloseBracketToken */); return finishNode(node); } function parseParenthesizedType() { - var node = createNode(150 /* ParenthesizedType */); + var node = createNode(152 /* ParenthesizedType */); parseExpected(16 /* OpenParenToken */); node.type = parseType(); parseExpected(17 /* CloseParenToken */); @@ -7912,7 +8770,7 @@ var ts; } function parseFunctionOrConstructorType(kind) { var node = createNode(kind); - if (kind === 144 /* ConstructorType */) { + if (kind === 146 /* ConstructorType */) { parseExpected(88 /* NewKeyword */); } fillSignature(32 /* EqualsGreaterThanToken */, false, false, node); @@ -7925,13 +8783,13 @@ var ts; function parseNonArrayType() { switch (token) { case 112 /* AnyKeyword */: - case 122 /* StringKeyword */: - case 120 /* NumberKeyword */: + case 123 /* StringKeyword */: + case 121 /* NumberKeyword */: case 113 /* BooleanKeyword */: - case 123 /* SymbolKeyword */: + case 124 /* SymbolKeyword */: // If these are followed by a dot, then parse these out as a dotted type reference instead. var node = tryParse(parseKeywordAndNoDot); - return node || parseTypeReference(); + return node || parseTypeReferenceOrTypePredicate(); case 99 /* VoidKeyword */: return parseTokenNode(); case 97 /* TypeOfKeyword */: @@ -7943,16 +8801,16 @@ var ts; case 16 /* OpenParenToken */: return parseParenthesizedType(); default: - return parseTypeReference(); + return parseTypeReferenceOrTypePredicate(); } } function isStartOfType() { switch (token) { case 112 /* AnyKeyword */: - case 122 /* StringKeyword */: - case 120 /* NumberKeyword */: + case 123 /* StringKeyword */: + case 121 /* NumberKeyword */: case 113 /* BooleanKeyword */: - case 123 /* SymbolKeyword */: + case 124 /* SymbolKeyword */: case 99 /* VoidKeyword */: case 97 /* TypeOfKeyword */: case 14 /* OpenBraceToken */: @@ -7976,7 +8834,7 @@ var ts; var type = parseNonArrayType(); while (!scanner.hasPrecedingLineBreak() && parseOptional(18 /* OpenBracketToken */)) { parseExpected(19 /* CloseBracketToken */); - var node = createNode(147 /* ArrayType */, type.pos); + var node = createNode(149 /* ArrayType */, type.pos); node.elementType = type; type = finishNode(node); } @@ -7991,7 +8849,7 @@ var ts; types.push(parseArrayTypeOrHigher()); } types.end = getNodeEnd(); - var node = createNode(149 /* UnionType */, type.pos); + var node = createNode(151 /* UnionType */, type.pos); node.types = types; type = finishNode(node); } @@ -8046,10 +8904,10 @@ var ts; } function parseTypeWorker() { if (isStartOfFunctionType()) { - return parseFunctionOrConstructorType(143 /* FunctionType */); + return parseFunctionOrConstructorType(145 /* FunctionType */); } if (token === 88 /* NewKeyword */) { - return parseFunctionOrConstructorType(144 /* ConstructorType */); + return parseFunctionOrConstructorType(146 /* ConstructorType */); } return parseUnionTypeOrHigher(); } @@ -8218,11 +9076,6 @@ var ts; if (inYieldContext()) { return true; } - if (inStrictModeContext()) { - // If we're in strict mode, then 'yield' is a keyword, could only ever start - // a yield expression. - 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 @@ -8237,7 +9090,7 @@ var ts; // 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 accidently consume something legal. - return lookAhead(nextTokenIsIdentifierOnSameLine); + return lookAhead(nextTokenIsIdentifierOrKeywordOrNumberOnSameLine); } return false; } @@ -8245,13 +9098,8 @@ var ts; nextToken(); return !scanner.hasPrecedingLineBreak() && isIdentifier(); } - function nextTokenIsIdentifierOrStartOfDestructuringOnTheSameLine() { - nextToken(); - return !scanner.hasPrecedingLineBreak() && - (isIdentifier() || token === 14 /* OpenBraceToken */ || token === 18 /* OpenBracketToken */); - } function parseYieldExpression() { - var node = createNode(173 /* YieldExpression */); + var node = createNode(175 /* YieldExpression */); // YieldExpression[In] : // yield // yield [no LineTerminator here] [Lexical goal InputElementRegExp]AssignmentExpression[?In, Yield] @@ -8271,8 +9119,8 @@ var ts; } function parseSimpleArrowFunctionExpression(identifier) { ts.Debug.assert(token === 32 /* EqualsGreaterThanToken */, "parseSimpleArrowFunctionExpression should only have been called if we had a =>"); - var node = createNode(164 /* ArrowFunction */, identifier.pos); - var parameter = createNode(130 /* Parameter */, identifier.pos); + var node = createNode(166 /* ArrowFunction */, identifier.pos); + var parameter = createNode(131 /* Parameter */, identifier.pos); parameter.name = identifier; finishNode(parameter); node.parameters = [parameter]; @@ -8390,7 +9238,7 @@ var ts; return parseParenthesizedArrowFunctionExpressionHead(false); } function parseParenthesizedArrowFunctionExpressionHead(allowAmbiguity) { - var node = createNode(164 /* ArrowFunction */); + var node = createNode(166 /* ArrowFunction */); // Arrow functions are never generators. // // If we're speculatively parsing a signature for a parenthesized arrow function, then @@ -8421,10 +9269,11 @@ var ts; if (token === 14 /* OpenBraceToken */) { return parseFunctionBlock(false, false); } - if (isStartOfStatement(true) && - !isStartOfExpressionStatement() && + if (token !== 22 /* SemicolonToken */ && token !== 83 /* FunctionKeyword */ && - token !== 69 /* ClassKeyword */) { + token !== 69 /* 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 @@ -8451,7 +9300,7 @@ var ts; } // Note: we explicitly 'allowIn' in the whenTrue part of the condition expression, and // we do not that for the 'whenFalse' part. - var node = createNode(171 /* ConditionalExpression */, leftOperand.pos); + var node = createNode(173 /* ConditionalExpression */, leftOperand.pos); node.condition = leftOperand; node.questionToken = questionToken; node.whenTrue = doOutsideOfContext(disallowInAndDecoratorContext, parseAssignmentExpressionOrHigher); @@ -8464,7 +9313,7 @@ var ts; return parseBinaryExpressionRest(precedence, leftOperand); } function isInOrOfKeyword(t) { - return t === 86 /* InKeyword */ || t === 126 /* OfKeyword */; + return t === 86 /* InKeyword */ || t === 127 /* OfKeyword */; } function parseBinaryExpressionRest(precedence, leftOperand) { while (true) { @@ -8530,33 +9379,33 @@ var ts; return -1; } function makeBinaryExpression(left, operatorToken, right) { - var node = createNode(170 /* BinaryExpression */, left.pos); + var node = createNode(172 /* BinaryExpression */, left.pos); node.left = left; node.operatorToken = operatorToken; node.right = right; return finishNode(node); } function parsePrefixUnaryExpression() { - var node = createNode(168 /* PrefixUnaryExpression */); + var node = createNode(170 /* PrefixUnaryExpression */); node.operator = token; nextToken(); node.operand = parseUnaryExpressionOrHigher(); return finishNode(node); } function parseDeleteExpression() { - var node = createNode(165 /* DeleteExpression */); + var node = createNode(167 /* DeleteExpression */); nextToken(); node.expression = parseUnaryExpressionOrHigher(); return finishNode(node); } function parseTypeOfExpression() { - var node = createNode(166 /* TypeOfExpression */); + var node = createNode(168 /* TypeOfExpression */); nextToken(); node.expression = parseUnaryExpressionOrHigher(); return finishNode(node); } function parseVoidExpression() { - var node = createNode(167 /* VoidExpression */); + var node = createNode(169 /* VoidExpression */); nextToken(); node.expression = parseUnaryExpressionOrHigher(); return finishNode(node); @@ -8586,7 +9435,7 @@ var ts; var expression = parseLeftHandSideExpressionOrHigher(); ts.Debug.assert(ts.isLeftHandSideExpression(expression)); if ((token === 38 /* PlusPlusToken */ || token === 39 /* MinusMinusToken */) && !scanner.hasPrecedingLineBreak()) { - var node = createNode(169 /* PostfixUnaryExpression */, expression.pos); + var node = createNode(171 /* PostfixUnaryExpression */, expression.pos); node.operand = expression; node.operator = token; nextToken(); @@ -8690,14 +9539,14 @@ var ts; } // 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(156 /* PropertyAccessExpression */, expression.pos); + var node = createNode(158 /* PropertyAccessExpression */, expression.pos); node.expression = expression; node.dotToken = parseExpectedToken(20 /* DotToken */, false, ts.Diagnostics.super_must_be_followed_by_an_argument_list_or_member_access); node.name = parseRightSideOfDot(true); return finishNode(node); } function parseTypeAssertion() { - var node = createNode(161 /* TypeAssertionExpression */); + var node = createNode(163 /* TypeAssertionExpression */); parseExpected(24 /* LessThanToken */); node.type = parseType(); parseExpected(25 /* GreaterThanToken */); @@ -8708,7 +9557,7 @@ var ts; while (true) { var dotToken = parseOptionalToken(20 /* DotToken */); if (dotToken) { - var propertyAccess = createNode(156 /* PropertyAccessExpression */, expression.pos); + var propertyAccess = createNode(158 /* PropertyAccessExpression */, expression.pos); propertyAccess.expression = expression; propertyAccess.dotToken = dotToken; propertyAccess.name = parseRightSideOfDot(true); @@ -8717,7 +9566,7 @@ var ts; } // when in the [Decorator] context, we do not parse ElementAccess as it could be part of a ComputedPropertyName if (!inDecoratorContext() && parseOptional(18 /* OpenBracketToken */)) { - var indexedAccess = createNode(157 /* ElementAccessExpression */, expression.pos); + var indexedAccess = createNode(159 /* 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. @@ -8733,7 +9582,7 @@ var ts; continue; } if (token === 10 /* NoSubstitutionTemplateLiteral */ || token === 11 /* TemplateHead */) { - var tagExpression = createNode(160 /* TaggedTemplateExpression */, expression.pos); + var tagExpression = createNode(162 /* TaggedTemplateExpression */, expression.pos); tagExpression.tag = expression; tagExpression.template = token === 10 /* NoSubstitutionTemplateLiteral */ ? parseLiteralNode() @@ -8756,7 +9605,7 @@ var ts; if (!typeArguments) { return expression; } - var callExpr = createNode(158 /* CallExpression */, expression.pos); + var callExpr = createNode(160 /* CallExpression */, expression.pos); callExpr.expression = expression; callExpr.typeArguments = typeArguments; callExpr.arguments = parseArgumentList(); @@ -8764,7 +9613,7 @@ var ts; continue; } else if (token === 16 /* OpenParenToken */) { - var callExpr = createNode(158 /* CallExpression */, expression.pos); + var callExpr = createNode(160 /* CallExpression */, expression.pos); callExpr.expression = expression; callExpr.arguments = parseArgumentList(); expression = finishNode(callExpr); @@ -8775,7 +9624,7 @@ var ts; } function parseArgumentList() { parseExpected(16 /* OpenParenToken */); - var result = parseDelimitedList(12 /* ArgumentExpressions */, parseArgumentExpression); + var result = parseDelimitedList(11 /* ArgumentExpressions */, parseArgumentExpression); parseExpected(17 /* CloseParenToken */); return result; } @@ -8783,7 +9632,7 @@ var ts; if (!parseOptional(24 /* LessThanToken */)) { return undefined; } - var typeArguments = parseDelimitedList(17 /* TypeArguments */, parseType); + var typeArguments = parseDelimitedList(16 /* TypeArguments */, parseType); if (!parseExpected(25 /* GreaterThanToken */)) { // If it doesn't have the closing > then it's definitely not an type argument list. return undefined; @@ -8866,41 +9715,41 @@ var ts; return parseIdentifier(ts.Diagnostics.Expression_expected); } function parseParenthesizedExpression() { - var node = createNode(162 /* ParenthesizedExpression */); + var node = createNode(164 /* ParenthesizedExpression */); parseExpected(16 /* OpenParenToken */); node.expression = allowInAnd(parseExpression); parseExpected(17 /* CloseParenToken */); return finishNode(node); } function parseSpreadElement() { - var node = createNode(174 /* SpreadElementExpression */); + var node = createNode(176 /* SpreadElementExpression */); parseExpected(21 /* DotDotDotToken */); node.expression = parseAssignmentExpressionOrHigher(); return finishNode(node); } function parseArgumentOrArrayLiteralElement() { return token === 21 /* DotDotDotToken */ ? parseSpreadElement() : - token === 23 /* CommaToken */ ? createNode(176 /* OmittedExpression */) : + token === 23 /* CommaToken */ ? createNode(178 /* OmittedExpression */) : parseAssignmentExpressionOrHigher(); } function parseArgumentExpression() { return doOutsideOfContext(disallowInAndDecoratorContext, parseArgumentOrArrayLiteralElement); } function parseArrayLiteralExpression() { - var node = createNode(154 /* ArrayLiteralExpression */); + var node = createNode(156 /* ArrayLiteralExpression */); parseExpected(18 /* OpenBracketToken */); if (scanner.hasPrecedingLineBreak()) node.flags |= 512 /* MultiLine */; - node.elements = parseDelimitedList(14 /* ArrayLiteralMembers */, parseArgumentOrArrayLiteralElement); + node.elements = parseDelimitedList(13 /* ArrayLiteralMembers */, parseArgumentOrArrayLiteralElement); parseExpected(19 /* CloseBracketToken */); return finishNode(node); } function tryParseAccessorDeclaration(fullStart, decorators, modifiers) { if (parseContextualModifier(116 /* GetKeyword */)) { - return parseAccessorDeclaration(137 /* GetAccessor */, fullStart, decorators, modifiers); + return parseAccessorDeclaration(138 /* GetAccessor */, fullStart, decorators, modifiers); } - else if (parseContextualModifier(121 /* SetKeyword */)) { - return parseAccessorDeclaration(138 /* SetAccessor */, fullStart, decorators, modifiers); + else if (parseContextualModifier(122 /* SetKeyword */)) { + return parseAccessorDeclaration(139 /* SetAccessor */, fullStart, decorators, modifiers); } return undefined; } @@ -8923,13 +9772,13 @@ var ts; } // Parse to check if it is short-hand property assignment or normal property assignment if ((token === 23 /* CommaToken */ || token === 15 /* CloseBraceToken */) && tokenIsIdentifier) { - var shorthandDeclaration = createNode(226 /* ShorthandPropertyAssignment */, fullStart); + var shorthandDeclaration = createNode(228 /* ShorthandPropertyAssignment */, fullStart); shorthandDeclaration.name = propertyName; shorthandDeclaration.questionToken = questionToken; return finishNode(shorthandDeclaration); } else { - var propertyAssignment = createNode(225 /* PropertyAssignment */, fullStart); + var propertyAssignment = createNode(227 /* PropertyAssignment */, fullStart); propertyAssignment.name = propertyName; propertyAssignment.questionToken = questionToken; parseExpected(51 /* ColonToken */); @@ -8938,12 +9787,12 @@ var ts; } } function parseObjectLiteralExpression() { - var node = createNode(155 /* ObjectLiteralExpression */); + var node = createNode(157 /* ObjectLiteralExpression */); parseExpected(14 /* OpenBraceToken */); if (scanner.hasPrecedingLineBreak()) { node.flags |= 512 /* MultiLine */; } - node.properties = parseDelimitedList(13 /* ObjectLiteralMembers */, parseObjectLiteralElement, true); + node.properties = parseDelimitedList(12 /* ObjectLiteralMembers */, parseObjectLiteralElement, true); parseExpected(15 /* CloseBraceToken */); return finishNode(node); } @@ -8956,7 +9805,7 @@ var ts; if (saveDecoratorContext) { setDecoratorContext(false); } - var node = createNode(163 /* FunctionExpression */); + var node = createNode(165 /* FunctionExpression */); parseExpected(83 /* FunctionKeyword */); node.asteriskToken = parseOptionalToken(35 /* AsteriskToken */); node.name = node.asteriskToken ? doInYieldContext(parseOptionalIdentifier) : parseOptionalIdentifier(); @@ -8971,7 +9820,7 @@ var ts; return isIdentifier() ? parseIdentifier() : undefined; } function parseNewExpression() { - var node = createNode(159 /* NewExpression */); + var node = createNode(161 /* NewExpression */); parseExpected(88 /* NewKeyword */); node.expression = parseMemberExpressionOrHigher(); node.typeArguments = tryParse(parseTypeArgumentsInExpression); @@ -8981,10 +9830,10 @@ var ts; return finishNode(node); } // STATEMENTS - function parseBlock(ignoreMissingOpenBrace, checkForStrictMode, diagnosticMessage) { - var node = createNode(180 /* Block */); + function parseBlock(ignoreMissingOpenBrace, diagnosticMessage) { + var node = createNode(182 /* Block */); if (parseExpected(14 /* OpenBraceToken */, diagnosticMessage) || ignoreMissingOpenBrace) { - node.statements = parseList(2 /* BlockStatements */, checkForStrictMode, parseStatement); + node.statements = parseList(1 /* BlockStatements */, parseStatement); parseExpected(15 /* CloseBraceToken */); } else { @@ -9001,7 +9850,7 @@ var ts; if (saveDecoratorContext) { setDecoratorContext(false); } - var block = parseBlock(ignoreMissingOpenBrace, true, diagnosticMessage); + var block = parseBlock(ignoreMissingOpenBrace, diagnosticMessage); if (saveDecoratorContext) { setDecoratorContext(true); } @@ -9009,12 +9858,12 @@ var ts; return block; } function parseEmptyStatement() { - var node = createNode(182 /* EmptyStatement */); + var node = createNode(184 /* EmptyStatement */); parseExpected(22 /* SemicolonToken */); return finishNode(node); } function parseIfStatement() { - var node = createNode(184 /* IfStatement */); + var node = createNode(186 /* IfStatement */); parseExpected(84 /* IfKeyword */); parseExpected(16 /* OpenParenToken */); node.expression = allowInAnd(parseExpression); @@ -9024,7 +9873,7 @@ var ts; return finishNode(node); } function parseDoStatement() { - var node = createNode(185 /* DoStatement */); + var node = createNode(187 /* DoStatement */); parseExpected(75 /* DoKeyword */); node.statement = parseStatement(); parseExpected(100 /* WhileKeyword */); @@ -9039,7 +9888,7 @@ var ts; return finishNode(node); } function parseWhileStatement() { - var node = createNode(186 /* WhileStatement */); + var node = createNode(188 /* WhileStatement */); parseExpected(100 /* WhileKeyword */); parseExpected(16 /* OpenParenToken */); node.expression = allowInAnd(parseExpression); @@ -9062,21 +9911,21 @@ var ts; } var forOrForInOrForOfStatement; if (parseOptional(86 /* InKeyword */)) { - var forInStatement = createNode(188 /* ForInStatement */, pos); + var forInStatement = createNode(190 /* ForInStatement */, pos); forInStatement.initializer = initializer; forInStatement.expression = allowInAnd(parseExpression); parseExpected(17 /* CloseParenToken */); forOrForInOrForOfStatement = forInStatement; } - else if (parseOptional(126 /* OfKeyword */)) { - var forOfStatement = createNode(189 /* ForOfStatement */, pos); + else if (parseOptional(127 /* OfKeyword */)) { + var forOfStatement = createNode(191 /* ForOfStatement */, pos); forOfStatement.initializer = initializer; forOfStatement.expression = allowInAnd(parseAssignmentExpressionOrHigher); parseExpected(17 /* CloseParenToken */); forOrForInOrForOfStatement = forOfStatement; } else { - var forStatement = createNode(187 /* ForStatement */, pos); + var forStatement = createNode(189 /* ForStatement */, pos); forStatement.initializer = initializer; parseExpected(22 /* SemicolonToken */); if (token !== 22 /* SemicolonToken */ && token !== 17 /* CloseParenToken */) { @@ -9094,7 +9943,7 @@ var ts; } function parseBreakOrContinueStatement(kind) { var node = createNode(kind); - parseExpected(kind === 191 /* BreakStatement */ ? 66 /* BreakKeyword */ : 71 /* ContinueKeyword */); + parseExpected(kind === 193 /* BreakStatement */ ? 66 /* BreakKeyword */ : 71 /* ContinueKeyword */); if (!canParseSemicolon()) { node.label = parseIdentifier(); } @@ -9102,7 +9951,7 @@ var ts; return finishNode(node); } function parseReturnStatement() { - var node = createNode(192 /* ReturnStatement */); + var node = createNode(194 /* ReturnStatement */); parseExpected(90 /* ReturnKeyword */); if (!canParseSemicolon()) { node.expression = allowInAnd(parseExpression); @@ -9111,7 +9960,7 @@ var ts; return finishNode(node); } function parseWithStatement() { - var node = createNode(193 /* WithStatement */); + var node = createNode(195 /* WithStatement */); parseExpected(101 /* WithKeyword */); parseExpected(16 /* OpenParenToken */); node.expression = allowInAnd(parseExpression); @@ -9120,32 +9969,32 @@ var ts; return finishNode(node); } function parseCaseClause() { - var node = createNode(221 /* CaseClause */); + var node = createNode(223 /* CaseClause */); parseExpected(67 /* CaseKeyword */); node.expression = allowInAnd(parseExpression); parseExpected(51 /* ColonToken */); - node.statements = parseList(4 /* SwitchClauseStatements */, false, parseStatement); + node.statements = parseList(3 /* SwitchClauseStatements */, parseStatement); return finishNode(node); } function parseDefaultClause() { - var node = createNode(222 /* DefaultClause */); + var node = createNode(224 /* DefaultClause */); parseExpected(73 /* DefaultKeyword */); parseExpected(51 /* ColonToken */); - node.statements = parseList(4 /* SwitchClauseStatements */, false, parseStatement); + node.statements = parseList(3 /* SwitchClauseStatements */, parseStatement); return finishNode(node); } function parseCaseOrDefaultClause() { return token === 67 /* CaseKeyword */ ? parseCaseClause() : parseDefaultClause(); } function parseSwitchStatement() { - var node = createNode(194 /* SwitchStatement */); + var node = createNode(196 /* SwitchStatement */); parseExpected(92 /* SwitchKeyword */); parseExpected(16 /* OpenParenToken */); node.expression = allowInAnd(parseExpression); parseExpected(17 /* CloseParenToken */); - var caseBlock = createNode(208 /* CaseBlock */, scanner.getStartPos()); + var caseBlock = createNode(210 /* CaseBlock */, scanner.getStartPos()); parseExpected(14 /* OpenBraceToken */); - caseBlock.clauses = parseList(3 /* SwitchClauses */, false, parseCaseOrDefaultClause); + caseBlock.clauses = parseList(2 /* SwitchClauses */, parseCaseOrDefaultClause); parseExpected(15 /* CloseBraceToken */); node.caseBlock = finishNode(caseBlock); return finishNode(node); @@ -9158,7 +10007,7 @@ var ts; // 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(196 /* ThrowStatement */); + var node = createNode(198 /* ThrowStatement */); parseExpected(94 /* ThrowKeyword */); node.expression = scanner.hasPrecedingLineBreak() ? undefined : allowInAnd(parseExpression); parseSemicolon(); @@ -9166,30 +10015,30 @@ var ts; } // TODO: Review for error recovery function parseTryStatement() { - var node = createNode(197 /* TryStatement */); + var node = createNode(199 /* TryStatement */); parseExpected(96 /* TryKeyword */); - node.tryBlock = parseBlock(false, false); + node.tryBlock = parseBlock(false); node.catchClause = token === 68 /* 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 === 81 /* FinallyKeyword */) { parseExpected(81 /* FinallyKeyword */); - node.finallyBlock = parseBlock(false, false); + node.finallyBlock = parseBlock(false); } return finishNode(node); } function parseCatchClause() { - var result = createNode(224 /* CatchClause */); + var result = createNode(226 /* CatchClause */); parseExpected(68 /* CatchKeyword */); if (parseExpected(16 /* OpenParenToken */)) { result.variableDeclaration = parseVariableDeclaration(); } parseExpected(17 /* CloseParenToken */); - result.block = parseBlock(false, false); + result.block = parseBlock(false); return finishNode(result); } function parseDebuggerStatement() { - var node = createNode(198 /* DebuggerStatement */); + var node = createNode(200 /* DebuggerStatement */); parseExpected(72 /* DebuggerKeyword */); parseSemicolon(); return finishNode(node); @@ -9201,45 +10050,108 @@ var ts; var fullStart = scanner.getStartPos(); var expression = allowInAnd(parseExpression); if (expression.kind === 65 /* Identifier */ && parseOptional(51 /* ColonToken */)) { - var labeledStatement = createNode(195 /* LabeledStatement */, fullStart); + var labeledStatement = createNode(197 /* LabeledStatement */, fullStart); labeledStatement.label = expression; labeledStatement.statement = parseStatement(); return finishNode(labeledStatement); } else { - var expressionStatement = createNode(183 /* ExpressionStatement */, fullStart); + var expressionStatement = createNode(185 /* ExpressionStatement */, fullStart); expressionStatement.expression = expression; parseSemicolon(); return finishNode(expressionStatement); } } - function isStartOfStatement(inErrorRecovery) { - // Functions, variable statements and classes are allowed as a statement. But as per - // the grammar, they also allow modifiers. So we have to check for those statements - // that might be following modifiers.This ensures that things work properly when - // incrementally parsing as the parser will produce the same FunctionDeclaraiton, - // VariableStatement or ClassDeclaration, if it has the same text regardless of whether - // it is inside a block or not. - if (ts.isModifier(token)) { - var result = lookAhead(parseVariableStatementOrFunctionDeclarationOrClassDeclarationWithDecoratorsOrModifiers); - if (result) { - return true; + function isIdentifierOrKeyword() { + return token >= 65 /* Identifier */; + } + function nextTokenIsIdentifierOrKeywordOnSameLine() { + nextToken(); + return isIdentifierOrKeyword() && !scanner.hasPrecedingLineBreak(); + } + function nextTokenIsIdentifierOrKeywordOrNumberOnSameLine() { + nextToken(); + return (isIdentifierOrKeyword() || token === 7 /* NumericLiteral */) && !scanner.hasPrecedingLineBreak(); + } + function isDeclaration() { + while (true) { + switch (token) { + case 98 /* VarKeyword */: + case 104 /* LetKeyword */: + case 70 /* ConstKeyword */: + case 83 /* FunctionKeyword */: + case 69 /* ClassKeyword */: + case 77 /* 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 103 /* InterfaceKeyword */: + case 125 /* TypeKeyword */: + return nextTokenIsIdentifierOnSameLine(); + case 118 /* ModuleKeyword */: + case 119 /* NamespaceKeyword */: + return nextTokenIsIdentifierOrStringLiteralOnSameLine(); + case 115 /* DeclareKeyword */: + nextToken(); + // ASI takes effect for this modifier. + if (scanner.hasPrecedingLineBreak()) { + return false; + } + continue; + case 85 /* ImportKeyword */: + nextToken(); + return token === 8 /* StringLiteral */ || token === 35 /* AsteriskToken */ || + token === 14 /* OpenBraceToken */ || isIdentifierOrKeyword(); + case 78 /* ExportKeyword */: + nextToken(); + if (token === 53 /* EqualsToken */ || token === 35 /* AsteriskToken */ || + token === 14 /* OpenBraceToken */ || token === 73 /* DefaultKeyword */) { + return true; + } + continue; + case 108 /* PublicKeyword */: + case 106 /* PrivateKeyword */: + case 107 /* ProtectedKeyword */: + case 109 /* StaticKeyword */: + nextToken(); + continue; + default: + return false; } } + } + function isStartOfDeclaration() { + return lookAhead(isDeclaration); + } + function isStartOfStatement() { switch (token) { + case 52 /* AtToken */: case 22 /* SemicolonToken */: - // 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 !inErrorRecovery; case 14 /* OpenBraceToken */: case 98 /* VarKeyword */: case 104 /* LetKeyword */: case 83 /* FunctionKeyword */: case 69 /* ClassKeyword */: + case 77 /* EnumKeyword */: case 84 /* IfKeyword */: case 75 /* DoKeyword */: case 100 /* WhileKeyword */: @@ -9258,56 +10170,53 @@ var ts; case 81 /* FinallyKeyword */: return true; case 70 /* ConstKeyword */: - // const keyword can precede enum keyword when defining constant enums - // 'const enum' do not start statement. - // In ES 6 'enum' is a future reserved keyword, so it should not be used as identifier - var isConstEnum = lookAhead(nextTokenIsEnumKeyword); - return !isConstEnum; + case 78 /* ExportKeyword */: + case 85 /* ImportKeyword */: + return isStartOfDeclaration(); + case 115 /* DeclareKeyword */: case 103 /* InterfaceKeyword */: - case 117 /* ModuleKeyword */: - case 118 /* NamespaceKeyword */: - case 77 /* EnumKeyword */: - case 124 /* TypeKeyword */: - // When followed by an identifier, these do not start a statement but might - // instead be following declarations - if (isDeclarationStart()) { - return false; - } + case 118 /* ModuleKeyword */: + case 119 /* NamespaceKeyword */: + case 125 /* TypeKeyword */: + // When these don't start a declaration, they're an identifier in an expression statement + return true; case 108 /* PublicKeyword */: case 106 /* PrivateKeyword */: case 107 /* ProtectedKeyword */: case 109 /* StaticKeyword */: - // When followed by an identifier or keyword, these do not start a statement but - // might instead be following type members - if (lookAhead(nextTokenIsIdentifierOrKeywordOnSameLine)) { - return false; - } + // 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 nextTokenIsEnumKeyword() { + function nextTokenIsIdentifierOrStartOfDestructuring() { nextToken(); - return token === 77 /* EnumKeyword */; + return isIdentifier() || token === 14 /* OpenBraceToken */ || token === 18 /* OpenBracketToken */; } - function nextTokenIsIdentifierOrKeywordOnSameLine() { - nextToken(); - return isIdentifierOrKeyword() && !scanner.hasPrecedingLineBreak(); + 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 22 /* SemicolonToken */: + return parseEmptyStatement(); case 14 /* OpenBraceToken */: - return parseBlock(false, false); + return parseBlock(false); case 98 /* VarKeyword */: - case 70 /* ConstKeyword */: - // const here should always be parsed as const declaration because of check in 'isStatement' return parseVariableStatement(scanner.getStartPos(), undefined, undefined); + case 104 /* LetKeyword */: + if (isLetDeclaration()) { + return parseVariableStatement(scanner.getStartPos(), undefined, undefined); + } + break; case 83 /* FunctionKeyword */: return parseFunctionDeclaration(scanner.getStartPos(), undefined, undefined); case 69 /* ClassKeyword */: return parseClassDeclaration(scanner.getStartPos(), undefined, undefined); - case 22 /* SemicolonToken */: - return parseEmptyStatement(); case 84 /* IfKeyword */: return parseIfStatement(); case 75 /* DoKeyword */: @@ -9317,9 +10226,9 @@ var ts; case 82 /* ForKeyword */: return parseForOrForInOrForOfStatement(); case 71 /* ContinueKeyword */: - return parseBreakOrContinueStatement(190 /* ContinueStatement */); + return parseBreakOrContinueStatement(192 /* ContinueStatement */); case 66 /* BreakKeyword */: - return parseBreakOrContinueStatement(191 /* BreakStatement */); + return parseBreakOrContinueStatement(193 /* BreakStatement */); case 90 /* ReturnKeyword */: return parseReturnStatement(); case 101 /* WithKeyword */: @@ -9329,60 +10238,78 @@ var ts; case 94 /* ThrowKeyword */: return parseThrowStatement(); case 96 /* TryKeyword */: - // Include the next two for error recovery. + // Include 'catch' and 'finally' for error recovery. case 68 /* CatchKeyword */: case 81 /* FinallyKeyword */: return parseTryStatement(); case 72 /* DebuggerKeyword */: return parseDebuggerStatement(); - case 104 /* LetKeyword */: - // If let follows identifier on the same line, it is declaration parse it as variable statement - if (isLetDeclaration()) { - return parseVariableStatement(scanner.getStartPos(), undefined, undefined); + case 52 /* AtToken */: + return parseDeclaration(); + case 103 /* InterfaceKeyword */: + case 125 /* TypeKeyword */: + case 118 /* ModuleKeyword */: + case 119 /* NamespaceKeyword */: + case 115 /* DeclareKeyword */: + case 70 /* ConstKeyword */: + case 77 /* EnumKeyword */: + case 78 /* ExportKeyword */: + case 85 /* ImportKeyword */: + case 106 /* PrivateKeyword */: + case 107 /* ProtectedKeyword */: + case 108 /* PublicKeyword */: + case 109 /* StaticKeyword */: + if (isStartOfDeclaration()) { + return parseDeclaration(); } - // Else parse it like identifier - fall through - default: - // Functions and variable statements are allowed as a statement. But as per - // the grammar, they also allow modifiers. So we have to check for those - // statements that might be following modifiers. This ensures that things - // work properly when incrementally parsing as the parser will produce the - // same FunctionDeclaraiton or VariableStatement if it has the same text - // regardless of whether it is inside a block or not. - // Even though variable statements and function declarations cannot have decorators, - // we parse them here to provide better error recovery. - if (ts.isModifier(token) || token === 52 /* AtToken */) { - var result = tryParse(parseVariableStatementOrFunctionDeclarationOrClassDeclarationWithDecoratorsOrModifiers); - if (result) { - return result; - } - } - return parseExpressionOrLabeledStatement(); + break; } + return parseExpressionOrLabeledStatement(); } - function parseVariableStatementOrFunctionDeclarationOrClassDeclarationWithDecoratorsOrModifiers() { - var start = scanner.getStartPos(); + function parseDeclaration() { + var fullStart = getNodePos(); var decorators = parseDecorators(); var modifiers = parseModifiers(); switch (token) { - case 70 /* ConstKeyword */: - var nextTokenIsEnum = lookAhead(nextTokenIsEnumKeyword); - if (nextTokenIsEnum) { - return undefined; - } - return parseVariableStatement(start, decorators, modifiers); - case 104 /* LetKeyword */: - if (!isLetDeclaration()) { - return undefined; - } - return parseVariableStatement(start, decorators, modifiers); case 98 /* VarKeyword */: - return parseVariableStatement(start, decorators, modifiers); + case 104 /* LetKeyword */: + case 70 /* ConstKeyword */: + return parseVariableStatement(fullStart, decorators, modifiers); case 83 /* FunctionKeyword */: - return parseFunctionDeclaration(start, decorators, modifiers); + return parseFunctionDeclaration(fullStart, decorators, modifiers); case 69 /* ClassKeyword */: - return parseClassDeclaration(start, decorators, modifiers); + return parseClassDeclaration(fullStart, decorators, modifiers); + case 103 /* InterfaceKeyword */: + return parseInterfaceDeclaration(fullStart, decorators, modifiers); + case 125 /* TypeKeyword */: + return parseTypeAliasDeclaration(fullStart, decorators, modifiers); + case 77 /* EnumKeyword */: + return parseEnumDeclaration(fullStart, decorators, modifiers); + case 118 /* ModuleKeyword */: + case 119 /* NamespaceKeyword */: + return parseModuleDeclaration(fullStart, decorators, modifiers); + case 85 /* ImportKeyword */: + return parseImportDeclarationOrImportEqualsDeclaration(fullStart, decorators, modifiers); + case 78 /* ExportKeyword */: + nextToken(); + return token === 73 /* DefaultKeyword */ || token === 53 /* EqualsToken */ ? + parseExportAssignment(fullStart, decorators, modifiers) : + 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(221 /* MissingDeclaration */, true, ts.Diagnostics.Declaration_expected); + node.pos = fullStart; + node.decorators = decorators; + setModifiers(node, modifiers); + return finishNode(node); + } } - return undefined; + } + function nextTokenIsIdentifierOrStringLiteralOnSameLine() { + nextToken(); + return !scanner.hasPrecedingLineBreak() && (isIdentifier() || token === 8 /* StringLiteral */); } function parseFunctionBlockOrSemicolon(isGenerator, diagnosticMessage) { if (token !== 14 /* OpenBraceToken */ && canParseSemicolon()) { @@ -9394,16 +10321,16 @@ var ts; // DECLARATIONS function parseArrayBindingElement() { if (token === 23 /* CommaToken */) { - return createNode(176 /* OmittedExpression */); + return createNode(178 /* OmittedExpression */); } - var node = createNode(153 /* BindingElement */); + var node = createNode(155 /* BindingElement */); node.dotDotDotToken = parseOptionalToken(21 /* DotDotDotToken */); node.name = parseIdentifierOrPattern(); node.initializer = parseInitializer(false); return finishNode(node); } function parseObjectBindingElement() { - var node = createNode(153 /* BindingElement */); + var node = createNode(155 /* BindingElement */); // TODO(andersh): Handle computed properties var tokenIsIdentifier = isIdentifier(); var propertyName = parsePropertyName(); @@ -9419,16 +10346,16 @@ var ts; return finishNode(node); } function parseObjectBindingPattern() { - var node = createNode(151 /* ObjectBindingPattern */); + var node = createNode(153 /* ObjectBindingPattern */); parseExpected(14 /* OpenBraceToken */); - node.elements = parseDelimitedList(10 /* ObjectBindingElements */, parseObjectBindingElement); + node.elements = parseDelimitedList(9 /* ObjectBindingElements */, parseObjectBindingElement); parseExpected(15 /* CloseBraceToken */); return finishNode(node); } function parseArrayBindingPattern() { - var node = createNode(152 /* ArrayBindingPattern */); + var node = createNode(154 /* ArrayBindingPattern */); parseExpected(18 /* OpenBracketToken */); - node.elements = parseDelimitedList(11 /* ArrayBindingElements */, parseArrayBindingElement); + node.elements = parseDelimitedList(10 /* ArrayBindingElements */, parseArrayBindingElement); parseExpected(19 /* CloseBracketToken */); return finishNode(node); } @@ -9445,7 +10372,7 @@ var ts; return parseIdentifier(); } function parseVariableDeclaration() { - var node = createNode(199 /* VariableDeclaration */); + var node = createNode(201 /* VariableDeclaration */); node.name = parseIdentifierOrPattern(); node.type = parseTypeAnnotation(); if (!isInOrOfKeyword(token)) { @@ -9454,7 +10381,7 @@ var ts; return finishNode(node); } function parseVariableDeclarationList(inForStatementInitializer) { - var node = createNode(200 /* VariableDeclarationList */); + var node = createNode(202 /* VariableDeclarationList */); switch (token) { case 98 /* VarKeyword */: break; @@ -9477,13 +10404,13 @@ var ts; // 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 === 126 /* OfKeyword */ && lookAhead(canFollowContextualOfKeyword)) { + if (token === 127 /* OfKeyword */ && lookAhead(canFollowContextualOfKeyword)) { node.declarations = createMissingList(); } else { var savedDisallowIn = inDisallowInContext(); setDisallowInContext(inForStatementInitializer); - node.declarations = parseDelimitedList(9 /* VariableDeclarations */, parseVariableDeclaration); + node.declarations = parseDelimitedList(8 /* VariableDeclarations */, parseVariableDeclaration); setDisallowInContext(savedDisallowIn); } return finishNode(node); @@ -9492,7 +10419,7 @@ var ts; return nextTokenIsIdentifier() && nextToken() === 17 /* CloseParenToken */; } function parseVariableStatement(fullStart, decorators, modifiers) { - var node = createNode(181 /* VariableStatement */, fullStart); + var node = createNode(183 /* VariableStatement */, fullStart); node.decorators = decorators; setModifiers(node, modifiers); node.declarationList = parseVariableDeclarationList(false); @@ -9500,7 +10427,7 @@ var ts; return finishNode(node); } function parseFunctionDeclaration(fullStart, decorators, modifiers) { - var node = createNode(201 /* FunctionDeclaration */, fullStart); + var node = createNode(203 /* FunctionDeclaration */, fullStart); node.decorators = decorators; setModifiers(node, modifiers); parseExpected(83 /* FunctionKeyword */); @@ -9511,7 +10438,7 @@ var ts; return finishNode(node); } function parseConstructorDeclaration(pos, decorators, modifiers) { - var node = createNode(136 /* Constructor */, pos); + var node = createNode(137 /* Constructor */, pos); node.decorators = decorators; setModifiers(node, modifiers); parseExpected(114 /* ConstructorKeyword */); @@ -9520,7 +10447,7 @@ var ts; return finishNode(node); } function parseMethodDeclaration(fullStart, decorators, modifiers, asteriskToken, name, questionToken, diagnosticMessage) { - var method = createNode(135 /* MethodDeclaration */, fullStart); + var method = createNode(136 /* MethodDeclaration */, fullStart); method.decorators = decorators; setModifiers(method, modifiers); method.asteriskToken = asteriskToken; @@ -9531,13 +10458,24 @@ var ts; return finishNode(method); } function parsePropertyDeclaration(fullStart, decorators, modifiers, name, questionToken) { - var property = createNode(133 /* PropertyDeclaration */, fullStart); + var property = createNode(134 /* PropertyDeclaration */, fullStart); property.decorators = decorators; setModifiers(property, modifiers); property.name = name; property.questionToken = questionToken; property.type = parseTypeAnnotation(); - property.initializer = allowInAnd(parseNonParameterInitializer); + // 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 Initialiser_opt[In]; + // AccessibilityModifier_opt static_opt PropertyName TypeAnnotation_opt Initialiser_opt[In, ?Yield]; + // + // The checker may still error in the static case to explicitly disallow the yield expression. + property.initializer = modifiers && modifiers.flags & 128 /* Static */ + ? allowInAnd(parseNonParameterInitializer) + : doOutsideOfContext(4 /* Yield */ | 2 /* DisallowIn */, parseNonParameterInitializer); parseSemicolon(); return finishNode(property); } @@ -9612,7 +10550,7 @@ var ts; // 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 === 121 /* SetKeyword */ || idToken === 116 /* GetKeyword */) { + if (!ts.isKeyword(idToken) || idToken === 122 /* SetKeyword */ || idToken === 116 /* GetKeyword */) { return true; } // If it *is* a keyword, but not an accessor, check a little farther along @@ -9646,7 +10584,7 @@ var ts; decorators = []; decorators.pos = scanner.getStartPos(); } - var decorator = createNode(131 /* Decorator */, decoratorStart); + var decorator = createNode(132 /* Decorator */, decoratorStart); decorator.expression = doInDecoratorContext(parseLeftHandSideExpressionOrHigher); decorators.push(finishNode(decorator)); } @@ -9679,7 +10617,7 @@ var ts; } function parseClassElement() { if (token === 22 /* SemicolonToken */) { - var result = createNode(179 /* SemicolonClassElement */); + var result = createNode(181 /* SemicolonClassElement */); nextToken(); return finishNode(result); } @@ -9705,27 +10643,24 @@ var ts; token === 18 /* OpenBracketToken */) { return parsePropertyOrMethodDeclaration(fullStart, decorators, modifiers); } - if (decorators) { + if (decorators || modifiers) { // treat this as a property declaration with a missing name. - var name_3 = createMissingNode(65 /* Identifier */, true, ts.Diagnostics.Declaration_expected); - return parsePropertyDeclaration(fullStart, decorators, modifiers, name_3, undefined); + var name_6 = createMissingNode(65 /* Identifier */, true, ts.Diagnostics.Declaration_expected); + return parsePropertyDeclaration(fullStart, decorators, modifiers, name_6, 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, 175 /* ClassExpression */); + /*fullStart*/ scanner.getStartPos(), + /*decorators*/ undefined, + /*modifiers*/ undefined, 177 /* ClassExpression */); } function parseClassDeclaration(fullStart, decorators, modifiers) { - return parseClassDeclarationOrExpression(fullStart, decorators, modifiers, 202 /* ClassDeclaration */); + return parseClassDeclarationOrExpression(fullStart, decorators, modifiers, 204 /* ClassDeclaration */); } function parseClassDeclarationOrExpression(fullStart, decorators, modifiers, kind) { - // In ES6 specification, All parts of a ClassDeclaration or a ClassExpression are strict mode code - var savedStrictModeContext = inStrictModeContext(); - setStrictModeContext(true); var node = createNode(kind, fullStart); node.decorators = decorators; setModifiers(node, modifiers); @@ -9745,9 +10680,7 @@ var ts; else { node.members = createMissingList(); } - var finishedNode = finishNode(node); - setStrictModeContext(savedStrictModeContext); - return finishedNode; + return finishNode(node); } function parseHeritageClauses(isClassHeritageClause) { // ClassTail[Yield,GeneratorParameter] : See 14.5 @@ -9761,23 +10694,23 @@ var ts; return undefined; } function parseHeritageClausesWorker() { - return parseList(19 /* HeritageClauses */, false, parseHeritageClause); + return parseList(18 /* HeritageClauses */, parseHeritageClause); } function parseHeritageClause() { if (token === 79 /* ExtendsKeyword */ || token === 102 /* ImplementsKeyword */) { - var node = createNode(223 /* HeritageClause */); + var node = createNode(225 /* HeritageClause */); node.token = token; nextToken(); - node.types = parseDelimitedList(8 /* HeritageClauseElement */, parseExpressionWithTypeArguments); + node.types = parseDelimitedList(7 /* HeritageClauseElement */, parseExpressionWithTypeArguments); return finishNode(node); } return undefined; } function parseExpressionWithTypeArguments() { - var node = createNode(177 /* ExpressionWithTypeArguments */); + var node = createNode(179 /* ExpressionWithTypeArguments */); node.expression = parseLeftHandSideExpressionOrHigher(); if (token === 24 /* LessThanToken */) { - node.typeArguments = parseBracketedList(17 /* TypeArguments */, parseType, 24 /* LessThanToken */, 25 /* GreaterThanToken */); + node.typeArguments = parseBracketedList(16 /* TypeArguments */, parseType, 24 /* LessThanToken */, 25 /* GreaterThanToken */); } return finishNode(node); } @@ -9785,10 +10718,10 @@ var ts; return token === 79 /* ExtendsKeyword */ || token === 102 /* ImplementsKeyword */; } function parseClassMembers() { - return parseList(6 /* ClassMembers */, false, parseClassElement); + return parseList(5 /* ClassMembers */, parseClassElement); } function parseInterfaceDeclaration(fullStart, decorators, modifiers) { - var node = createNode(203 /* InterfaceDeclaration */, fullStart); + var node = createNode(205 /* InterfaceDeclaration */, fullStart); node.decorators = decorators; setModifiers(node, modifiers); parseExpected(103 /* InterfaceKeyword */); @@ -9799,11 +10732,12 @@ var ts; return finishNode(node); } function parseTypeAliasDeclaration(fullStart, decorators, modifiers) { - var node = createNode(204 /* TypeAliasDeclaration */, fullStart); + var node = createNode(206 /* TypeAliasDeclaration */, fullStart); node.decorators = decorators; setModifiers(node, modifiers); - parseExpected(124 /* TypeKeyword */); + parseExpected(125 /* TypeKeyword */); node.name = parseIdentifier(); + node.typeParameters = parseTypeParameters(); parseExpected(53 /* EqualsToken */); node.type = parseType(); parseSemicolon(); @@ -9814,19 +10748,19 @@ var ts; // ConstantEnumMemberSection, which starts at the beginning of an enum declaration // or any time an integer literal initializer is encountered. function parseEnumMember() { - var node = createNode(227 /* EnumMember */, scanner.getStartPos()); + var node = createNode(229 /* EnumMember */, scanner.getStartPos()); node.name = parsePropertyName(); node.initializer = allowInAnd(parseNonParameterInitializer); return finishNode(node); } function parseEnumDeclaration(fullStart, decorators, modifiers) { - var node = createNode(205 /* EnumDeclaration */, fullStart); + var node = createNode(207 /* EnumDeclaration */, fullStart); node.decorators = decorators; setModifiers(node, modifiers); parseExpected(77 /* EnumKeyword */); node.name = parseIdentifier(); if (parseExpected(14 /* OpenBraceToken */)) { - node.members = parseDelimitedList(7 /* EnumMembers */, parseEnumMember); + node.members = parseDelimitedList(6 /* EnumMembers */, parseEnumMember); parseExpected(15 /* CloseBraceToken */); } else { @@ -9835,9 +10769,9 @@ var ts; return finishNode(node); } function parseModuleBlock() { - var node = createNode(207 /* ModuleBlock */, scanner.getStartPos()); + var node = createNode(209 /* ModuleBlock */, scanner.getStartPos()); if (parseExpected(14 /* OpenBraceToken */)) { - node.statements = parseList(1 /* ModuleElements */, false, parseModuleElement); + node.statements = parseList(1 /* BlockStatements */, parseStatement); parseExpected(15 /* CloseBraceToken */); } else { @@ -9846,7 +10780,7 @@ var ts; return finishNode(node); } function parseModuleOrNamespaceDeclaration(fullStart, decorators, modifiers, flags) { - var node = createNode(206 /* ModuleDeclaration */, fullStart); + var node = createNode(208 /* ModuleDeclaration */, fullStart); node.decorators = decorators; setModifiers(node, modifiers); node.flags |= flags; @@ -9857,7 +10791,7 @@ var ts; return finishNode(node); } function parseAmbientExternalModuleDeclaration(fullStart, decorators, modifiers) { - var node = createNode(206 /* ModuleDeclaration */, fullStart); + var node = createNode(208 /* ModuleDeclaration */, fullStart); node.decorators = decorators; setModifiers(node, modifiers); node.name = parseLiteralNode(true); @@ -9866,11 +10800,11 @@ var ts; } function parseModuleDeclaration(fullStart, decorators, modifiers) { var flags = modifiers ? modifiers.flags : 0; - if (parseOptional(118 /* NamespaceKeyword */)) { + if (parseOptional(119 /* NamespaceKeyword */)) { flags |= 32768 /* Namespace */; } else { - parseExpected(117 /* ModuleKeyword */); + parseExpected(118 /* ModuleKeyword */); if (token === 8 /* StringLiteral */) { return parseAmbientExternalModuleDeclaration(fullStart, decorators, modifiers); } @@ -9878,7 +10812,7 @@ var ts; return parseModuleOrNamespaceDeclaration(fullStart, decorators, modifiers, flags); } function isExternalModuleReference() { - return token === 119 /* RequireKeyword */ && + return token === 120 /* RequireKeyword */ && lookAhead(nextTokenIsOpenParen); } function nextTokenIsOpenParen() { @@ -9887,7 +10821,7 @@ var ts; function nextTokenIsCommaOrFromKeyword() { nextToken(); return token === 23 /* CommaToken */ || - token === 125 /* FromKeyword */; + token === 126 /* FromKeyword */; } function parseImportDeclarationOrImportEqualsDeclaration(fullStart, decorators, modifiers) { parseExpected(85 /* ImportKeyword */); @@ -9895,11 +10829,11 @@ var ts; var identifier; if (isIdentifier()) { identifier = parseIdentifier(); - if (token !== 23 /* CommaToken */ && token !== 125 /* FromKeyword */) { + if (token !== 23 /* CommaToken */ && token !== 126 /* FromKeyword */) { // ImportEquals declaration of type: // import x = require("mod"); or // import x = M.x; - var importEqualsDeclaration = createNode(209 /* ImportEqualsDeclaration */, fullStart); + var importEqualsDeclaration = createNode(211 /* ImportEqualsDeclaration */, fullStart); importEqualsDeclaration.decorators = decorators; setModifiers(importEqualsDeclaration, modifiers); importEqualsDeclaration.name = identifier; @@ -9910,7 +10844,7 @@ var ts; } } // Import statement - var importDeclaration = createNode(210 /* ImportDeclaration */, fullStart); + var importDeclaration = createNode(212 /* ImportDeclaration */, fullStart); importDeclaration.decorators = decorators; setModifiers(importDeclaration, modifiers); // ImportDeclaration: @@ -9920,7 +10854,7 @@ var ts; token === 35 /* AsteriskToken */ || token === 14 /* OpenBraceToken */) { importDeclaration.importClause = parseImportClause(identifier, afterImportPos); - parseExpected(125 /* FromKeyword */); + parseExpected(126 /* FromKeyword */); } importDeclaration.moduleSpecifier = parseModuleSpecifier(); parseSemicolon(); @@ -9933,7 +10867,7 @@ var ts; // NamedImports // ImportedDefaultBinding, NameSpaceImport // ImportedDefaultBinding, NamedImports - var importClause = createNode(211 /* ImportClause */, fullStart); + var importClause = createNode(213 /* ImportClause */, fullStart); if (identifier) { // ImportedDefaultBinding: // ImportedBinding @@ -9943,7 +10877,7 @@ var ts; // parse namespace or named imports if (!importClause.name || parseOptional(23 /* CommaToken */)) { - importClause.namedBindings = token === 35 /* AsteriskToken */ ? parseNamespaceImport() : parseNamedImportsOrExports(213 /* NamedImports */); + importClause.namedBindings = token === 35 /* AsteriskToken */ ? parseNamespaceImport() : parseNamedImportsOrExports(215 /* NamedImports */); } return finishNode(importClause); } @@ -9953,8 +10887,8 @@ var ts; : parseEntityName(false); } function parseExternalModuleReference() { - var node = createNode(220 /* ExternalModuleReference */); - parseExpected(119 /* RequireKeyword */); + var node = createNode(222 /* ExternalModuleReference */); + parseExpected(120 /* RequireKeyword */); parseExpected(16 /* OpenParenToken */); node.expression = parseModuleSpecifier(); parseExpected(17 /* CloseParenToken */); @@ -9975,7 +10909,7 @@ var ts; function parseNamespaceImport() { // NameSpaceImport: // * as ImportedBinding - var namespaceImport = createNode(212 /* NamespaceImport */); + var namespaceImport = createNode(214 /* NamespaceImport */); parseExpected(35 /* AsteriskToken */); parseExpected(111 /* AsKeyword */); namespaceImport.name = parseIdentifier(); @@ -9990,14 +10924,14 @@ var ts; // ImportsList: // ImportSpecifier // ImportsList, ImportSpecifier - node.elements = parseBracketedList(20 /* ImportOrExportSpecifiers */, kind === 213 /* NamedImports */ ? parseImportSpecifier : parseExportSpecifier, 14 /* OpenBraceToken */, 15 /* CloseBraceToken */); + node.elements = parseBracketedList(19 /* ImportOrExportSpecifiers */, kind === 215 /* NamedImports */ ? parseImportSpecifier : parseExportSpecifier, 14 /* OpenBraceToken */, 15 /* CloseBraceToken */); return finishNode(node); } function parseExportSpecifier() { - return parseImportOrExportSpecifier(218 /* ExportSpecifier */); + return parseImportOrExportSpecifier(220 /* ExportSpecifier */); } function parseImportSpecifier() { - return parseImportOrExportSpecifier(214 /* ImportSpecifier */); + return parseImportOrExportSpecifier(216 /* ImportSpecifier */); } function parseImportOrExportSpecifier(kind) { var node = createNode(kind); @@ -10022,23 +10956,23 @@ var ts; else { node.name = identifierName; } - if (kind === 214 /* ImportSpecifier */ && checkIdentifierIsKeyword) { + if (kind === 216 /* 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(216 /* ExportDeclaration */, fullStart); + var node = createNode(218 /* ExportDeclaration */, fullStart); node.decorators = decorators; setModifiers(node, modifiers); if (parseOptional(35 /* AsteriskToken */)) { - parseExpected(125 /* FromKeyword */); + parseExpected(126 /* FromKeyword */); node.moduleSpecifier = parseModuleSpecifier(); } else { - node.exportClause = parseNamedImportsOrExports(217 /* NamedExports */); - if (parseOptional(125 /* FromKeyword */)) { + node.exportClause = parseNamedImportsOrExports(219 /* NamedExports */); + if (parseOptional(126 /* FromKeyword */)) { node.moduleSpecifier = parseModuleSpecifier(); } } @@ -10046,7 +10980,7 @@ var ts; return finishNode(node); } function parseExportAssignment(fullStart, decorators, modifiers) { - var node = createNode(215 /* ExportAssignment */, fullStart); + var node = createNode(217 /* ExportAssignment */, fullStart); node.decorators = decorators; setModifiers(node, modifiers); if (parseOptional(53 /* EqualsToken */)) { @@ -10059,136 +10993,6 @@ var ts; parseSemicolon(); return finishNode(node); } - function isLetDeclaration() { - // It is let declaration if in strict mode or next token is identifier\open bracket\open curly on same line. - // otherwise it needs to be treated like identifier - return inStrictModeContext() || lookAhead(nextTokenIsIdentifierOrStartOfDestructuringOnTheSameLine); - } - function isDeclarationStart(followsModifier) { - switch (token) { - case 98 /* VarKeyword */: - case 70 /* ConstKeyword */: - case 83 /* FunctionKeyword */: - return true; - case 104 /* LetKeyword */: - return isLetDeclaration(); - case 69 /* ClassKeyword */: - case 103 /* InterfaceKeyword */: - case 77 /* EnumKeyword */: - case 124 /* TypeKeyword */: - // Not true keywords so ensure an identifier follows - return lookAhead(nextTokenIsIdentifierOrKeyword); - case 85 /* ImportKeyword */: - // Not true keywords so ensure an identifier follows or is string literal or asterisk or open brace - return lookAhead(nextTokenCanFollowImportKeyword); - case 117 /* ModuleKeyword */: - case 118 /* NamespaceKeyword */: - // Not a true keyword so ensure an identifier or string literal follows - return lookAhead(nextTokenIsIdentifierOrKeywordOrStringLiteral); - case 78 /* ExportKeyword */: - // Check for export assignment or modifier on source element - return lookAhead(nextTokenCanFollowExportKeyword); - case 115 /* DeclareKeyword */: - case 108 /* PublicKeyword */: - case 106 /* PrivateKeyword */: - case 107 /* ProtectedKeyword */: - case 109 /* StaticKeyword */: - // Check for modifier on source element - return lookAhead(nextTokenIsDeclarationStart); - case 52 /* AtToken */: - // a lookahead here is too costly, and decorators are only valid on a declaration. - // We will assume we are parsing a declaration here and report an error later - return !followsModifier; - } - } - function isIdentifierOrKeyword() { - return token >= 65 /* Identifier */; - } - function nextTokenIsIdentifierOrKeyword() { - nextToken(); - return isIdentifierOrKeyword(); - } - function nextTokenIsIdentifierOrKeywordOrStringLiteral() { - nextToken(); - return isIdentifierOrKeyword() || token === 8 /* StringLiteral */; - } - function nextTokenCanFollowImportKeyword() { - nextToken(); - return isIdentifierOrKeyword() || token === 8 /* StringLiteral */ || - token === 35 /* AsteriskToken */ || token === 14 /* OpenBraceToken */; - } - function nextTokenCanFollowExportKeyword() { - nextToken(); - return token === 53 /* EqualsToken */ || token === 35 /* AsteriskToken */ || - token === 14 /* OpenBraceToken */ || token === 73 /* DefaultKeyword */ || isDeclarationStart(true); - } - function nextTokenIsDeclarationStart() { - nextToken(); - return isDeclarationStart(true); - } - function nextTokenIsAsKeyword() { - return nextToken() === 111 /* AsKeyword */; - } - function parseDeclaration() { - var fullStart = getNodePos(); - var decorators = parseDecorators(); - var modifiers = parseModifiers(); - if (token === 78 /* ExportKeyword */) { - nextToken(); - if (token === 73 /* DefaultKeyword */ || token === 53 /* EqualsToken */) { - return parseExportAssignment(fullStart, decorators, modifiers); - } - if (token === 35 /* AsteriskToken */ || token === 14 /* OpenBraceToken */) { - return parseExportDeclaration(fullStart, decorators, modifiers); - } - } - switch (token) { - case 98 /* VarKeyword */: - case 104 /* LetKeyword */: - case 70 /* ConstKeyword */: - return parseVariableStatement(fullStart, decorators, modifiers); - case 83 /* FunctionKeyword */: - return parseFunctionDeclaration(fullStart, decorators, modifiers); - case 69 /* ClassKeyword */: - return parseClassDeclaration(fullStart, decorators, modifiers); - case 103 /* InterfaceKeyword */: - return parseInterfaceDeclaration(fullStart, decorators, modifiers); - case 124 /* TypeKeyword */: - return parseTypeAliasDeclaration(fullStart, decorators, modifiers); - case 77 /* EnumKeyword */: - return parseEnumDeclaration(fullStart, decorators, modifiers); - case 117 /* ModuleKeyword */: - case 118 /* NamespaceKeyword */: - return parseModuleDeclaration(fullStart, decorators, modifiers); - case 85 /* ImportKeyword */: - return parseImportDeclarationOrImportEqualsDeclaration(fullStart, decorators, modifiers); - default: - if (decorators) { - // We reached this point because we encountered an AtToken and assumed a declaration would - // follow. For recovery and error reporting purposes, return an incomplete declaration. - var node = createMissingNode(219 /* MissingDeclaration */, true, ts.Diagnostics.Declaration_expected); - node.pos = fullStart; - node.decorators = decorators; - setModifiers(node, modifiers); - return finishNode(node); - } - ts.Debug.fail("Mismatch between isDeclarationStart and parseDeclaration"); - } - } - function isSourceElement(inErrorRecovery) { - return isDeclarationStart() || isStartOfStatement(inErrorRecovery); - } - function parseSourceElement() { - return parseSourceElementOrModuleElement(); - } - function parseModuleElement() { - return parseSourceElementOrModuleElement(); - } - function parseSourceElementOrModuleElement() { - return isDeclarationStart() - ? parseDeclaration() - : parseStatement(); - } function processReferenceComments(sourceFile) { var triviaScanner = ts.createScanner(sourceFile.languageVersion, false, sourceText); var referencedFiles = []; @@ -10216,7 +11020,7 @@ var ts; referencedFiles.push(fileReference); } if (diagnosticMessage) { - sourceFile.parseDiagnostics.push(ts.createFileDiagnostic(sourceFile, range.pos, range.end - range.pos, diagnosticMessage)); + parseDiagnostics.push(ts.createFileDiagnostic(sourceFile, range.pos, range.end - range.pos, diagnosticMessage)); } } else { @@ -10224,7 +11028,7 @@ var ts; var amdModuleNameMatchResult = amdModuleNameRegEx.exec(comment); if (amdModuleNameMatchResult) { if (amdModuleName) { - sourceFile.parseDiagnostics.push(ts.createFileDiagnostic(sourceFile, range.pos, range.end - range.pos, ts.Diagnostics.An_AMD_module_cannot_have_multiple_name_assignments)); + parseDiagnostics.push(ts.createFileDiagnostic(sourceFile, range.pos, range.end - range.pos, ts.Diagnostics.An_AMD_module_cannot_have_multiple_name_assignments)); } amdModuleName = amdModuleNameMatchResult[2]; } @@ -10244,15 +11048,15 @@ var ts; } sourceFile.referencedFiles = referencedFiles; sourceFile.amdDependencies = amdDependencies; - sourceFile.amdModuleName = amdModuleName; + sourceFile.moduleName = amdModuleName; } function setExternalModuleIndicator(sourceFile) { sourceFile.externalModuleIndicator = ts.forEach(sourceFile.statements, function (node) { return node.flags & 1 /* Export */ - || node.kind === 209 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 220 /* ExternalModuleReference */ - || node.kind === 210 /* ImportDeclaration */ - || node.kind === 215 /* ExportAssignment */ - || node.kind === 216 /* ExportDeclaration */ + || node.kind === 211 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 222 /* ExternalModuleReference */ + || node.kind === 212 /* ImportDeclaration */ + || node.kind === 217 /* ExportAssignment */ + || node.kind === 218 /* ExportDeclaration */ ? node : undefined; }); @@ -10260,27 +11064,30 @@ var ts; var ParsingContext; (function (ParsingContext) { ParsingContext[ParsingContext["SourceElements"] = 0] = "SourceElements"; - ParsingContext[ParsingContext["ModuleElements"] = 1] = "ModuleElements"; - ParsingContext[ParsingContext["BlockStatements"] = 2] = "BlockStatements"; - ParsingContext[ParsingContext["SwitchClauses"] = 3] = "SwitchClauses"; - ParsingContext[ParsingContext["SwitchClauseStatements"] = 4] = "SwitchClauseStatements"; - ParsingContext[ParsingContext["TypeMembers"] = 5] = "TypeMembers"; - ParsingContext[ParsingContext["ClassMembers"] = 6] = "ClassMembers"; - ParsingContext[ParsingContext["EnumMembers"] = 7] = "EnumMembers"; - ParsingContext[ParsingContext["HeritageClauseElement"] = 8] = "HeritageClauseElement"; - ParsingContext[ParsingContext["VariableDeclarations"] = 9] = "VariableDeclarations"; - ParsingContext[ParsingContext["ObjectBindingElements"] = 10] = "ObjectBindingElements"; - ParsingContext[ParsingContext["ArrayBindingElements"] = 11] = "ArrayBindingElements"; - ParsingContext[ParsingContext["ArgumentExpressions"] = 12] = "ArgumentExpressions"; - ParsingContext[ParsingContext["ObjectLiteralMembers"] = 13] = "ObjectLiteralMembers"; - ParsingContext[ParsingContext["ArrayLiteralMembers"] = 14] = "ArrayLiteralMembers"; - ParsingContext[ParsingContext["Parameters"] = 15] = "Parameters"; - ParsingContext[ParsingContext["TypeParameters"] = 16] = "TypeParameters"; - ParsingContext[ParsingContext["TypeArguments"] = 17] = "TypeArguments"; - ParsingContext[ParsingContext["TupleElementTypes"] = 18] = "TupleElementTypes"; - ParsingContext[ParsingContext["HeritageClauses"] = 19] = "HeritageClauses"; - ParsingContext[ParsingContext["ImportOrExportSpecifiers"] = 20] = "ImportOrExportSpecifiers"; - ParsingContext[ParsingContext["Count"] = 21] = "Count"; // Number of parsing contexts + ParsingContext[ParsingContext["BlockStatements"] = 1] = "BlockStatements"; + ParsingContext[ParsingContext["SwitchClauses"] = 2] = "SwitchClauses"; + ParsingContext[ParsingContext["SwitchClauseStatements"] = 3] = "SwitchClauseStatements"; + ParsingContext[ParsingContext["TypeMembers"] = 4] = "TypeMembers"; + ParsingContext[ParsingContext["ClassMembers"] = 5] = "ClassMembers"; + ParsingContext[ParsingContext["EnumMembers"] = 6] = "EnumMembers"; + ParsingContext[ParsingContext["HeritageClauseElement"] = 7] = "HeritageClauseElement"; + ParsingContext[ParsingContext["VariableDeclarations"] = 8] = "VariableDeclarations"; + ParsingContext[ParsingContext["ObjectBindingElements"] = 9] = "ObjectBindingElements"; + ParsingContext[ParsingContext["ArrayBindingElements"] = 10] = "ArrayBindingElements"; + ParsingContext[ParsingContext["ArgumentExpressions"] = 11] = "ArgumentExpressions"; + ParsingContext[ParsingContext["ObjectLiteralMembers"] = 12] = "ObjectLiteralMembers"; + ParsingContext[ParsingContext["ArrayLiteralMembers"] = 13] = "ArrayLiteralMembers"; + ParsingContext[ParsingContext["Parameters"] = 14] = "Parameters"; + ParsingContext[ParsingContext["TypeParameters"] = 15] = "TypeParameters"; + ParsingContext[ParsingContext["TypeArguments"] = 16] = "TypeArguments"; + ParsingContext[ParsingContext["TupleElementTypes"] = 17] = "TupleElementTypes"; + ParsingContext[ParsingContext["HeritageClauses"] = 18] = "HeritageClauses"; + ParsingContext[ParsingContext["ImportOrExportSpecifiers"] = 19] = "ImportOrExportSpecifiers"; + ParsingContext[ParsingContext["JSDocFunctionParameters"] = 20] = "JSDocFunctionParameters"; + ParsingContext[ParsingContext["JSDocTypeArguments"] = 21] = "JSDocTypeArguments"; + ParsingContext[ParsingContext["JSDocRecordMembers"] = 22] = "JSDocRecordMembers"; + ParsingContext[ParsingContext["JSDocTupleTypes"] = 23] = "JSDocTupleTypes"; + ParsingContext[ParsingContext["Count"] = 24] = "Count"; // Number of parsing contexts })(ParsingContext || (ParsingContext = {})); var Tristate; (function (Tristate) { @@ -10288,6 +11095,546 @@ var ts; Tristate[Tristate["True"] = 1] = "True"; Tristate[Tristate["Unknown"] = 2] = "Unknown"; })(Tristate || (Tristate = {})); + var JSDocParser; + (function (JSDocParser) { + function isJSDocType() { + switch (token) { + case 35 /* AsteriskToken */: + case 50 /* QuestionToken */: + case 16 /* OpenParenToken */: + case 18 /* OpenBracketToken */: + case 46 /* ExclamationToken */: + case 14 /* OpenBraceToken */: + case 83 /* FunctionKeyword */: + case 21 /* DotDotDotToken */: + case 88 /* NewKeyword */: + case 93 /* ThisKeyword */: + return true; + } + return isIdentifierOrKeyword(); + } + JSDocParser.isJSDocType = isJSDocType; + function parseJSDocTypeExpressionForTests(content, start, length) { + initializeState("file.js", content, 2 /* Latest */, undefined); + var jsDocTypeExpression = parseJSDocTypeExpression(start, length); + var diagnostics = parseDiagnostics; + clearState(); + return jsDocTypeExpression ? { jsDocTypeExpression: jsDocTypeExpression, diagnostics: diagnostics } : undefined; + } + JSDocParser.parseJSDocTypeExpressionForTests = parseJSDocTypeExpressionForTests; + // Parses out a JSDoc type expression. The starting position should be right at the open + // curly in the type expression. Returns 'undefined' if it encounters any errors while parsing. + /* @internal */ + function parseJSDocTypeExpression(start, length) { + scanner.setText(sourceText, start, length); + // Prime the first token for us to start processing. + token = nextToken(); + var result = createNode(231 /* JSDocTypeExpression */); + parseExpected(14 /* OpenBraceToken */); + result.type = parseJSDocTopLevelType(); + parseExpected(15 /* CloseBraceToken */); + fixupParentReferences(result); + return finishNode(result); + } + JSDocParser.parseJSDocTypeExpression = parseJSDocTypeExpression; + function parseJSDocTopLevelType() { + var type = parseJSDocType(); + if (token === 44 /* BarToken */) { + var unionType = createNode(235 /* JSDocUnionType */, type.pos); + unionType.types = parseJSDocTypeList(type); + type = finishNode(unionType); + } + if (token === 53 /* EqualsToken */) { + var optionalType = createNode(242 /* JSDocOptionalType */, type.pos); + nextToken(); + optionalType.type = type; + type = finishNode(optionalType); + } + return type; + } + function parseJSDocType() { + var type = parseBasicTypeExpression(); + while (true) { + if (token === 18 /* OpenBracketToken */) { + var arrayType = createNode(234 /* JSDocArrayType */, type.pos); + arrayType.elementType = type; + nextToken(); + parseExpected(19 /* CloseBracketToken */); + type = finishNode(arrayType); + } + else if (token === 50 /* QuestionToken */) { + var nullableType = createNode(237 /* JSDocNullableType */, type.pos); + nullableType.type = type; + nextToken(); + type = finishNode(nullableType); + } + else if (token === 46 /* ExclamationToken */) { + var nonNullableType = createNode(238 /* JSDocNonNullableType */, type.pos); + nonNullableType.type = type; + nextToken(); + type = finishNode(nonNullableType); + } + else { + break; + } + } + return type; + } + function parseBasicTypeExpression() { + switch (token) { + case 35 /* AsteriskToken */: + return parseJSDocAllType(); + case 50 /* QuestionToken */: + return parseJSDocUnknownOrNullableType(); + case 16 /* OpenParenToken */: + return parseJSDocUnionType(); + case 18 /* OpenBracketToken */: + return parseJSDocTupleType(); + case 46 /* ExclamationToken */: + return parseJSDocNonNullableType(); + case 14 /* OpenBraceToken */: + return parseJSDocRecordType(); + case 83 /* FunctionKeyword */: + return parseJSDocFunctionType(); + case 21 /* DotDotDotToken */: + return parseJSDocVariadicType(); + case 88 /* NewKeyword */: + return parseJSDocConstructorType(); + case 93 /* ThisKeyword */: + return parseJSDocThisType(); + case 112 /* AnyKeyword */: + case 123 /* StringKeyword */: + case 121 /* NumberKeyword */: + case 113 /* BooleanKeyword */: + case 124 /* SymbolKeyword */: + case 99 /* VoidKeyword */: + return parseTokenNode(); + } + return parseJSDocTypeReference(); + } + function parseJSDocThisType() { + var result = createNode(246 /* JSDocThisType */); + nextToken(); + parseExpected(51 /* ColonToken */); + result.type = parseJSDocType(); + return finishNode(result); + } + function parseJSDocConstructorType() { + var result = createNode(245 /* JSDocConstructorType */); + nextToken(); + parseExpected(51 /* ColonToken */); + result.type = parseJSDocType(); + return finishNode(result); + } + function parseJSDocVariadicType() { + var result = createNode(244 /* JSDocVariadicType */); + nextToken(); + result.type = parseJSDocType(); + return finishNode(result); + } + function parseJSDocFunctionType() { + var result = createNode(243 /* JSDocFunctionType */); + nextToken(); + parseExpected(16 /* OpenParenToken */); + result.parameters = parseDelimitedList(20 /* JSDocFunctionParameters */, parseJSDocParameter); + checkForTrailingComma(result.parameters); + parseExpected(17 /* CloseParenToken */); + if (token === 51 /* ColonToken */) { + nextToken(); + result.type = parseJSDocType(); + } + return finishNode(result); + } + function parseJSDocParameter() { + var parameter = createNode(131 /* Parameter */); + parameter.type = parseJSDocType(); + return finishNode(parameter); + } + function parseJSDocOptionalType(type) { + var result = createNode(242 /* JSDocOptionalType */, type.pos); + nextToken(); + result.type = type; + return finishNode(result); + } + function parseJSDocTypeReference() { + var result = createNode(241 /* JSDocTypeReference */); + result.name = parseSimplePropertyName(); + while (parseOptional(20 /* DotToken */)) { + if (token === 24 /* LessThanToken */) { + result.typeArguments = parseTypeArguments(); + break; + } + else { + result.name = parseQualifiedName(result.name); + } + } + return finishNode(result); + } + function parseTypeArguments() { + // Move past the < + nextToken(); + var typeArguments = parseDelimitedList(21 /* JSDocTypeArguments */, parseJSDocType); + checkForTrailingComma(typeArguments); + checkForEmptyTypeArgumentList(typeArguments); + parseExpected(25 /* GreaterThanToken */); + return typeArguments; + } + function checkForEmptyTypeArgumentList(typeArguments) { + if (parseDiagnostics.length === 0 && typeArguments && typeArguments.length === 0) { + var start = typeArguments.pos - "<".length; + var end = ts.skipTrivia(sourceText, typeArguments.end) + ">".length; + return parseErrorAtPosition(start, end - start, ts.Diagnostics.Type_argument_list_cannot_be_empty); + } + } + function parseQualifiedName(left) { + var result = createNode(128 /* QualifiedName */, left.pos); + result.left = left; + result.right = parseIdentifierName(); + return finishNode(result); + } + function parseJSDocRecordType() { + var result = createNode(239 /* JSDocRecordType */); + nextToken(); + result.members = parseDelimitedList(22 /* JSDocRecordMembers */, parseJSDocRecordMember); + checkForTrailingComma(result.members); + parseExpected(15 /* CloseBraceToken */); + return finishNode(result); + } + function parseJSDocRecordMember() { + var result = createNode(240 /* JSDocRecordMember */); + result.name = parseSimplePropertyName(); + if (token === 51 /* ColonToken */) { + nextToken(); + result.type = parseJSDocType(); + } + return finishNode(result); + } + function parseJSDocNonNullableType() { + var result = createNode(238 /* JSDocNonNullableType */); + nextToken(); + result.type = parseJSDocType(); + return finishNode(result); + } + function parseJSDocTupleType() { + var result = createNode(236 /* JSDocTupleType */); + nextToken(); + result.types = parseDelimitedList(23 /* JSDocTupleTypes */, parseJSDocType); + checkForTrailingComma(result.types); + parseExpected(19 /* 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(235 /* JSDocUnionType */); + nextToken(); + result.types = parseJSDocTypeList(parseJSDocType()); + parseExpected(17 /* CloseParenToken */); + return finishNode(result); + } + function parseJSDocTypeList(firstType) { + ts.Debug.assert(!!firstType); + var types = []; + types.pos = firstType.pos; + types.push(firstType); + while (parseOptional(44 /* BarToken */)) { + types.push(parseJSDocType()); + } + types.end = scanner.getStartPos(); + return types; + } + function parseJSDocAllType() { + var result = createNode(232 /* 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 === 23 /* CommaToken */ || + token === 15 /* CloseBraceToken */ || + token === 17 /* CloseParenToken */ || + token === 25 /* GreaterThanToken */ || + token === 53 /* EqualsToken */ || + token === 44 /* BarToken */) { + var result = createNode(233 /* JSDocUnknownType */, pos); + return finishNode(result); + } + else { + var result = createNode(237 /* JSDocNullableType */, pos); + result.type = parseJSDocType(); + return finishNode(result); + } + } + function parseIsolatedJSDocComment(content, start, length) { + initializeState("file.js", content, 2 /* Latest */, undefined); + var jsDocComment = parseJSDocComment(undefined, start, length); + var diagnostics = parseDiagnostics; + clearState(); + return jsDocComment ? { jsDocComment: jsDocComment, diagnostics: diagnostics } : undefined; + } + JSDocParser.parseIsolatedJSDocComment = parseIsolatedJSDocComment; + function parseJSDocComment(parent, start, length) { + var comment = parseJSDocCommentWorker(start, length); + if (comment) { + fixupParentReferences(comment); + comment.parent = parent; + } + return comment; + } + JSDocParser.parseJSDocComment = parseJSDocComment; + 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 pos; + // NOTE(cyrusn): This is essentially a handwritten scanner for JSDocComments. I + // considered using an actual Scanner, but this would complicate things. The + // scanner would need to know it was in a Doc Comment. Otherwise, it would then + // produce comments *inside* the doc comment. In the end it was just easier to + // write a simple scanner rather than go that route. + if (length >= "/** */".length) { + if (content.charCodeAt(start) === 47 /* slash */ && + content.charCodeAt(start + 1) === 42 /* asterisk */ && + content.charCodeAt(start + 2) === 42 /* asterisk */ && + content.charCodeAt(start + 3) !== 42 /* asterisk */) { + // Initially we can parse out a tag. We also have seen a starting asterisk. + // This is so that /** * @type */ doesn't parse. + var canParseTag = true; + var seenAsterisk = true; + for (pos = start + "/**".length; pos < end;) { + var ch = content.charCodeAt(pos); + pos++; + if (ch === 64 /* at */ && canParseTag) { + parseTag(); + // Once we parse out a tag, we cannot keep parsing out tags on this line. + canParseTag = false; + continue; + } + if (ts.isLineBreak(ch)) { + // After a line break, we can parse a tag, and we haven't seen as asterisk + // on the next line yet. + canParseTag = true; + seenAsterisk = false; + continue; + } + if (ts.isWhiteSpace(ch)) { + // Whitespace doesn't affect any of our parsing. + continue; + } + // Ignore the first asterisk on a line. + if (ch === 42 /* asterisk */) { + if (seenAsterisk) { + // If we've already seen an asterisk, then we can no longer parse a tag + // on this line. + canParseTag = false; + } + seenAsterisk = true; + continue; + } + // Anything else is doc comment text. We can't do anything with it. Because it + // wasn't a tag, we can no longer parse a tag on this line until we hit the next + // line break. + canParseTag = false; + } + } + } + return createJSDocComment(); + function createJSDocComment() { + if (!tags) { + return undefined; + } + var result = createNode(247 /* JSDocComment */, start); + result.tags = tags; + return finishNode(result, end); + } + function skipWhitespace() { + while (pos < end && ts.isWhiteSpace(content.charCodeAt(pos))) { + pos++; + } + } + function parseTag() { + ts.Debug.assert(content.charCodeAt(pos - 1) === 64 /* at */); + var atToken = createNode(52 /* AtToken */, pos - 1); + atToken.end = pos; + var startPos = pos; + var tagName = scanIdentifier(); + if (!tagName) { + return; + } + var tag = handleTag(atToken, tagName) || handleUnknownTag(atToken, tagName); + addTag(tag); + } + function handleTag(atToken, tagName) { + if (tagName) { + switch (tagName.text) { + case "param": + return handleParamTag(atToken, tagName); + case "return": + case "returns": + return handleReturnTag(atToken, tagName); + case "template": + return handleTemplateTag(atToken, tagName); + case "type": + return handleTypeTag(atToken, tagName); + } + } + return undefined; + } + function handleUnknownTag(atToken, tagName) { + var result = createNode(248 /* JSDocTag */, atToken.pos); + result.atToken = atToken; + result.tagName = tagName; + return finishNode(result, pos); + } + function addTag(tag) { + if (tag) { + if (!tags) { + tags = []; + tags.pos = tag.pos; + } + tags.push(tag); + tags.end = tag.end; + } + } + function tryParseTypeExpression() { + skipWhitespace(); + if (content.charCodeAt(pos) !== 123 /* openBrace */) { + return undefined; + } + var typeExpression = parseJSDocTypeExpression(pos, end - pos); + pos = typeExpression.end; + return typeExpression; + } + function handleParamTag(atToken, tagName) { + var typeExpression = tryParseTypeExpression(); + skipWhitespace(); + var name; + var isBracketed; + if (content.charCodeAt(pos) === 91 /* openBracket */) { + pos++; + skipWhitespace(); + name = scanIdentifier(); + isBracketed = true; + } + else { + name = scanIdentifier(); + } + if (!name) { + parseErrorAtPosition(pos, 0, ts.Diagnostics.Identifier_expected); + return undefined; + } + var preName, postName; + if (typeExpression) { + postName = name; + } + else { + preName = name; + } + if (!typeExpression) { + typeExpression = tryParseTypeExpression(); + } + var result = createNode(249 /* JSDocParameterTag */, atToken.pos); + result.atToken = atToken; + result.tagName = tagName; + result.preParameterName = preName; + result.typeExpression = typeExpression; + result.postParameterName = postName; + result.isBracketed = isBracketed; + return finishNode(result, pos); + } + function handleReturnTag(atToken, tagName) { + if (ts.forEach(tags, function (t) { return t.kind === 250 /* JSDocReturnTag */; })) { + parseErrorAtPosition(tagName.pos, pos - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.text); + } + var result = createNode(250 /* JSDocReturnTag */, atToken.pos); + result.atToken = atToken; + result.tagName = tagName; + result.typeExpression = tryParseTypeExpression(); + return finishNode(result, pos); + } + function handleTypeTag(atToken, tagName) { + if (ts.forEach(tags, function (t) { return t.kind === 251 /* JSDocTypeTag */; })) { + parseErrorAtPosition(tagName.pos, pos - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.text); + } + var result = createNode(251 /* JSDocTypeTag */, atToken.pos); + result.atToken = atToken; + result.tagName = tagName; + result.typeExpression = tryParseTypeExpression(); + return finishNode(result, pos); + } + function handleTemplateTag(atToken, tagName) { + if (ts.forEach(tags, function (t) { return t.kind === 252 /* JSDocTemplateTag */; })) { + parseErrorAtPosition(tagName.pos, pos - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.text); + } + var typeParameters = []; + typeParameters.pos = pos; + while (true) { + skipWhitespace(); + var startPos = pos; + var name_7 = scanIdentifier(); + if (!name_7) { + parseErrorAtPosition(startPos, 0, ts.Diagnostics.Identifier_expected); + return undefined; + } + var typeParameter = createNode(130 /* TypeParameter */, name_7.pos); + typeParameter.name = name_7; + finishNode(typeParameter, pos); + typeParameters.push(typeParameter); + skipWhitespace(); + if (content.charCodeAt(pos) !== 44 /* comma */) { + break; + } + pos++; + } + typeParameters.end = pos; + var result = createNode(252 /* JSDocTemplateTag */, atToken.pos); + result.atToken = atToken; + result.tagName = tagName; + result.typeParameters = typeParameters; + return finishNode(result, pos); + } + function scanIdentifier() { + var startPos = pos; + for (; pos < end; pos++) { + var ch = content.charCodeAt(pos); + if (pos === startPos && ts.isIdentifierStart(ch, 2 /* Latest */)) { + continue; + } + else if (pos > startPos && ts.isIdentifierPart(ch, 2 /* Latest */)) { + continue; + } + break; + } + if (startPos === pos) { + return undefined; + } + var result = createNode(65 /* Identifier */, startPos); + result.text = content.substring(startPos, pos); + return finishNode(result, pos); + } + } + JSDocParser.parseJSDocCommentWorker = parseJSDocCommentWorker; + })(JSDocParser = Parser.JSDocParser || (Parser.JSDocParser = {})); })(Parser || (Parser = {})); var IncrementalParser; (function (IncrementalParser) { @@ -10375,7 +11722,12 @@ var ts; } // Ditch any existing LS children we may have created. This way we can avoid // moving them forward. - node._children = undefined; + if (node._children) { + node._children = undefined; + } + if (node.jsDocComment) { + node.jsDocComment = undefined; + } node.pos += delta; node.end += delta; if (aggressiveChecks && shouldCheckNode(node)) { @@ -10830,18 +12182,20 @@ var ts; var stringType = createIntrinsicType(2 /* String */, "string"); var numberType = createIntrinsicType(4 /* Number */, "number"); var booleanType = createIntrinsicType(8 /* Boolean */, "boolean"); - var esSymbolType = createIntrinsicType(1048576 /* ESSymbol */, "symbol"); + var esSymbolType = createIntrinsicType(2097152 /* ESSymbol */, "symbol"); var voidType = createIntrinsicType(16 /* Void */, "void"); - var undefinedType = createIntrinsicType(32 /* Undefined */ | 262144 /* ContainsUndefinedOrNull */, "undefined"); - var nullType = createIntrinsicType(64 /* Null */ | 262144 /* ContainsUndefinedOrNull */, "null"); + var undefinedType = createIntrinsicType(32 /* Undefined */ | 524288 /* ContainsUndefinedOrNull */, "undefined"); + var nullType = createIntrinsicType(64 /* Null */ | 524288 /* ContainsUndefinedOrNull */, "null"); var unknownType = createIntrinsicType(1 /* Any */, "unknown"); + var circularType = createIntrinsicType(1 /* Any */, "__circular__"); var emptyObjectType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); + var emptyGenericType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); + emptyGenericType.instantiations = {}; var anyFunctionType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); var noConstraintType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); - var anySignature = createSignature(undefined, undefined, emptyArray, anyType, 0, false, false); - var unknownSignature = createSignature(undefined, undefined, emptyArray, unknownType, 0, false, false); + var anySignature = createSignature(undefined, undefined, emptyArray, anyType, undefined, 0, false, false); + var unknownSignature = createSignature(undefined, undefined, emptyArray, unknownType, undefined, 0, false, false); var globals = {}; - var globalArraySymbol; var globalESSymbolConstructorSymbol; var globalObjectType; var globalFunctionType; @@ -10853,6 +12207,8 @@ var ts; var globalTemplateStringsArrayType; var globalESSymbolType; var globalIterableType; + var globalIteratorType; + var globalIterableIteratorType; var anyArrayType; var getGlobalClassDecoratorType; var getGlobalParameterDecoratorType; @@ -10886,9 +12242,14 @@ var ts; }, "symbol": { type: esSymbolType, - flags: 1048576 /* ESSymbol */ + flags: 2097152 /* ESSymbol */ } }; + var subtypeRelation = {}; + var assignableRelation = {}; + var identityRelation = {}; + initializeTypeChecker(); + return checker; function getEmitResolver(sourceFile) { // 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. @@ -11031,10 +12392,10 @@ var ts; return nodeLinks[nodeId] || (nodeLinks[nodeId] = {}); } function getSourceFile(node) { - return ts.getAncestor(node, 228 /* SourceFile */); + return ts.getAncestor(node, 230 /* SourceFile */); } function isGlobalSourceFile(node) { - return node.kind === 228 /* SourceFile */ && !ts.isExternalModule(node); + return node.kind === 230 /* SourceFile */ && !ts.isExternalModule(node); } function getSymbol(symbols, name, meaning) { if (meaning && ts.hasProperty(symbols, name)) { @@ -11079,44 +12440,66 @@ var ts; // Locals of a source file are not in scope (because they get merged into the global symbol table) if (location.locals && !isGlobalSourceFile(location)) { if (result = getSymbol(location.locals, name, meaning)) { - break loop; + // 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. + if (!(meaning & 793056 /* Type */) || + !(result.flags & (793056 /* Type */ & ~262144 /* TypeParameter */)) || + !ts.isFunctionLike(location) || + lastLocation === location.body) { + break loop; + } + result = undefined; } } switch (location.kind) { - case 228 /* SourceFile */: + case 230 /* SourceFile */: if (!ts.isExternalModule(location)) break; - case 206 /* ModuleDeclaration */: - if (result = getSymbol(getSymbolOfNode(location).exports, name, meaning & 8914931 /* ModuleMember */)) { - if (result.flags & meaning || !(result.flags & 8388608 /* Alias */ && getDeclarationOfAliasSymbol(result).kind === 218 /* ExportSpecifier */)) { - break loop; + case 208 /* ModuleDeclaration */: + var moduleExports = getSymbolOfNode(location).exports; + if (location.kind === 230 /* SourceFile */ || + (location.kind === 208 /* ModuleDeclaration */ && location.name.kind === 8 /* StringLiteral */)) { + // It's an external module. 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. + if (ts.hasProperty(moduleExports, name) && + moduleExports[name].flags === 8388608 /* Alias */ && + ts.getDeclarationOfKind(moduleExports[name], 220 /* ExportSpecifier */)) { + break; } - result = undefined; - } - else if (location.kind === 228 /* SourceFile */ || - (location.kind === 206 /* ModuleDeclaration */ && location.name.kind === 8 /* StringLiteral */)) { - result = getSymbolOfNode(location).exports["default"]; + result = moduleExports["default"]; var localSymbol = ts.getLocalSymbolForExportDefault(result); if (result && localSymbol && (result.flags & meaning) && localSymbol.name === name) { break loop; } result = undefined; } + if (result = getSymbol(moduleExports, name, meaning & 8914931 /* ModuleMember */)) { + break loop; + } break; - case 205 /* EnumDeclaration */: + case 207 /* EnumDeclaration */: if (result = getSymbol(getSymbolOfNode(location).exports, name, meaning & 8 /* EnumMember */)) { break loop; } break; - case 133 /* PropertyDeclaration */: - case 132 /* PropertySignature */: + case 134 /* PropertyDeclaration */: + case 133 /* 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 (location.parent.kind === 202 /* ClassDeclaration */ && !(location.flags & 128 /* Static */)) { + if (location.parent.kind === 204 /* ClassDeclaration */ && !(location.flags & 128 /* Static */)) { var ctor = findConstructorDeclaration(location.parent); if (ctor && ctor.locals) { if (getSymbol(ctor.locals, name, meaning & 107455 /* Value */)) { @@ -11126,8 +12509,8 @@ var ts; } } break; - case 202 /* ClassDeclaration */: - case 203 /* InterfaceDeclaration */: + case 204 /* ClassDeclaration */: + case 205 /* InterfaceDeclaration */: if (result = getSymbol(getSymbolOfNode(location).members, name, meaning & 793056 /* Type */)) { if (lastLocation && lastLocation.flags & 128 /* Static */) { // TypeScript 1.0 spec (April 2014): 3.4.1 @@ -11147,9 +12530,9 @@ var ts; // [foo()]() { } // <-- Reference to T from class's own computed property // } // - case 128 /* ComputedPropertyName */: + case 129 /* ComputedPropertyName */: grandparent = location.parent.parent; - if (grandparent.kind === 202 /* ClassDeclaration */ || grandparent.kind === 203 /* InterfaceDeclaration */) { + if (grandparent.kind === 204 /* ClassDeclaration */ || grandparent.kind === 205 /* InterfaceDeclaration */) { // A reference to this grandparent's type parameters would be an error if (result = getSymbol(getSymbolOfNode(grandparent).members, name, meaning & 793056 /* Type */)) { error(errorLocation, ts.Diagnostics.A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type); @@ -11157,37 +12540,41 @@ var ts; } } break; - case 135 /* MethodDeclaration */: - case 134 /* MethodSignature */: - case 136 /* Constructor */: - case 137 /* GetAccessor */: - case 138 /* SetAccessor */: - case 201 /* FunctionDeclaration */: - case 164 /* ArrowFunction */: - if (name === "arguments") { + case 136 /* MethodDeclaration */: + case 135 /* MethodSignature */: + case 137 /* Constructor */: + case 138 /* GetAccessor */: + case 139 /* SetAccessor */: + case 203 /* FunctionDeclaration */: + case 166 /* ArrowFunction */: + if (meaning & 3 /* Variable */ && name === "arguments") { result = argumentsSymbol; break loop; } break; - case 163 /* FunctionExpression */: - if (name === "arguments") { + case 165 /* FunctionExpression */: + if (meaning & 3 /* Variable */ && name === "arguments") { result = argumentsSymbol; break loop; } - var functionName = location.name; - if (functionName && name === functionName.text) { - result = location.symbol; - break loop; + if (meaning & 16 /* Function */) { + var functionName = location.name; + if (functionName && name === functionName.text) { + result = location.symbol; + break loop; + } } break; - case 175 /* ClassExpression */: - var className = location.name; - if (className && name === className.text) { - result = location.symbol; - break loop; + case 177 /* ClassExpression */: + if (meaning & 32 /* Class */) { + var className = location.name; + if (className && name === className.text) { + result = location.symbol; + break loop; + } } break; - case 131 /* Decorator */: + case 132 /* Decorator */: // Decorators are resolved at the class declaration. Resolving at the parameter // or member would result in looking up locals in the method. // @@ -11196,7 +12583,7 @@ var ts; // method(@y x, y) {} // <-- decorator y should be resolved at the class declaration, not the parameter. // } // - if (location.parent && location.parent.kind === 130 /* Parameter */) { + if (location.parent && location.parent.kind === 131 /* Parameter */) { location = location.parent; } // @@ -11252,16 +12639,16 @@ var ts; // for (let x in x) // for (let x of x) // climb up to the variable declaration skipping binding patterns - var variableDeclaration = ts.getAncestor(declaration, 199 /* VariableDeclaration */); + var variableDeclaration = ts.getAncestor(declaration, 201 /* VariableDeclaration */); var container = ts.getEnclosingBlockScopeContainer(variableDeclaration); - if (variableDeclaration.parent.parent.kind === 181 /* VariableStatement */ || - variableDeclaration.parent.parent.kind === 187 /* ForStatement */) { + if (variableDeclaration.parent.parent.kind === 183 /* VariableStatement */ || + variableDeclaration.parent.parent.kind === 189 /* ForStatement */) { // variable statement/for statement case, // use site should not be inside variable declaration (initializer of declaration or binding element) isUsedBeforeDeclaration = isSameScopeDescendentOf(errorLocation, variableDeclaration, container); } - else if (variableDeclaration.parent.parent.kind === 189 /* ForOfStatement */ || - variableDeclaration.parent.parent.kind === 188 /* ForInStatement */) { + else if (variableDeclaration.parent.parent.kind === 191 /* ForOfStatement */ || + variableDeclaration.parent.parent.kind === 190 /* ForInStatement */) { // ForIn/ForOf case - use site should not be used in expression part var expression = variableDeclaration.parent.parent.expression; isUsedBeforeDeclaration = isSameScopeDescendentOf(errorLocation, expression, container); @@ -11288,10 +12675,10 @@ var ts; } function getAnyImportSyntax(node) { if (ts.isAliasSymbolDeclaration(node)) { - if (node.kind === 209 /* ImportEqualsDeclaration */) { + if (node.kind === 211 /* ImportEqualsDeclaration */) { return node; } - while (node && node.kind !== 210 /* ImportDeclaration */) { + while (node && node.kind !== 212 /* ImportDeclaration */) { node = node.parent; } return node; @@ -11301,7 +12688,7 @@ var ts; return ts.forEach(symbol.declarations, function (d) { return ts.isAliasSymbolDeclaration(d) ? d : undefined; }); } function getTargetOfImportEqualsDeclaration(node) { - if (node.moduleReference.kind === 220 /* ExternalModuleReference */) { + if (node.moduleReference.kind === 222 /* ExternalModuleReference */) { return resolveExternalModuleSymbol(resolveExternalModuleName(node, ts.getExternalModuleImportEqualsDeclarationExpression(node))); } return getSymbolOfPartOfRightHandSideOfImportEquals(node.moduleReference, node); @@ -11381,15 +12768,15 @@ var ts; var moduleSymbol = resolveExternalModuleName(node, node.moduleSpecifier); var targetSymbol = resolveESModuleSymbol(moduleSymbol, node.moduleSpecifier); if (targetSymbol) { - var name_4 = specifier.propertyName || specifier.name; - if (name_4.text) { - var symbolFromModule = getExportOfModule(targetSymbol, name_4.text); - var symbolFromVariable = getPropertyOfVariable(targetSymbol, name_4.text); + var name_8 = specifier.propertyName || specifier.name; + if (name_8.text) { + var symbolFromModule = getExportOfModule(targetSymbol, name_8.text); + var symbolFromVariable = getPropertyOfVariable(targetSymbol, name_8.text); var symbol = symbolFromModule && symbolFromVariable ? combineValueAndTypeSymbols(symbolFromVariable, symbolFromModule) : symbolFromModule || symbolFromVariable; if (!symbol) { - error(name_4, ts.Diagnostics.Module_0_has_no_exported_member_1, getFullyQualifiedName(moduleSymbol), ts.declarationNameToString(name_4)); + error(name_8, ts.Diagnostics.Module_0_has_no_exported_member_1, getFullyQualifiedName(moduleSymbol), ts.declarationNameToString(name_8)); } return symbol; } @@ -11408,17 +12795,17 @@ var ts; } function getTargetOfAliasDeclaration(node) { switch (node.kind) { - case 209 /* ImportEqualsDeclaration */: + case 211 /* ImportEqualsDeclaration */: return getTargetOfImportEqualsDeclaration(node); - case 211 /* ImportClause */: + case 213 /* ImportClause */: return getTargetOfImportClause(node); - case 212 /* NamespaceImport */: + case 214 /* NamespaceImport */: return getTargetOfNamespaceImport(node); - case 214 /* ImportSpecifier */: + case 216 /* ImportSpecifier */: return getTargetOfImportSpecifier(node); - case 218 /* ExportSpecifier */: + case 220 /* ExportSpecifier */: return getTargetOfExportSpecifier(node); - case 215 /* ExportAssignment */: + case 217 /* ExportAssignment */: return getTargetOfExportAssignment(node); } } @@ -11448,7 +12835,7 @@ var ts; var symbol = getSymbolOfNode(node); var target = resolveAlias(symbol); if (target) { - var markAlias = (target === unknownSymbol && compilerOptions.separateCompilation) || + var markAlias = (target === unknownSymbol && compilerOptions.isolatedModules) || (target !== unknownSymbol && (target.flags & 107455 /* Value */) && !isConstEnumOrConstEnumOnlyModule(target)); if (markAlias) { markAliasSymbolAsReferenced(symbol); @@ -11463,11 +12850,11 @@ var ts; if (!links.referenced) { links.referenced = true; var node = getDeclarationOfAliasSymbol(symbol); - if (node.kind === 215 /* ExportAssignment */) { + if (node.kind === 217 /* ExportAssignment */) { // export default checkExpressionCached(node.expression); } - else if (node.kind === 218 /* ExportSpecifier */) { + else if (node.kind === 220 /* ExportSpecifier */) { // export { } or export { as foo } checkExpressionCached(node.propertyName || node.name); } @@ -11480,7 +12867,7 @@ var ts; // This function is only for imports with entity names function getSymbolOfPartOfRightHandSideOfImportEquals(entityName, importDeclaration) { if (!importDeclaration) { - importDeclaration = ts.getAncestor(entityName, 209 /* ImportEqualsDeclaration */); + importDeclaration = ts.getAncestor(entityName, 211 /* ImportEqualsDeclaration */); ts.Debug.assert(importDeclaration !== undefined); } // There are three things we might try to look for. In the following examples, @@ -11493,13 +12880,13 @@ var ts; entityName = entityName.parent; } // Check for case 1 and 3 in the above example - if (entityName.kind === 65 /* Identifier */ || entityName.parent.kind === 127 /* QualifiedName */) { + if (entityName.kind === 65 /* Identifier */ || entityName.parent.kind === 128 /* QualifiedName */) { return resolveEntityName(entityName, 1536 /* Namespace */); } else { // Case 2 in above example // entityName.kind could be a QualifiedName or a Missing identifier - ts.Debug.assert(entityName.parent.kind === 209 /* ImportEqualsDeclaration */); + ts.Debug.assert(entityName.parent.kind === 211 /* ImportEqualsDeclaration */); return resolveEntityName(entityName, 107455 /* Value */ | 793056 /* Type */ | 1536 /* Namespace */); } } @@ -11519,9 +12906,9 @@ var ts; return undefined; } } - else if (name.kind === 127 /* QualifiedName */ || name.kind === 156 /* PropertyAccessExpression */) { - var left = name.kind === 127 /* QualifiedName */ ? name.left : name.expression; - var right = name.kind === 127 /* QualifiedName */ ? name.right : name.name; + else if (name.kind === 128 /* QualifiedName */ || name.kind === 158 /* PropertyAccessExpression */) { + var left = name.kind === 128 /* QualifiedName */ ? name.left : name.expression; + var right = name.kind === 128 /* QualifiedName */ ? name.right : name.name; var namespace = resolveEntityName(left, 1536 /* Namespace */); if (!namespace || namespace === unknownSymbol || ts.nodeIsMissing(right)) { return undefined; @@ -11682,7 +13069,7 @@ var ts; var members = node.members; for (var _i = 0; _i < members.length; _i++) { var member = members[_i]; - if (member.kind === 136 /* Constructor */ && ts.nodeIsPresent(member.body)) { + if (member.kind === 137 /* Constructor */ && ts.nodeIsPresent(member.body)) { return member; } } @@ -11752,17 +13139,17 @@ var ts; } } switch (location_1.kind) { - case 228 /* SourceFile */: + case 230 /* SourceFile */: if (!ts.isExternalModule(location_1)) { break; } - case 206 /* ModuleDeclaration */: + case 208 /* ModuleDeclaration */: if (result = callback(getSymbolOfNode(location_1).exports)) { return result; } break; - case 202 /* ClassDeclaration */: - case 203 /* InterfaceDeclaration */: + case 204 /* ClassDeclaration */: + case 205 /* InterfaceDeclaration */: if (result = callback(getSymbolOfNode(location_1).members)) { return result; } @@ -11911,8 +13298,8 @@ var ts; } } function hasExternalModuleSymbol(declaration) { - return (declaration.kind === 206 /* ModuleDeclaration */ && declaration.name.kind === 8 /* StringLiteral */) || - (declaration.kind === 228 /* SourceFile */ && ts.isExternalModule(declaration)); + return (declaration.kind === 208 /* ModuleDeclaration */ && declaration.name.kind === 8 /* StringLiteral */) || + (declaration.kind === 230 /* SourceFile */ && ts.isExternalModule(declaration)); } function hasVisibleDeclarations(symbol) { var aliasesToMakeVisible; @@ -11948,12 +13335,12 @@ var ts; function isEntityNameVisible(entityName, enclosingDeclaration) { // get symbol of the first identifier of the entityName var meaning; - if (entityName.parent.kind === 145 /* TypeQuery */) { + if (entityName.parent.kind === 147 /* TypeQuery */) { // Typeof value meaning = 107455 /* Value */ | 1048576 /* ExportValue */; } - else if (entityName.kind === 127 /* QualifiedName */ || entityName.kind === 156 /* PropertyAccessExpression */ || - entityName.parent.kind === 209 /* ImportEqualsDeclaration */) { + else if (entityName.kind === 128 /* QualifiedName */ || entityName.kind === 158 /* PropertyAccessExpression */ || + entityName.parent.kind === 211 /* ImportEqualsDeclaration */) { // Left identifier from type reference or TypeAlias // Entity name of the import declaration meaning = 1536 /* Namespace */; @@ -11987,6 +13374,13 @@ var ts; ts.releaseStringWriter(writer); return result; } + function signatureToString(signature, enclosingDeclaration, flags) { + var writer = ts.getSingleLineStringWriter(); + getSymbolDisplayBuilder().buildSignatureDisplay(signature, writer, enclosingDeclaration, flags); + var result = writer.string(); + ts.releaseStringWriter(writer); + return result; + } function typeToString(type, enclosingDeclaration, flags) { var writer = ts.getSingleLineStringWriter(); getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); @@ -12001,10 +13395,10 @@ var ts; function getTypeAliasForTypeLiteral(type) { if (type.symbol && type.symbol.flags & 2048 /* TypeLiteral */) { var node = type.symbol.declarations[0].parent; - while (node.kind === 150 /* ParenthesizedType */) { + while (node.kind === 152 /* ParenthesizedType */) { node = node.parent; } - if (node.kind === 204 /* TypeAliasDeclaration */) { + if (node.kind === 206 /* TypeAliasDeclaration */) { return getSymbolOfNode(node); } } @@ -12095,15 +13489,16 @@ var ts; } return appendParentTypeArgumentsAndSymbolName(symbol); } - function buildTypeDisplay(type, writer, enclosingDeclaration, globalFlags, typeStack) { + function buildTypeDisplay(type, writer, enclosingDeclaration, globalFlags, symbolStack) { var globalFlagsToPass = globalFlags & 16 /* WriteOwnNameForAnyLike */; return writeType(type, globalFlags); function writeType(type, flags) { // Write undefined/null type as any - if (type.flags & 1048703 /* Intrinsic */) { + if (type.flags & 2097279 /* Intrinsic */) { // Special handling for unknown / resolving types, they should show up as any and not unknown or __resolving - writer.writeKeyword(!(globalFlags & 16 /* WriteOwnNameForAnyLike */) && - (type.flags & 1 /* Any */) ? "any" : type.intrinsicName); + writer.writeKeyword(!(globalFlags & 16 /* WriteOwnNameForAnyLike */) && isTypeAny(type) + ? "any" + : type.intrinsicName); } else if (type.flags & 4096 /* Reference */) { writeTypeReference(type, flags); @@ -12146,17 +13541,54 @@ var ts; writeType(types[i], union ? 64 /* InElementType */ : 0 /* None */); } } + function writeSymbolTypeReference(symbol, typeArguments, pos, end) { + // Unnamed function expressions, arrow functions, and unnamed class expressions have reserved names that + // we don't want to display + if (!isReservedMemberName(symbol.name)) { + buildSymbolDisplay(symbol, writer, enclosingDeclaration, 793056 /* Type */); + } + if (pos < end) { + writePunctuation(writer, 24 /* LessThanToken */); + writeType(typeArguments[pos++], 0 /* None */); + while (pos < end) { + writePunctuation(writer, 23 /* CommaToken */); + writeSpace(writer); + writeType(typeArguments[pos++], 0 /* None */); + } + writePunctuation(writer, 25 /* GreaterThanToken */); + } + } function writeTypeReference(type, flags) { + var typeArguments = type.typeArguments; if (type.target === globalArrayType && !(flags & 1 /* WriteArrayAsGenericType */)) { - writeType(type.typeArguments[0], 64 /* InElementType */); + writeType(typeArguments[0], 64 /* InElementType */); writePunctuation(writer, 18 /* OpenBracketToken */); writePunctuation(writer, 19 /* CloseBracketToken */); } else { - buildSymbolDisplay(type.target.symbol, writer, enclosingDeclaration, 793056 /* Type */); - writePunctuation(writer, 24 /* LessThanToken */); - writeTypeList(type.typeArguments, false); - writePunctuation(writer, 25 /* GreaterThanToken */); + // 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_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_3 = getParentSymbolOfTypeParameter(outerTypeParameters[i]); + do { + i++; + } while (i < length_1 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent_3); + // 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_3, typeArguments, start, i); + writePunctuation(writer, 20 /* DotToken */); + } + } + } + writeSymbolTypeReference(type.symbol, typeArguments, i, typeArguments.length); } } function writeTupleType(type) { @@ -12174,47 +13606,54 @@ var ts; } } function writeAnonymousType(type, flags) { - // Always use 'typeof T' for type of class, enum, and module objects - if (type.symbol && type.symbol.flags & (32 /* Class */ | 384 /* Enum */ | 512 /* ValueModule */)) { - writeTypeofSymbol(type, flags); - } - else if (shouldWriteTypeOfFunctionSymbol()) { - writeTypeofSymbol(type, flags); - } - else if (typeStack && ts.contains(typeStack, type)) { - // 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, 793056 /* Type */, 0 /* None */, flags); + var symbol = type.symbol; + if (symbol) { + // Always use 'typeof T' for type of class, enum, and module objects + if (symbol.flags & (32 /* Class */ | 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, 793056 /* Type */, 0 /* None */, flags); + } + else { + // Recursive usage, use any + writeKeyword(writer, 112 /* AnyKeyword */); + } } else { - // Recursive usage, use any - writeKeyword(writer, 112 /* AnyKeyword */); + // 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 { - if (!typeStack) { - typeStack = []; - } - typeStack.push(type); + // Anonymous types with no symbol are never circular writeLiteralType(type, flags); - typeStack.pop(); } function shouldWriteTypeOfFunctionSymbol() { - if (type.symbol) { - var isStaticMethodSymbol = !!(type.symbol.flags & 8192 /* Method */ && - ts.forEach(type.symbol.declarations, function (declaration) { return declaration.flags & 128 /* Static */; })); - var isNonLocalFunctionSymbol = !!(type.symbol.flags & 16 /* Function */) && - (type.symbol.parent || - ts.forEach(type.symbol.declarations, function (declaration) { - return declaration.parent.kind === 228 /* SourceFile */ || declaration.parent.kind === 207 /* ModuleBlock */; - })); - if (isStaticMethodSymbol || isNonLocalFunctionSymbol) { - // typeof is allowed only for static/non local functions - return !!(flags & 2 /* UseTypeOfFunction */) || - (typeStack && ts.contains(typeStack, type)); // it is type of the symbol uses itself recursively - } + var isStaticMethodSymbol = !!(symbol.flags & 8192 /* Method */ && + ts.forEach(symbol.declarations, function (declaration) { return declaration.flags & 128 /* Static */; })); + var isNonLocalFunctionSymbol = !!(symbol.flags & 16 /* Function */) && + (symbol.parent || + ts.forEach(symbol.declarations, function (declaration) { + return declaration.parent.kind === 230 /* SourceFile */ || declaration.parent.kind === 209 /* 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 } } } @@ -12245,7 +13684,7 @@ var ts; if (flags & 64 /* InElementType */) { writePunctuation(writer, 16 /* OpenParenToken */); } - buildSignatureDisplay(resolved.callSignatures[0], writer, enclosingDeclaration, globalFlagsToPass | 8 /* WriteArrowStyleSignature */, typeStack); + buildSignatureDisplay(resolved.callSignatures[0], writer, enclosingDeclaration, globalFlagsToPass | 8 /* WriteArrowStyleSignature */, symbolStack); if (flags & 64 /* InElementType */) { writePunctuation(writer, 17 /* CloseParenToken */); } @@ -12257,7 +13696,7 @@ var ts; } writeKeyword(writer, 88 /* NewKeyword */); writeSpace(writer); - buildSignatureDisplay(resolved.constructSignatures[0], writer, enclosingDeclaration, globalFlagsToPass | 8 /* WriteArrowStyleSignature */, typeStack); + buildSignatureDisplay(resolved.constructSignatures[0], writer, enclosingDeclaration, globalFlagsToPass | 8 /* WriteArrowStyleSignature */, symbolStack); if (flags & 64 /* InElementType */) { writePunctuation(writer, 17 /* CloseParenToken */); } @@ -12269,7 +13708,7 @@ var ts; writer.increaseIndent(); for (var _i = 0, _a = resolved.callSignatures; _i < _a.length; _i++) { var signature = _a[_i]; - buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, typeStack); + buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, symbolStack); writePunctuation(writer, 22 /* SemicolonToken */); writer.writeLine(); } @@ -12277,7 +13716,7 @@ var ts; var signature = _c[_b]; writeKeyword(writer, 88 /* NewKeyword */); writeSpace(writer); - buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, typeStack); + buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, symbolStack); writePunctuation(writer, 22 /* SemicolonToken */); writer.writeLine(); } @@ -12287,7 +13726,7 @@ var ts; writer.writeParameter(getIndexerParameterName(resolved, 0 /* String */, "x")); writePunctuation(writer, 51 /* ColonToken */); writeSpace(writer); - writeKeyword(writer, 122 /* StringKeyword */); + writeKeyword(writer, 123 /* StringKeyword */); writePunctuation(writer, 19 /* CloseBracketToken */); writePunctuation(writer, 51 /* ColonToken */); writeSpace(writer); @@ -12301,7 +13740,7 @@ var ts; writer.writeParameter(getIndexerParameterName(resolved, 1 /* Number */, "x")); writePunctuation(writer, 51 /* ColonToken */); writeSpace(writer); - writeKeyword(writer, 120 /* NumberKeyword */); + writeKeyword(writer, 121 /* NumberKeyword */); writePunctuation(writer, 19 /* CloseBracketToken */); writePunctuation(writer, 51 /* ColonToken */); writeSpace(writer); @@ -12320,7 +13759,7 @@ var ts; if (p.flags & 536870912 /* Optional */) { writePunctuation(writer, 50 /* QuestionToken */); } - buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, typeStack); + buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, symbolStack); writePunctuation(writer, 22 /* SemicolonToken */); writer.writeLine(); } @@ -12344,32 +13783,33 @@ var ts; function buildTypeParameterDisplayFromSymbol(symbol, writer, enclosingDeclaraiton, flags) { var targetSymbol = getTargetSymbol(symbol); if (targetSymbol.flags & 32 /* Class */ || targetSymbol.flags & 64 /* Interface */) { - buildDisplayForTypeParametersAndDelimiters(getTypeParametersOfClassOrInterface(symbol), writer, enclosingDeclaraiton, flags); + buildDisplayForTypeParametersAndDelimiters(getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol), writer, enclosingDeclaraiton, flags); } } - function buildTypeParameterDisplay(tp, writer, enclosingDeclaration, flags, typeStack) { + function buildTypeParameterDisplay(tp, writer, enclosingDeclaration, flags, symbolStack) { appendSymbolNameOnly(tp.symbol, writer); var constraint = getConstraintOfTypeParameter(tp); if (constraint) { writeSpace(writer); writeKeyword(writer, 79 /* ExtendsKeyword */); writeSpace(writer); - buildTypeDisplay(constraint, writer, enclosingDeclaration, flags, typeStack); + buildTypeDisplay(constraint, writer, enclosingDeclaration, flags, symbolStack); } } - function buildParameterDisplay(p, writer, enclosingDeclaration, flags, typeStack) { - if (ts.hasDotDotDotToken(p.valueDeclaration)) { + function buildParameterDisplay(p, writer, enclosingDeclaration, flags, symbolStack) { + var parameterNode = p.valueDeclaration; + if (ts.isRestParameter(parameterNode)) { writePunctuation(writer, 21 /* DotDotDotToken */); } appendSymbolNameOnly(p, writer); - if (ts.hasQuestionToken(p.valueDeclaration) || p.valueDeclaration.initializer) { + if (isOptionalParameter(parameterNode)) { writePunctuation(writer, 50 /* QuestionToken */); } writePunctuation(writer, 51 /* ColonToken */); writeSpace(writer); - buildTypeDisplay(getTypeOfSymbol(p), writer, enclosingDeclaration, flags, typeStack); + buildTypeDisplay(getTypeOfSymbol(p), writer, enclosingDeclaration, flags, symbolStack); } - function buildDisplayForTypeParametersAndDelimiters(typeParameters, writer, enclosingDeclaration, flags, typeStack) { + function buildDisplayForTypeParametersAndDelimiters(typeParameters, writer, enclosingDeclaration, flags, symbolStack) { if (typeParameters && typeParameters.length) { writePunctuation(writer, 24 /* LessThanToken */); for (var i = 0; i < typeParameters.length; i++) { @@ -12377,12 +13817,12 @@ var ts; writePunctuation(writer, 23 /* CommaToken */); writeSpace(writer); } - buildTypeParameterDisplay(typeParameters[i], writer, enclosingDeclaration, flags, typeStack); + buildTypeParameterDisplay(typeParameters[i], writer, enclosingDeclaration, flags, symbolStack); } writePunctuation(writer, 25 /* GreaterThanToken */); } } - function buildDisplayForTypeArgumentsAndDelimiters(typeParameters, mapper, writer, enclosingDeclaration, flags, typeStack) { + function buildDisplayForTypeArgumentsAndDelimiters(typeParameters, mapper, writer, enclosingDeclaration, flags, symbolStack) { if (typeParameters && typeParameters.length) { writePunctuation(writer, 24 /* LessThanToken */); for (var i = 0; i < typeParameters.length; i++) { @@ -12395,18 +13835,18 @@ var ts; writePunctuation(writer, 25 /* GreaterThanToken */); } } - function buildDisplayForParametersAndDelimiters(parameters, writer, enclosingDeclaration, flags, typeStack) { + function buildDisplayForParametersAndDelimiters(parameters, writer, enclosingDeclaration, flags, symbolStack) { writePunctuation(writer, 16 /* OpenParenToken */); for (var i = 0; i < parameters.length; i++) { if (i > 0) { writePunctuation(writer, 23 /* CommaToken */); writeSpace(writer); } - buildParameterDisplay(parameters[i], writer, enclosingDeclaration, flags, typeStack); + buildParameterDisplay(parameters[i], writer, enclosingDeclaration, flags, symbolStack); } writePunctuation(writer, 17 /* CloseParenToken */); } - function buildReturnTypeDisplay(signature, writer, enclosingDeclaration, flags, typeStack) { + function buildReturnTypeDisplay(signature, writer, enclosingDeclaration, flags, symbolStack) { if (flags & 8 /* WriteArrowStyleSignature */) { writeSpace(writer); writePunctuation(writer, 32 /* EqualsGreaterThanToken */); @@ -12415,19 +13855,19 @@ var ts; writePunctuation(writer, 51 /* ColonToken */); } writeSpace(writer); - buildTypeDisplay(getReturnTypeOfSignature(signature), writer, enclosingDeclaration, flags, typeStack); + buildTypeDisplay(getReturnTypeOfSignature(signature), writer, enclosingDeclaration, flags, symbolStack); } - function buildSignatureDisplay(signature, writer, enclosingDeclaration, flags, typeStack) { + function buildSignatureDisplay(signature, writer, enclosingDeclaration, flags, symbolStack) { 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, typeStack); + buildDisplayForTypeParametersAndDelimiters(signature.typeParameters, writer, enclosingDeclaration, flags, symbolStack); } - buildDisplayForParametersAndDelimiters(signature.parameters, writer, enclosingDeclaration, flags, typeStack); - buildReturnTypeDisplay(signature, writer, enclosingDeclaration, flags, typeStack); + buildDisplayForParametersAndDelimiters(signature.parameters, writer, enclosingDeclaration, flags, symbolStack); + buildReturnTypeDisplay(signature, writer, enclosingDeclaration, flags, symbolStack); } return _displayBuilder || (_displayBuilder = { symbolToString: symbolToString, @@ -12447,12 +13887,12 @@ var ts; function isDeclarationVisible(node) { function getContainingExternalModule(node) { for (; node; node = node.parent) { - if (node.kind === 206 /* ModuleDeclaration */) { + if (node.kind === 208 /* ModuleDeclaration */) { if (node.name.kind === 8 /* StringLiteral */) { return node; } } - else if (node.kind === 228 /* SourceFile */) { + else if (node.kind === 230 /* SourceFile */) { return ts.isExternalModule(node) ? node : undefined; } } @@ -12501,69 +13941,69 @@ var ts; } function determineIfDeclarationIsVisible() { switch (node.kind) { - case 153 /* BindingElement */: + case 155 /* BindingElement */: return isDeclarationVisible(node.parent.parent); - case 199 /* VariableDeclaration */: + case 201 /* VariableDeclaration */: if (ts.isBindingPattern(node.name) && !node.name.elements.length) { // If the binding pattern is empty, this variable declaration is not visible return false; } // Otherwise fall through - case 206 /* ModuleDeclaration */: - case 202 /* ClassDeclaration */: - case 203 /* InterfaceDeclaration */: - case 204 /* TypeAliasDeclaration */: - case 201 /* FunctionDeclaration */: - case 205 /* EnumDeclaration */: - case 209 /* ImportEqualsDeclaration */: - var parent_2 = getDeclarationContainer(node); + case 208 /* ModuleDeclaration */: + case 204 /* ClassDeclaration */: + case 205 /* InterfaceDeclaration */: + case 206 /* TypeAliasDeclaration */: + case 203 /* FunctionDeclaration */: + case 207 /* EnumDeclaration */: + case 211 /* ImportEqualsDeclaration */: + var parent_4 = getDeclarationContainer(node); // If the node is not exported or it is not ambient module element (except import declaration) if (!(ts.getCombinedNodeFlags(node) & 1 /* Export */) && - !(node.kind !== 209 /* ImportEqualsDeclaration */ && parent_2.kind !== 228 /* SourceFile */ && ts.isInAmbientContext(parent_2))) { - return isGlobalSourceFile(parent_2); + !(node.kind !== 211 /* ImportEqualsDeclaration */ && parent_4.kind !== 230 /* SourceFile */ && ts.isInAmbientContext(parent_4))) { + return isGlobalSourceFile(parent_4); } // Exported members/ambient module elements (exception import declaration) are visible if parent is visible - return isDeclarationVisible(parent_2); - case 133 /* PropertyDeclaration */: - case 132 /* PropertySignature */: - case 137 /* GetAccessor */: - case 138 /* SetAccessor */: - case 135 /* MethodDeclaration */: - case 134 /* MethodSignature */: + return isDeclarationVisible(parent_4); + case 134 /* PropertyDeclaration */: + case 133 /* PropertySignature */: + case 138 /* GetAccessor */: + case 139 /* SetAccessor */: + case 136 /* MethodDeclaration */: + case 135 /* MethodSignature */: if (node.flags & (32 /* Private */ | 64 /* Protected */)) { // Private/protected properties/methods are not visible return false; } // Public properties/methods are visible if its parents are visible, so let it fall into next case statement - case 136 /* Constructor */: - case 140 /* ConstructSignature */: - case 139 /* CallSignature */: - case 141 /* IndexSignature */: - case 130 /* Parameter */: - case 207 /* ModuleBlock */: - case 143 /* FunctionType */: - case 144 /* ConstructorType */: - case 146 /* TypeLiteral */: - case 142 /* TypeReference */: - case 147 /* ArrayType */: - case 148 /* TupleType */: - case 149 /* UnionType */: - case 150 /* ParenthesizedType */: + case 137 /* Constructor */: + case 141 /* ConstructSignature */: + case 140 /* CallSignature */: + case 142 /* IndexSignature */: + case 131 /* Parameter */: + case 209 /* ModuleBlock */: + case 145 /* FunctionType */: + case 146 /* ConstructorType */: + case 148 /* TypeLiteral */: + case 144 /* TypeReference */: + case 149 /* ArrayType */: + case 150 /* TupleType */: + case 151 /* UnionType */: + case 152 /* 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 211 /* ImportClause */: - case 212 /* NamespaceImport */: - case 214 /* ImportSpecifier */: + case 213 /* ImportClause */: + case 214 /* NamespaceImport */: + case 216 /* ImportSpecifier */: return false; // Type parameters are always visible - case 129 /* TypeParameter */: + case 130 /* TypeParameter */: // Source file is always visible - case 228 /* SourceFile */: + case 230 /* SourceFile */: return true; // Export assignements do not create name bindings outside the module - case 215 /* ExportAssignment */: + case 217 /* ExportAssignment */: return false; default: ts.Debug.fail("isDeclarationVisible unknown: SyntaxKind: " + node.kind); @@ -12579,10 +14019,10 @@ var ts; } function collectLinkedAliases(node) { var exportSymbol; - if (node.parent && node.parent.kind === 215 /* ExportAssignment */) { + if (node.parent && node.parent.kind === 217 /* ExportAssignment */) { exportSymbol = resolveName(node.parent, node.text, 107455 /* Value */ | 793056 /* Type */ | 1536 /* Namespace */, ts.Diagnostics.Cannot_find_name_0, node); } - else if (node.parent.kind === 218 /* ExportSpecifier */) { + else if (node.parent.kind === 220 /* ExportSpecifier */) { exportSymbol = getTargetOfExportSpecifier(node.parent); } var result = []; @@ -12640,7 +14080,7 @@ var ts; node = ts.getRootDeclaration(node); // Parent chain: // VaribleDeclaration -> VariableDeclarationList -> VariableStatement -> 'Declaration Container' - return node.kind === 199 /* VariableDeclaration */ ? node.parent.parent.parent : node.parent; + return node.kind === 201 /* VariableDeclaration */ ? node.parent.parent.parent : node.parent; } function getTypeOfPrototypeProperty(prototype) { // TypeScript 1.0 spec (April 2014): 8.4 @@ -12655,6 +14095,9 @@ var ts; var prop = getPropertyOfType(type, name); return prop ? getTypeOfSymbol(prop) : undefined; } + function isTypeAny(type) { + return type && (type.flags & 1 /* Any */) !== 0; + } // Return the inferred type for a binding element function getTypeForBindingElement(declaration) { var pattern = declaration.parent; @@ -12666,23 +14109,23 @@ var ts; // 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 || parentType === anyType) { + if (!parentType || isTypeAny(parentType)) { if (declaration.initializer) { return checkExpressionCached(declaration.initializer); } return parentType; } var type; - if (pattern.kind === 151 /* ObjectBindingPattern */) { + if (pattern.kind === 153 /* ObjectBindingPattern */) { // Use explicitly specified property name ({ p: xxx } form), or otherwise the implied name ({ p } form) - var name_5 = declaration.propertyName || declaration.name; + var name_9 = declaration.propertyName || declaration.name; // 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. - type = getTypeOfPropertyOfType(parentType, name_5.text) || - isNumericLiteralName(name_5.text) && getIndexTypeOfType(parentType, 1 /* Number */) || + type = getTypeOfPropertyOfType(parentType, name_9.text) || + isNumericLiteralName(name_9.text) && getIndexTypeOfType(parentType, 1 /* Number */) || getIndexTypeOfType(parentType, 0 /* String */); if (!type) { - error(name_5, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(parentType), ts.declarationNameToString(name_5)); + error(name_9, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(parentType), ts.declarationNameToString(name_9)); return unknownType; } } @@ -12692,7 +14135,7 @@ var ts; // fact an iterable or array (depending on target language). var elementType = checkIteratedTypeOrElementType(parentType, pattern, false); if (!declaration.dotDotDotToken) { - if (elementType.flags & 1 /* Any */) { + if (isTypeAny(elementType)) { return elementType; } // Use specific property type when parent is a tuple or numeric index type when parent is an array @@ -12720,14 +14163,14 @@ var ts; // Return the inferred type for a variable, parameter, or property declaration function getTypeForVariableLikeDeclaration(declaration) { // A variable declared in a for..in statement is always of type any - if (declaration.parent.parent.kind === 188 /* ForInStatement */) { + if (declaration.parent.parent.kind === 190 /* ForInStatement */) { return anyType; } - if (declaration.parent.parent.kind === 189 /* ForOfStatement */) { + if (declaration.parent.parent.kind === 191 /* 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 getIteratedType. + // or it may have led to an error inside getElementTypeOfIterable. return checkRightHandSideOfForOf(declaration.parent.parent.expression) || anyType; } if (ts.isBindingPattern(declaration.parent)) { @@ -12737,11 +14180,11 @@ var ts; if (declaration.type) { return getTypeFromTypeNode(declaration.type); } - if (declaration.kind === 130 /* Parameter */) { + if (declaration.kind === 131 /* 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 === 138 /* SetAccessor */ && !ts.hasDynamicName(func)) { - var getter = ts.getDeclarationOfKind(declaration.parent.symbol, 137 /* GetAccessor */); + if (func.kind === 139 /* SetAccessor */ && !ts.hasDynamicName(func)) { + var getter = ts.getDeclarationOfKind(declaration.parent.symbol, 138 /* GetAccessor */); if (getter) { return getReturnTypeOfSignature(getSignatureFromDeclaration(getter)); } @@ -12757,7 +14200,7 @@ var ts; return checkExpressionCached(declaration.initializer); } // If it is a short-hand property assignment, use the type of the identifier - if (declaration.kind === 226 /* ShorthandPropertyAssignment */) { + if (declaration.kind === 228 /* ShorthandPropertyAssignment */) { return checkIdentifier(declaration.name); } // No type specified and nothing can be inferred @@ -12792,7 +14235,7 @@ var ts; var hasSpreadElement = false; var elementTypes = []; ts.forEach(pattern.elements, function (e) { - elementTypes.push(e.kind === 176 /* OmittedExpression */ || e.dotDotDotToken ? anyType : getTypeFromBindingElement(e)); + elementTypes.push(e.kind === 178 /* OmittedExpression */ || e.dotDotDotToken ? anyType : getTypeFromBindingElement(e)); if (e.dotDotDotToken) { hasSpreadElement = true; } @@ -12815,7 +14258,7 @@ var ts; // parameter with no type annotation or initializer, the type implied by the binding pattern becomes the type of // the parameter. function getTypeFromBindingPattern(pattern) { - return pattern.kind === 151 /* ObjectBindingPattern */ + return pattern.kind === 153 /* ObjectBindingPattern */ ? getTypeFromObjectBindingPattern(pattern) : getTypeFromArrayBindingPattern(pattern); } @@ -12837,7 +14280,7 @@ var ts; // 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. - return declaration.kind !== 225 /* PropertyAssignment */ ? getWidenedType(type) : type; + return declaration.kind !== 227 /* PropertyAssignment */ ? getWidenedType(type) : type; } // If no type was specified and nothing could be inferred, and if the declaration specifies a binding pattern, use // the type implied by the binding pattern @@ -12849,7 +14292,7 @@ var ts; // Report implicit any errors unless this is a private property within an ambient declaration if (reportErrors && compilerOptions.noImplicitAny) { var root = ts.getRootDeclaration(declaration); - if (!isPrivateWithinAmbient(root) && !(root.kind === 130 /* Parameter */ && isPrivateWithinAmbient(root.parent))) { + if (!isPrivateWithinAmbient(root) && !(root.kind === 131 /* Parameter */ && isPrivateWithinAmbient(root.parent))) { reportImplicitAnyError(declaration, type); } } @@ -12864,11 +14307,11 @@ var ts; } // Handle catch clause variables var declaration = symbol.valueDeclaration; - if (declaration.parent.kind === 224 /* CatchClause */) { + if (declaration.parent.kind === 226 /* CatchClause */) { return links.type = anyType; } // Handle export default expressions - if (declaration.kind === 215 /* ExportAssignment */) { + if (declaration.kind === 217 /* ExportAssignment */) { return links.type = checkExpression(declaration.expression); } // Handle variable, parameter or property @@ -12886,7 +14329,7 @@ var ts; // Variable has initializer that circularly references the variable itself type = anyType; if (compilerOptions.noImplicitAny) { - error(symbol.valueDeclaration, ts.Diagnostics._0_implicitly_has_type_any_because_it_is_does_not_have_a_type_annotation_and_is_referenced_directly_or_indirectly_in_its_own_initializer, symbolToString(symbol)); + 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)); } } } @@ -12899,7 +14342,7 @@ var ts; } function getAnnotatedAccessorType(accessor) { if (accessor) { - if (accessor.kind === 137 /* GetAccessor */) { + if (accessor.kind === 138 /* GetAccessor */) { return accessor.type && getTypeFromTypeNode(accessor.type); } else { @@ -12915,8 +14358,8 @@ var ts; if (!pushTypeResolution(symbol)) { return unknownType; } - var getter = ts.getDeclarationOfKind(symbol, 137 /* GetAccessor */); - var setter = ts.getDeclarationOfKind(symbol, 138 /* SetAccessor */); + var getter = ts.getDeclarationOfKind(symbol, 138 /* GetAccessor */); + var setter = ts.getDeclarationOfKind(symbol, 139 /* SetAccessor */); var type; // First try to see if the user specified a return type on the get-accessor. var getterReturnType = getAnnotatedAccessorType(getter); @@ -12945,7 +14388,7 @@ var ts; if (!popTypeResolution()) { type = anyType; if (compilerOptions.noImplicitAny) { - var getter_1 = ts.getDeclarationOfKind(symbol, 137 /* GetAccessor */); + var getter_1 = ts.getDeclarationOfKind(symbol, 138 /* 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)); } } @@ -13020,77 +14463,180 @@ var ts; return target === checkBase || ts.forEach(getBaseTypes(target), check); } } - // Return combined list of type parameters from all declarations of a class or interface. Elsewhere we check they're all - // the same, but even if they're not we still need the complete list to ensure instantiations supply type arguments - // for all type parameters. - function getTypeParametersOfClassOrInterface(symbol) { - var result; - ts.forEach(symbol.declarations, function (node) { - if (node.kind === 203 /* InterfaceDeclaration */ || node.kind === 202 /* ClassDeclaration */) { - var declaration = node; - if (declaration.typeParameters && declaration.typeParameters.length) { - ts.forEach(declaration.typeParameters, function (node) { - var tp = getDeclaredTypeOfTypeParameter(getSymbolOfNode(node)); - if (!result) { - result = [tp]; - } - else if (!ts.contains(result, tp)) { - result.push(tp); - } - }); + // 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; _i < declarations.length; _i++) { + var declaration = declarations[_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 === 204 /* ClassDeclaration */ || node.kind === 203 /* FunctionDeclaration */ || + node.kind === 165 /* FunctionExpression */ || node.kind === 136 /* MethodDeclaration */ || + node.kind === 166 /* 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 kind = symbol.flags & 32 /* Class */ ? 204 /* ClassDeclaration */ : 205 /* InterfaceDeclaration */; + return appendOuterTypeParameters(undefined, ts.getDeclarationOfKind(symbol, kind)); + } + // 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 === 205 /* InterfaceDeclaration */ || node.kind === 204 /* ClassDeclaration */ || node.kind === 206 /* 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)); + } + function isConstructorType(type) { + return type.flags & 48128 /* ObjectType */ && getSignaturesOfType(type, 1 /* Construct */).length > 0; + } + function getBaseTypeNodeOfClass(type) { + return ts.getClassExtendsHeritageClauseElement(type.symbol.valueDeclaration); + } + function getConstructorsForTypeArguments(type, typeArgumentNodes) { + var typeArgCount = typeArgumentNodes ? typeArgumentNodes.length : 0; + return ts.filter(getSignaturesOfType(type, 1 /* Construct */), function (sig) { return (sig.typeParameters ? sig.typeParameters.length : 0) === typeArgCount; }); + } + function getInstantiatedConstructorsForTypeArguments(type, typeArgumentNodes) { + var signatures = getConstructorsForTypeArguments(type, typeArgumentNodes); + if (typeArgumentNodes) { + var typeArguments = ts.map(typeArgumentNodes, getTypeFromTypeNode); + signatures = ts.map(signatures, function (sig) { return getSignatureInstantiation(sig, typeArguments); }); + } + 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, 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)) { + return unknownType; + } + var baseConstructorType = checkExpression(baseTypeNode.expression); + if (baseConstructorType.flags & 48128 /* ObjectType */) { + // 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. + resolveObjectOrUnionTypeMembers(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 !== unknownType && baseConstructorType !== nullType && !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) { - var typeWithBaseTypes = type; - if (!typeWithBaseTypes.baseTypes) { + if (!type.resolvedBaseTypes) { if (type.symbol.flags & 32 /* Class */) { - resolveBaseTypesOfClass(typeWithBaseTypes); + resolveBaseTypesOfClass(type); } else if (type.symbol.flags & 64 /* Interface */) { - resolveBaseTypesOfInterface(typeWithBaseTypes); + resolveBaseTypesOfInterface(type); } else { ts.Debug.fail("type must be class or interface"); } } - return typeWithBaseTypes.baseTypes; + return type.resolvedBaseTypes; } function resolveBaseTypesOfClass(type) { - type.baseTypes = []; - var declaration = ts.getDeclarationOfKind(type.symbol, 202 /* ClassDeclaration */); - var baseTypeNode = ts.getClassExtendsHeritageClauseElement(declaration); - if (baseTypeNode) { - var baseType = getTypeFromTypeNode(baseTypeNode); - if (baseType !== unknownType) { - if (getTargetType(baseType).flags & 1024 /* Class */) { - if (type !== baseType && !hasBaseType(baseType, type)) { - type.baseTypes.push(baseType); - } - else { - error(declaration, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, undefined, 1 /* WriteArrayAsGenericType */)); - } - } - else { - error(baseTypeNode, ts.Diagnostics.A_class_may_only_extend_another_class); - } - } + type.resolvedBaseTypes = emptyArray; + var baseContructorType = getBaseConstructorTypeOfClass(type); + if (!(baseContructorType.flags & 48128 /* ObjectType */)) { + return; } + var baseTypeNode = getBaseTypeNodeOfClass(type); + var baseType; + if (baseContructorType.symbol && baseContructorType.symbol.flags & 32 /* Class */) { + // When base constructor type is a class 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, baseContructorType.symbol); + } + 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(baseContructorType, baseTypeNode.typeArguments); + if (!constructors.length) { + error(baseTypeNode.expression, ts.Diagnostics.No_base_constructor_has_the_specified_number_of_type_arguments); + return; + } + baseType = getReturnTypeOfSignature(constructors[0]); + } + if (baseType === unknownType) { + return; + } + if (!(getTargetType(baseType).flags & (1024 /* Class */ | 2048 /* Interface */))) { + 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(type.symbol.valueDeclaration, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, undefined, 1 /* WriteArrayAsGenericType */)); + return; + } + type.resolvedBaseTypes = [baseType]; } function resolveBaseTypesOfInterface(type) { - type.baseTypes = []; + type.resolvedBaseTypes = []; for (var _i = 0, _a = type.symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (declaration.kind === 203 /* InterfaceDeclaration */ && ts.getInterfaceBaseTypeNodes(declaration)) { + if (declaration.kind === 205 /* 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 (getTargetType(baseType).flags & (1024 /* Class */ | 2048 /* Interface */)) { if (type !== baseType && !hasBaseType(baseType, type)) { - type.baseTypes.push(baseType); + type.resolvedBaseTypes.push(baseType); } else { error(declaration, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, undefined, 1 /* WriteArrayAsGenericType */)); @@ -13109,10 +14655,13 @@ var ts; if (!links.declaredType) { var kind = symbol.flags & 32 /* Class */ ? 1024 /* Class */ : 2048 /* Interface */; var type = links.declaredType = createObjectType(kind, symbol); - var typeParameters = getTypeParametersOfClassOrInterface(symbol); - if (typeParameters) { + var outerTypeParameters = getOuterTypeParametersOfClassOrInterface(symbol); + var localTypeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); + if (outerTypeParameters || localTypeParameters) { type.flags |= 4096 /* Reference */; - type.typeParameters = typeParameters; + type.typeParameters = ts.concatenate(outerTypeParameters, localTypeParameters); + type.outerTypeParameters = outerTypeParameters; + type.localTypeParameters = localTypeParameters; type.instantiations = {}; type.instantiations[getTypeListId(type.typeParameters)] = type; type.target = type; @@ -13129,9 +14678,18 @@ var ts; if (!pushTypeResolution(links)) { return unknownType; } - var declaration = ts.getDeclarationOfKind(symbol, 204 /* TypeAliasDeclaration */); + var declaration = ts.getDeclarationOfKind(symbol, 206 /* TypeAliasDeclaration */); var type = getTypeFromTypeNode(declaration.type); - if (!popTypeResolution()) { + if (popTypeResolution()) { + links.typeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); + if (links.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.instantiations = {}; + links.instantiations[getTypeListId(links.typeParameters)] = type; + } + } + else { type = unknownType; error(declaration.name, ts.Diagnostics.Type_alias_0_circularly_references_itself, symbolToString(symbol)); } @@ -13153,7 +14711,7 @@ var ts; if (!links.declaredType) { var type = createType(512 /* TypeParameter */); type.symbol = symbol; - if (!ts.getDeclarationOfKind(symbol, 129 /* TypeParameter */).constraint) { + if (!ts.getDeclarationOfKind(symbol, 130 /* TypeParameter */).constraint) { type.constraint = noConstraintType; } links.declaredType = type; @@ -13268,34 +14826,42 @@ var ts; }); setObjectTypeMembers(type, members, callSignatures, constructSignatures, stringIndexType, numberIndexType); } - function createSignature(declaration, typeParameters, parameters, resolvedReturnType, minArgumentCount, hasRestParameter, hasStringLiterals) { + function createSignature(declaration, typeParameters, parameters, resolvedReturnType, typePredicate, minArgumentCount, hasRestParameter, hasStringLiterals) { var sig = new Signature(checker); sig.declaration = declaration; sig.typeParameters = typeParameters; sig.parameters = parameters; sig.resolvedReturnType = resolvedReturnType; + sig.typePredicate = typePredicate; sig.minArgumentCount = minArgumentCount; sig.hasRestParameter = hasRestParameter; sig.hasStringLiterals = hasStringLiterals; return sig; } function cloneSignature(sig) { - return createSignature(sig.declaration, sig.typeParameters, sig.parameters, sig.resolvedReturnType, sig.minArgumentCount, sig.hasRestParameter, sig.hasStringLiterals); + return createSignature(sig.declaration, sig.typeParameters, sig.parameters, sig.resolvedReturnType, sig.typePredicate, sig.minArgumentCount, sig.hasRestParameter, sig.hasStringLiterals); } function getDefaultConstructSignatures(classType) { - var baseTypes = getBaseTypes(classType); - if (baseTypes.length) { - var baseType = baseTypes[0]; - var baseSignatures = getSignaturesOfType(getTypeOfSymbol(baseType.symbol), 1 /* Construct */); - return ts.map(baseSignatures, function (baseSignature) { - var signature = baseType.flags & 4096 /* Reference */ ? - getSignatureInstantiation(baseSignature, baseType.typeArguments) : cloneSignature(baseSignature); - signature.typeParameters = classType.typeParameters; - signature.resolvedReturnType = classType; - return signature; - }); + if (!getBaseTypes(classType).length) { + return [createSignature(undefined, classType.localTypeParameters, emptyArray, classType, undefined, 0, false, false)]; } - return [createSignature(undefined, classType.typeParameters, emptyArray, classType, 0, false, false)]; + var baseConstructorType = getBaseConstructorTypeOfClass(classType); + var baseSignatures = getSignaturesOfType(baseConstructorType, 1 /* Construct */); + var baseTypeNode = getBaseTypeNodeOfClass(classType); + var typeArguments = ts.map(baseTypeNode.typeArguments, getTypeFromTypeNode); + var typeArgCount = typeArguments ? typeArguments.length : 0; + var result = []; + for (var _i = 0; _i < baseSignatures.length; _i++) { + var baseSig = baseSignatures[_i]; + var typeParamCount = baseSig.typeParameters ? baseSig.typeParameters.length : 0; + if (typeParamCount === typeArgCount) { + var sig = typeParamCount ? getSignatureInstantiation(baseSig, typeArguments) : cloneSignature(baseSig); + sig.typeParameters = classType.localTypeParameters; + sig.resolvedReturnType = classType; + result.push(sig); + } + } + return result; } function createTupleTypeMemberSymbols(memberTypes) { var members = {}; @@ -13401,10 +14967,10 @@ var ts; if (!constructSignatures.length) { constructSignatures = getDefaultConstructSignatures(classType); } - var baseTypes = getBaseTypes(classType); - if (baseTypes.length) { + var baseConstructorType = getBaseConstructorTypeOfClass(classType); + if (baseConstructorType.flags & 48128 /* ObjectType */) { members = createSymbolTable(getNamedMembers(members)); - addInheritedMembers(members, getPropertiesOfObjectType(getTypeOfSymbol(baseTypes[0].symbol))); + addInheritedMembers(members, getPropertiesOfObjectType(baseConstructorType)); } } stringIndexType = undefined; @@ -13490,7 +15056,7 @@ var ts; else if (type.flags & 8 /* Boolean */) { type = globalBooleanType; } - else if (type.flags & 1048576 /* ESSymbol */) { + else if (type.flags & 2097152 /* ESSymbol */) { type = globalESSymbolType; } return type; @@ -13619,11 +15185,14 @@ var ts; } return result; } + function isOptionalParameter(node) { + return ts.hasQuestionToken(node) || !!node.initializer; + } function getSignatureFromDeclaration(declaration) { var links = getNodeLinks(declaration); if (!links.resolvedSignature) { - var classType = declaration.kind === 136 /* Constructor */ ? getDeclaredTypeOfClassOrInterface(declaration.parent.symbol) : undefined; - var typeParameters = classType ? classType.typeParameters : + var classType = declaration.kind === 137 /* Constructor */ ? getDeclaredTypeOfClassOrInterface(declaration.parent.symbol) : undefined; + var typeParameters = classType ? classType.localTypeParameters : declaration.typeParameters ? getTypeParametersFromDeclaration(declaration.typeParameters) : undefined; var parameters = []; var hasStringLiterals = false; @@ -13644,24 +15213,33 @@ var ts; minArgumentCount = declaration.parameters.length; } var returnType; + var typePredicate; if (classType) { returnType = classType; } else if (declaration.type) { returnType = getTypeFromTypeNode(declaration.type); + if (declaration.type.kind === 143 /* TypePredicate */) { + var typePredicateNode = declaration.type; + typePredicate = { + parameterName: typePredicateNode.parameterName ? typePredicateNode.parameterName.text : undefined, + parameterIndex: typePredicateNode.parameterName ? getTypePredicateParameterIndex(declaration.parameters, typePredicateNode.parameterName) : undefined, + type: getTypeFromTypeNode(typePredicateNode.type) + }; + } } else { // 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 === 137 /* GetAccessor */ && !ts.hasDynamicName(declaration)) { - var setter = ts.getDeclarationOfKind(declaration.symbol, 138 /* SetAccessor */); + if (declaration.kind === 138 /* GetAccessor */ && !ts.hasDynamicName(declaration)) { + var setter = ts.getDeclarationOfKind(declaration.symbol, 139 /* SetAccessor */); returnType = getAnnotatedAccessorType(setter); } if (!returnType && ts.nodeIsMissing(declaration.body)) { returnType = anyType; } } - links.resolvedSignature = createSignature(declaration, typeParameters, parameters, returnType, minArgumentCount, ts.hasRestParameters(declaration), hasStringLiterals); + links.resolvedSignature = createSignature(declaration, typeParameters, parameters, returnType, typePredicate, minArgumentCount, ts.hasRestParameter(declaration), hasStringLiterals); } return links.resolvedSignature; } @@ -13672,19 +15250,19 @@ var ts; for (var i = 0, len = symbol.declarations.length; i < len; i++) { var node = symbol.declarations[i]; switch (node.kind) { - case 143 /* FunctionType */: - case 144 /* ConstructorType */: - case 201 /* FunctionDeclaration */: - case 135 /* MethodDeclaration */: - case 134 /* MethodSignature */: - case 136 /* Constructor */: - case 139 /* CallSignature */: - case 140 /* ConstructSignature */: - case 141 /* IndexSignature */: - case 137 /* GetAccessor */: - case 138 /* SetAccessor */: - case 163 /* FunctionExpression */: - case 164 /* ArrowFunction */: + case 145 /* FunctionType */: + case 146 /* ConstructorType */: + case 203 /* FunctionDeclaration */: + case 136 /* MethodDeclaration */: + case 135 /* MethodSignature */: + case 137 /* Constructor */: + case 140 /* CallSignature */: + case 141 /* ConstructSignature */: + case 142 /* IndexSignature */: + case 138 /* GetAccessor */: + case 139 /* SetAccessor */: + case 165 /* FunctionExpression */: + case 166 /* ArrowFunction */: // 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). @@ -13761,8 +15339,8 @@ var ts; // 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 === 136 /* Constructor */ || signature.declaration.kind === 140 /* ConstructSignature */; - var type = createObjectType(32768 /* Anonymous */ | 65536 /* FromSignature */); + var isConstructor = signature.declaration.kind === 137 /* Constructor */ || signature.declaration.kind === 141 /* ConstructSignature */; + var type = createObjectType(32768 /* Anonymous */ | 131072 /* FromSignature */); type.members = emptySymbols; type.properties = emptyArray; type.callSignatures = !isConstructor ? [signature] : emptyArray; @@ -13775,7 +15353,7 @@ var ts; return symbol.members["__index"]; } function getIndexDeclarationOfSymbol(symbol, kind) { - var syntaxKind = kind === 1 /* Number */ ? 120 /* NumberKeyword */ : 122 /* StringKeyword */; + var syntaxKind = kind === 1 /* Number */ ? 121 /* NumberKeyword */ : 123 /* StringKeyword */; var indexSymbol = getIndexSymbol(symbol); if (indexSymbol) { var len = indexSymbol.declarations.length; @@ -13805,11 +15383,14 @@ var ts; type.constraint = targetConstraint ? instantiateType(targetConstraint, type.mapper) : noConstraintType; } else { - type.constraint = getTypeFromTypeNode(ts.getDeclarationOfKind(type.symbol, 129 /* TypeParameter */).constraint); + type.constraint = getTypeFromTypeNode(ts.getDeclarationOfKind(type.symbol, 130 /* TypeParameter */).constraint); } } return type.constraint === noConstraintType ? undefined : type.constraint; } + function getParentSymbolOfTypeParameter(typeParameter) { + return getSymbolOfNode(ts.getDeclarationOfKind(typeParameter.symbol, 130 /* TypeParameter */).parent); + } function getTypeListId(types) { switch (types.length) { case 1: @@ -13836,7 +15417,7 @@ var ts; var type = types[_i]; result |= type.flags; } - return result & 786432 /* RequiresWidening */; + return result & 1572864 /* RequiresWidening */; } function createTypeReference(target, typeArguments) { var id = getTypeListId(typeArguments); @@ -13861,13 +15442,13 @@ var ts; currentNode = currentNode.parent; } // if last step was made from the type parameter this means that path has started somewhere in constraint which is illegal - links.isIllegalTypeReferenceInConstraint = currentNode.kind === 129 /* TypeParameter */; + links.isIllegalTypeReferenceInConstraint = currentNode.kind === 130 /* TypeParameter */; return links.isIllegalTypeReferenceInConstraint; } function checkTypeParameterHasIllegalReferencesInConstraint(typeParameter) { var typeParameterSymbol; function check(n) { - if (n.kind === 142 /* TypeReference */ && n.typeName.kind === 65 /* Identifier */) { + if (n.kind === 144 /* TypeReference */ && n.typeName.kind === 65 /* Identifier */) { var links = getNodeLinks(n); if (links.isIllegalTypeReferenceInConstraint === undefined) { var symbol = resolveName(typeParameter, n.typeName.text, 793056 /* Type */, undefined, undefined); @@ -13879,7 +15460,7 @@ var ts; // -> typeParameter and symbol.declaration originate from the same type parameter list // -> illegal for all declarations in symbol // forEach === exists - links.isIllegalTypeReferenceInConstraint = ts.forEach(symbol.declarations, function (d) { return d.parent == typeParameter.parent; }); + links.isIllegalTypeReferenceInConstraint = ts.forEach(symbol.declarations, function (d) { return d.parent === typeParameter.parent; }); } } if (links.isIllegalTypeReferenceInConstraint) { @@ -13893,47 +15474,79 @@ var ts; check(typeParameter.constraint); } } - function getTypeFromTypeReferenceOrExpressionWithTypeArguments(node) { + // Get type from reference to class or interface + function getTypeFromClassOrInterfaceReference(node, symbol) { + var type = getDeclaredTypeOfSymbol(symbol); + var typeParameters = type.localTypeParameters; + if (typeParameters) { + if (!node.typeArguments || node.typeArguments.length !== typeParameters.length) { + error(node, ts.Diagnostics.Generic_type_0_requires_1_type_argument_s, typeToString(type, undefined, 1 /* WriteArrayAsGenericType */), 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. + return createTypeReference(type, ts.concatenate(type.outerTypeParameters, ts.map(node.typeArguments, getTypeFromTypeNode))); + } + if (node.typeArguments) { + error(node, ts.Diagnostics.Type_0_is_not_generic, typeToString(type)); + return unknownType; + } + return type; + } + // Get type from reference to type alias. When a type alias is generic, the declared type of the type alias may include + // references to the type parameters of the alias. We replace those with the actual type arguments by instantiating the + // declared type. Instantiations are cached using the type identities of the type arguments as the key. + function getTypeFromTypeAliasReference(node, symbol) { + var type = getDeclaredTypeOfSymbol(symbol); + var links = getSymbolLinks(symbol); + var typeParameters = links.typeParameters; + if (typeParameters) { + if (!node.typeArguments || node.typeArguments.length !== typeParameters.length) { + error(node, ts.Diagnostics.Generic_type_0_requires_1_type_argument_s, symbolToString(symbol), typeParameters.length); + return unknownType; + } + var typeArguments = ts.map(node.typeArguments, getTypeFromTypeNode); + var id = getTypeListId(typeArguments); + return links.instantiations[id] || (links.instantiations[id] = instantiateType(type, createTypeMapper(typeParameters, 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 (symbol.flags & 262144 /* TypeParameter */ && isTypeParameterReferenceIllegalInConstraint(node, symbol)) { + // TypeScript 1.0 spec (April 2014): 3.4.1 + // Type parameters declared in a particular type parameter list + // may not be referenced in constraints in that type parameter list + // Implementation: such type references are resolved to 'unknown' type that usually denotes error + return unknownType; + } + if (node.typeArguments) { + error(node, ts.Diagnostics.Type_0_is_not_generic, symbolToString(symbol)); + return unknownType; + } + return getDeclaredTypeOfSymbol(symbol); + } + function getTypeFromTypeReference(node) { var links = getNodeLinks(node); if (!links.resolvedType) { - var type; - // We don't currently support heritage clauses with complex expressions in them. - // For these cases, we just set the type to be the unknownType. - if (node.kind !== 177 /* ExpressionWithTypeArguments */ || ts.isSupportedExpressionWithTypeArguments(node)) { - var typeNameOrExpression = node.kind === 142 /* TypeReference */ - ? node.typeName - : node.expression; - var symbol = resolveEntityName(typeNameOrExpression, 793056 /* Type */); - if (symbol) { - if ((symbol.flags & 262144 /* TypeParameter */) && isTypeParameterReferenceIllegalInConstraint(node, symbol)) { - // TypeScript 1.0 spec (April 2014): 3.4.1 - // Type parameters declared in a particular type parameter list - // may not be referenced in constraints in that type parameter list - // Implementation: such type references are resolved to 'unknown' type that usually denotes error - type = unknownType; - } - else { - type = getDeclaredTypeOfSymbol(symbol); - if (type.flags & (1024 /* Class */ | 2048 /* Interface */) && type.flags & 4096 /* Reference */) { - var typeParameters = type.typeParameters; - if (node.typeArguments && node.typeArguments.length === typeParameters.length) { - type = createTypeReference(type, ts.map(node.typeArguments, getTypeFromTypeNode)); - } - else { - error(node, ts.Diagnostics.Generic_type_0_requires_1_type_argument_s, typeToString(type, undefined, 1 /* WriteArrayAsGenericType */), typeParameters.length); - type = undefined; - } - } - else { - if (node.typeArguments) { - error(node, ts.Diagnostics.Type_0_is_not_generic, typeToString(type)); - type = undefined; - } - } - } - } - } - links.resolvedType = type || unknownType; + // We only support expressions that are simple qualified names. For other expressions this produces undefined. + var typeNameOrExpression = node.kind === 144 /* TypeReference */ ? node.typeName : + ts.isSupportedExpressionWithTypeArguments(node) ? node.expression : + undefined; + var symbol = typeNameOrExpression && resolveEntityName(typeNameOrExpression, 793056 /* Type */) || unknownSymbol; + var type = symbol === unknownSymbol ? unknownType : + symbol.flags & (32 /* Class */ | 64 /* Interface */) ? getTypeFromClassOrInterfaceReference(node, symbol) : + symbol.flags & 524288 /* TypeAlias */ ? getTypeFromTypeAliasReference(node, symbol) : + getTypeFromNonGenericTypeReference(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; } @@ -13944,7 +15557,7 @@ var ts; // 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(checkExpressionOrQualifiedName(node.exprName)); + links.resolvedType = getWidenedType(checkExpression(node.exprName)); } return links.resolvedType; } @@ -13954,24 +15567,24 @@ var ts; for (var _i = 0; _i < declarations.length; _i++) { var declaration = declarations[_i]; switch (declaration.kind) { - case 202 /* ClassDeclaration */: - case 203 /* InterfaceDeclaration */: - case 205 /* EnumDeclaration */: + case 204 /* ClassDeclaration */: + case 205 /* InterfaceDeclaration */: + case 207 /* EnumDeclaration */: return declaration; } } } if (!symbol) { - return emptyObjectType; + return arity ? emptyGenericType : emptyObjectType; } var type = getDeclaredTypeOfSymbol(symbol); if (!(type.flags & 48128 /* ObjectType */)) { error(getTypeDeclaration(symbol), ts.Diagnostics.Global_type_0_must_be_a_class_or_interface_type, symbol.name); - return emptyObjectType; + return arity ? emptyGenericType : emptyObjectType; } if ((type.typeParameters ? type.typeParameters.length : 0) !== arity) { error(getTypeDeclaration(symbol), ts.Diagnostics.Global_type_0_must_have_1_type_parameter_s, symbol.name, arity); - return emptyObjectType; + return arity ? emptyGenericType : emptyObjectType; } return type; } @@ -13991,15 +15604,20 @@ var ts; function getGlobalESSymbolConstructorSymbol() { return globalESSymbolConstructorSymbol || (globalESSymbolConstructorSymbol = getGlobalValueSymbol("Symbol")); } + /** + * Instantiates a global type that is generic with some element type, and returns that instantiation. + */ + function createTypeFromGenericGlobalType(genericGlobalType, elementType) { + return genericGlobalType !== emptyGenericType ? createTypeReference(genericGlobalType, [elementType]) : emptyObjectType; + } function createIterableType(elementType) { - return globalIterableType !== emptyObjectType ? createTypeReference(globalIterableType, [elementType]) : emptyObjectType; + return createTypeFromGenericGlobalType(globalIterableType, elementType); + } + function createIterableIteratorType(elementType) { + return createTypeFromGenericGlobalType(globalIterableIteratorType, elementType); } function createArrayType(elementType) { - // globalArrayType will be undefined if we get here during creation of the Array type. This for example happens if - // user code augments the Array type with call or construct signatures that have an array type as the return type. - // We instead use globalArraySymbol to obtain the (not yet fully constructed) Array type. - var arrayType = globalArrayType || getDeclaredTypeOfSymbol(globalArraySymbol); - return arrayType !== emptyObjectType ? createTypeReference(arrayType, [elementType]) : emptyObjectType; + return createTypeFromGenericGlobalType(globalArrayType, elementType); } function getTypeFromArrayTypeNode(node) { var links = getNodeLinks(node); @@ -14054,17 +15672,7 @@ var ts; } return false; } - // Since removeSubtypes checks the subtype relation, and the subtype relation on a union - // may attempt to reduce a union, it is possible that removeSubtypes could be called - // recursively on the same set of types. The removeSubtypesStack is used to track which - // sets of types are currently undergoing subtype reduction. - var removeSubtypesStack = []; function removeSubtypes(types) { - var typeListId = getTypeListId(types); - if (removeSubtypesStack.lastIndexOf(typeListId) >= 0) { - return; - } - removeSubtypesStack.push(typeListId); var i = types.length; while (i > 0) { i--; @@ -14072,12 +15680,11 @@ var ts; types.splice(i, 1); } } - removeSubtypesStack.pop(); } - function containsAnyType(types) { + function containsTypeAny(types) { for (var _i = 0; _i < types.length; _i++) { var type = types[_i]; - if (type.flags & 1 /* Any */) { + if (isTypeAny(type)) { return true; } } @@ -14103,7 +15710,7 @@ var ts; var sortedTypes = []; addTypesToSortedSet(sortedTypes, types); if (noSubtypeReduction) { - if (containsAnyType(sortedTypes)) { + if (containsTypeAny(sortedTypes)) { return anyType; } removeAllButLast(sortedTypes, undefinedType); @@ -14124,10 +15731,20 @@ var ts; } return type; } + // Subtype reduction is basically an optimization we do to avoid excessively large union types, which take longer + // to process and look strange in quick info and error messages. Semantically there is no difference between the + // reduced type and the type itself. So, when we detect a circularity we simply say that the reduced type is the + // type itself. function getReducedTypeOfUnionType(type) { - // If union type was created without subtype reduction, perform the deferred reduction now if (!type.reducedType) { - type.reducedType = getUnionType(type.types, false); + type.reducedType = circularType; + var reducedType = getUnionType(type.types, false); + if (type.reducedType === circularType) { + type.reducedType = reducedType; + } + } + else if (type.reducedType === circularType) { + type.reducedType = type; } return type.reducedType; } @@ -14165,40 +15782,42 @@ var ts; switch (node.kind) { case 112 /* AnyKeyword */: return anyType; - case 122 /* StringKeyword */: + case 123 /* StringKeyword */: return stringType; - case 120 /* NumberKeyword */: + case 121 /* NumberKeyword */: return numberType; case 113 /* BooleanKeyword */: return booleanType; - case 123 /* SymbolKeyword */: + case 124 /* SymbolKeyword */: return esSymbolType; case 99 /* VoidKeyword */: return voidType; case 8 /* StringLiteral */: return getTypeFromStringLiteral(node); - case 142 /* TypeReference */: - return getTypeFromTypeReferenceOrExpressionWithTypeArguments(node); - case 177 /* ExpressionWithTypeArguments */: - return getTypeFromTypeReferenceOrExpressionWithTypeArguments(node); - case 145 /* TypeQuery */: + case 144 /* TypeReference */: + return getTypeFromTypeReference(node); + case 143 /* TypePredicate */: + return booleanType; + case 179 /* ExpressionWithTypeArguments */: + return getTypeFromTypeReference(node); + case 147 /* TypeQuery */: return getTypeFromTypeQueryNode(node); - case 147 /* ArrayType */: + case 149 /* ArrayType */: return getTypeFromArrayTypeNode(node); - case 148 /* TupleType */: + case 150 /* TupleType */: return getTypeFromTupleTypeNode(node); - case 149 /* UnionType */: + case 151 /* UnionType */: return getTypeFromUnionTypeNode(node); - case 150 /* ParenthesizedType */: + case 152 /* ParenthesizedType */: return getTypeFromTypeNode(node.type); - case 143 /* FunctionType */: - case 144 /* ConstructorType */: - case 146 /* TypeLiteral */: + case 145 /* FunctionType */: + case 146 /* ConstructorType */: + case 148 /* TypeLiteral */: return getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node); // This function assumes that an identifier or qualified name is a type expression // Callers should first ensure this by calling isTypeNode case 65 /* Identifier */: - case 127 /* QualifiedName */: + case 128 /* QualifiedName */: var symbol = getSymbolInfo(node); return symbol && getDeclaredTypeOfSymbol(symbol); default: @@ -14288,11 +15907,19 @@ var ts; } function instantiateSignature(signature, mapper, eraseTypeParameters) { var freshTypeParameters; + var freshTypePredicate; if (signature.typeParameters && !eraseTypeParameters) { freshTypeParameters = instantiateList(signature.typeParameters, mapper, instantiateTypeParameter); mapper = combineTypeMappers(createTypeMapper(signature.typeParameters, freshTypeParameters), mapper); } - var result = createSignature(signature.declaration, freshTypeParameters, instantiateList(signature.parameters, mapper, instantiateSymbol), signature.resolvedReturnType ? instantiateType(signature.resolvedReturnType, mapper) : undefined, signature.minArgumentCount, signature.hasRestParameter, signature.hasStringLiterals); + if (signature.typePredicate) { + freshTypePredicate = { + parameterName: signature.typePredicate.parameterName, + parameterIndex: signature.typePredicate.parameterIndex, + type: instantiateType(signature.typePredicate.type, mapper) + }; + } + var result = createSignature(signature.declaration, freshTypeParameters, instantiateList(signature.parameters, mapper, instantiateSymbol), signature.resolvedReturnType ? instantiateType(signature.resolvedReturnType, mapper) : undefined, freshTypePredicate, signature.minArgumentCount, signature.hasRestParameter, signature.hasStringLiterals); result.target = signature; result.mapper = mapper; return result; @@ -14319,7 +15946,8 @@ var ts; return result; } function instantiateAnonymousType(type, mapper) { - var result = createObjectType(32768 /* Anonymous */, type.symbol); + // Mark the anonymous type as instantiated such that our infinite instantiation detection logic can recognize it + var result = createObjectType(32768 /* Anonymous */ | 65536 /* Instantiated */, type.symbol); result.properties = instantiateList(getPropertiesOfObjectType(type), mapper, instantiateSymbol); result.members = createSymbolTable(result.properties); result.callSignatures = instantiateList(getSignaturesOfType(type, 0 /* Call */), mapper, instantiateSignature); @@ -14338,7 +15966,7 @@ var ts; return mapper(type); } if (type.flags & 32768 /* Anonymous */) { - return type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) ? + return type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) ? instantiateAnonymousType(type, mapper) : type; } if (type.flags & 4096 /* Reference */) { @@ -14356,27 +15984,27 @@ var ts; // Returns true if the given expression contains (at any level of nesting) a function or arrow expression // that is subject to contextual typing. function isContextSensitive(node) { - ts.Debug.assert(node.kind !== 135 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); + ts.Debug.assert(node.kind !== 136 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); switch (node.kind) { - case 163 /* FunctionExpression */: - case 164 /* ArrowFunction */: + case 165 /* FunctionExpression */: + case 166 /* ArrowFunction */: return isContextSensitiveFunctionLikeDeclaration(node); - case 155 /* ObjectLiteralExpression */: + case 157 /* ObjectLiteralExpression */: return ts.forEach(node.properties, isContextSensitive); - case 154 /* ArrayLiteralExpression */: + case 156 /* ArrayLiteralExpression */: return ts.forEach(node.elements, isContextSensitive); - case 171 /* ConditionalExpression */: + case 173 /* ConditionalExpression */: return isContextSensitive(node.whenTrue) || isContextSensitive(node.whenFalse); - case 170 /* BinaryExpression */: + case 172 /* BinaryExpression */: return node.operatorToken.kind === 49 /* BarBarToken */ && (isContextSensitive(node.left) || isContextSensitive(node.right)); - case 225 /* PropertyAssignment */: + case 227 /* PropertyAssignment */: return isContextSensitive(node.initializer); - case 135 /* MethodDeclaration */: - case 134 /* MethodSignature */: + case 136 /* MethodDeclaration */: + case 135 /* MethodSignature */: return isContextSensitiveFunctionLikeDeclaration(node); - case 162 /* ParenthesizedExpression */: + case 164 /* ParenthesizedExpression */: return isContextSensitive(node.expression); } return false; @@ -14384,14 +16012,14 @@ var ts; function isContextSensitiveFunctionLikeDeclaration(node) { return !node.typeParameters && node.parameters.length && !ts.forEach(node.parameters, function (p) { return p.type; }); } - function getTypeWithoutConstructors(type) { + function getTypeWithoutSignatures(type) { if (type.flags & 48128 /* ObjectType */) { var resolved = resolveObjectOrUnionTypeMembers(type); if (resolved.constructSignatures.length) { var result = createObjectType(32768 /* Anonymous */, type.symbol); result.members = resolved.members; result.properties = resolved.properties; - result.callSignatures = resolved.callSignatures; + result.callSignatures = emptyArray; result.constructSignatures = emptyArray; type = result; } @@ -14399,9 +16027,6 @@ var ts; return type; } // TYPE CHECKING - var subtypeRelation = {}; - var assignableRelation = {}; - var identityRelation = {}; function isTypeIdenticalTo(source, target) { return checkTypeRelatedTo(source, target, identityRelation, undefined); } @@ -14468,7 +16093,7 @@ var ts; if (source === target) return -1 /* True */; if (relation !== identityRelation) { - if (target.flags & 1 /* Any */) + if (isTypeAny(target)) return -1 /* True */; if (source === undefinedType) return -1 /* True */; @@ -14479,7 +16104,7 @@ var ts; if (source.flags & 256 /* StringLiteral */ && target === stringType) return -1 /* True */; if (relation === assignableRelation) { - if (source.flags & 1 /* Any */) + if (isTypeAny(source)) return -1 /* True */; if (source === numberType && target.flags & 128 /* Enum */) return -1 /* True */; @@ -14678,9 +16303,9 @@ var ts; maybeStack[depth][id] = 1 /* Succeeded */; depth++; var saveExpandingFlags = expandingFlags; - if (!(expandingFlags & 1) && isDeeplyNestedGeneric(source, sourceStack)) + if (!(expandingFlags & 1) && isDeeplyNestedGeneric(source, sourceStack, depth)) expandingFlags |= 1; - if (!(expandingFlags & 2) && isDeeplyNestedGeneric(target, targetStack)) + if (!(expandingFlags & 2) && isDeeplyNestedGeneric(target, targetStack, depth)) expandingFlags |= 2; var result; if (expandingFlags === 3) { @@ -14716,33 +16341,13 @@ var ts; } return result; } - // Return true if the given type is part of a deeply nested chain of generic instantiations. We consider this to be the case - // when structural type comparisons have been started for 10 or more instantiations of the same generic type. 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 10 levels, but unequal at - // some level beyond that. - function isDeeplyNestedGeneric(type, stack) { - if (type.flags & 4096 /* Reference */ && depth >= 10) { - var target_1 = type.target; - var count = 0; - for (var i = 0; i < depth; i++) { - var t = stack[i]; - if (t.flags & 4096 /* Reference */ && t.target === target_1) { - count++; - if (count >= 10) - return true; - } - } - } - return 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 && !(source.flags & 131072 /* ObjectLiteral */); + var requireOptionalProperties = relation === subtypeRelation && !(source.flags & 262144 /* ObjectLiteral */); for (var _i = 0; _i < properties.length; _i++) { var targetProp = properties[_i]; var sourceProp = getPropertyOfType(source, targetProp.name); @@ -14848,11 +16453,11 @@ var ts; var saveErrorInfo = errorInfo; outer: for (var _i = 0; _i < targetSignatures.length; _i++) { var t = targetSignatures[_i]; - if (!t.hasStringLiterals || target.flags & 65536 /* FromSignature */) { + if (!t.hasStringLiterals || target.flags & 131072 /* FromSignature */) { var localErrors = reportErrors; for (var _a = 0; _a < sourceSignatures.length; _a++) { var s = sourceSignatures[_a]; - if (!s.hasStringLiterals || source.flags & 65536 /* FromSignature */) { + if (!s.hasStringLiterals || source.flags & 131072 /* FromSignature */) { var related = signatureRelatedTo(s, t, localErrors); if (related) { result &= related; @@ -14916,6 +16521,33 @@ var ts; } result &= related; } + if (source.typePredicate && target.typePredicate) { + var hasDifferentParameterIndex = source.typePredicate.parameterIndex !== target.typePredicate.parameterIndex; + var hasDifferentTypes; + if (hasDifferentParameterIndex || + (hasDifferentTypes = !isTypeIdenticalTo(source.typePredicate.type, target.typePredicate.type))) { + if (reportErrors) { + var sourceParamText = source.typePredicate.parameterName; + var targetParamText = target.typePredicate.parameterName; + var sourceTypeText = typeToString(source.typePredicate.type); + var targetTypeText = typeToString(target.typePredicate.type); + if (hasDifferentParameterIndex) { + reportError(ts.Diagnostics.Parameter_0_is_not_in_the_same_position_as_parameter_1, sourceParamText, targetParamText); + } + else if (hasDifferentTypes) { + reportError(ts.Diagnostics.Type_0_is_not_assignable_to_type_1, sourceTypeText, targetTypeText); + } + reportError(ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1, sourceParamText + " is " + sourceTypeText, targetParamText + " is " + targetTypeText); + } + return 0 /* False */; + } + } + else if (!source.typePredicate && target.typePredicate) { + if (reportErrors) { + reportError(ts.Diagnostics.Signature_0_must_have_a_type_predicate, signatureToString(source)); + } + return 0 /* False */; + } var t = getReturnTypeOfSignature(target); if (t === voidType) return result; @@ -15006,6 +16638,27 @@ var ts; return 0 /* False */; } } + // Return true if the given type is part of a deeply nested chain of generic instantiations. We consider this to be the case + // when structural type comparisons have been started for 10 or more instantiations of the same generic type. 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 10 levels, but unequal at + // some level beyond that. + function isDeeplyNestedGeneric(type, stack, depth) { + // We track type references (created by createTypeReference) and instantiated types (created by instantiateType) + if (type.flags & (4096 /* Reference */ | 65536 /* Instantiated */) && depth >= 5) { + var symbol = type.symbol; + var count = 0; + for (var i = 0; i < depth; i++) { + var t = stack[i]; + if (t.flags & (4096 /* Reference */ | 65536 /* Instantiated */) && t.symbol === symbol) { + count++; + if (count >= 5) + return true; + } + } + } + return false; + } function isPropertyIdenticalTo(sourceProp, targetProp) { return compareProperties(sourceProp, targetProp, compareTypes) !== 0 /* False */; } @@ -15164,11 +16817,11 @@ var ts; return createAnonymousType(type.symbol, members, emptyArray, emptyArray, stringIndexType, numberIndexType); } function getWidenedType(type) { - if (type.flags & 786432 /* RequiresWidening */) { + if (type.flags & 1572864 /* RequiresWidening */) { if (type.flags & (32 /* Undefined */ | 64 /* Null */)) { return anyType; } - if (type.flags & 131072 /* ObjectLiteral */) { + if (type.flags & 262144 /* ObjectLiteral */) { return getWidenedTypeOfObjectLiteral(type); } if (type.flags & 16384 /* Union */) { @@ -15193,11 +16846,11 @@ var ts; if (isArrayType(type)) { return reportWideningErrorsInType(type.typeArguments[0]); } - if (type.flags & 131072 /* ObjectLiteral */) { + if (type.flags & 262144 /* ObjectLiteral */) { var errorReported = false; ts.forEach(getPropertiesOfObjectType(type), function (p) { var t = getTypeOfSymbol(p); - if (t.flags & 262144 /* ContainsUndefinedOrNull */) { + if (t.flags & 524288 /* ContainsUndefinedOrNull */) { if (!reportWideningErrorsInType(t)) { error(p.valueDeclaration, ts.Diagnostics.Object_literal_s_property_0_implicitly_has_an_1_type, p.name, typeToString(getWidenedType(t))); } @@ -15212,22 +16865,22 @@ var ts; var typeAsString = typeToString(getWidenedType(type)); var diagnostic; switch (declaration.kind) { - case 133 /* PropertyDeclaration */: - case 132 /* PropertySignature */: + case 134 /* PropertyDeclaration */: + case 133 /* PropertySignature */: diagnostic = ts.Diagnostics.Member_0_implicitly_has_an_1_type; break; - case 130 /* Parameter */: + case 131 /* 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 201 /* FunctionDeclaration */: - case 135 /* MethodDeclaration */: - case 134 /* MethodSignature */: - case 137 /* GetAccessor */: - case 138 /* SetAccessor */: - case 163 /* FunctionExpression */: - case 164 /* ArrowFunction */: + case 203 /* FunctionDeclaration */: + case 136 /* MethodDeclaration */: + case 135 /* MethodSignature */: + case 138 /* GetAccessor */: + case 139 /* SetAccessor */: + case 165 /* FunctionExpression */: + case 166 /* ArrowFunction */: if (!declaration.name) { error(declaration, ts.Diagnostics.Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeAsString); return; @@ -15240,7 +16893,7 @@ var ts; error(declaration, diagnostic, ts.declarationNameToString(declaration.name), typeAsString); } function reportErrorsFromWidening(declaration, type) { - if (produceDiagnostics && compilerOptions.noImplicitAny && type.flags & 262144 /* ContainsUndefinedOrNull */) { + if (produceDiagnostics && compilerOptions.noImplicitAny && type.flags & 524288 /* ContainsUndefinedOrNull */) { // Report implicit any error within type if possible, otherwise report error on declaration if (!reportWideningErrorsInType(type)) { reportImplicitAnyError(declaration, type); @@ -15300,20 +16953,6 @@ var ts; } return false; } - function isWithinDepthLimit(type, stack) { - if (depth >= 5) { - var target_2 = type.target; - var count = 0; - for (var i = 0; i < depth; i++) { - var t = stack[i]; - if (t.flags & 4096 /* Reference */ && t.target === target_2) { - count++; - } - } - return count < 5; - } - return true; - } function inferFromTypes(source, target) { if (source === anyFunctionType) { return; @@ -15383,22 +17022,26 @@ var ts; else if (source.flags & 48128 /* ObjectType */ && (target.flags & (4096 /* Reference */ | 8192 /* Tuple */) || (target.flags & 32768 /* Anonymous */) && target.symbol && target.symbol.flags & (8192 /* Method */ | 2048 /* TypeLiteral */))) { // If source is an object type, and target is a type reference, a tuple type, the type of a method, or a type literal, infer from members - if (!isInProcess(source, target) && isWithinDepthLimit(source, sourceStack) && isWithinDepthLimit(target, targetStack)) { - if (depth === 0) { - sourceStack = []; - targetStack = []; - } - sourceStack[depth] = source; - targetStack[depth] = target; - depth++; - inferFromProperties(source, target); - inferFromSignatures(source, target, 0 /* Call */); - inferFromSignatures(source, target, 1 /* Construct */); - inferFromIndexTypes(source, target, 0 /* String */, 0 /* String */); - inferFromIndexTypes(source, target, 1 /* Number */, 1 /* Number */); - inferFromIndexTypes(source, target, 0 /* String */, 1 /* Number */); - depth--; + if (isInProcess(source, target)) { + return; } + if (isDeeplyNestedGeneric(source, sourceStack, depth) && isDeeplyNestedGeneric(target, targetStack, depth)) { + return; + } + if (depth === 0) { + sourceStack = []; + targetStack = []; + } + sourceStack[depth] = source; + targetStack[depth] = target; + depth++; + inferFromProperties(source, target); + inferFromSignatures(source, target, 0 /* Call */); + inferFromSignatures(source, target, 1 /* Construct */); + inferFromIndexTypes(source, target, 0 /* String */, 0 /* String */); + inferFromIndexTypes(source, target, 1 /* Number */, 1 /* Number */); + inferFromIndexTypes(source, target, 0 /* String */, 1 /* Number */); + depth--; } } function inferFromProperties(source, target) { @@ -15423,7 +17066,17 @@ var ts; } function inferFromSignature(source, target) { forEachMatchingParameterType(source, target, inferFromTypes); - inferFromTypes(getReturnTypeOfSignature(source), getReturnTypeOfSignature(target)); + if (source.typePredicate && target.typePredicate) { + if (target.typePredicate.parameterIndex === source.typePredicate.parameterIndex) { + // Return types from type predicates are treated as booleans. In order to infer types + // from type predicates we would need to infer using the type within the type predicate + // (i.e. 'Foo' from 'x is Foo'). + inferFromTypes(source.typePredicate.type, target.typePredicate.type); + } + } + else { + inferFromTypes(getReturnTypeOfSignature(source), getReturnTypeOfSignature(target)); + } } function inferFromIndexTypes(source, target, sourceKind, targetKind) { var targetIndexType = getIndexTypeOfType(target, targetKind); @@ -15496,10 +17149,10 @@ var ts; // The expression is restricted to a single identifier or a sequence of identifiers separated by periods while (node) { switch (node.kind) { - case 145 /* TypeQuery */: + case 147 /* TypeQuery */: return true; case 65 /* Identifier */: - case 127 /* QualifiedName */: + case 128 /* QualifiedName */: node = node.parent; continue; default: @@ -15547,7 +17200,7 @@ var ts; function isAssignedInBinaryExpression(node) { if (node.operatorToken.kind >= 53 /* FirstAssignment */ && node.operatorToken.kind <= 64 /* LastAssignment */) { var n = node.left; - while (n.kind === 162 /* ParenthesizedExpression */) { + while (n.kind === 164 /* ParenthesizedExpression */) { n = n.expression; } if (n.kind === 65 /* Identifier */ && getResolvedSymbol(n) === symbol) { @@ -15564,46 +17217,46 @@ var ts; } function isAssignedIn(node) { switch (node.kind) { - case 170 /* BinaryExpression */: + case 172 /* BinaryExpression */: return isAssignedInBinaryExpression(node); - case 199 /* VariableDeclaration */: - case 153 /* BindingElement */: + case 201 /* VariableDeclaration */: + case 155 /* BindingElement */: return isAssignedInVariableDeclaration(node); - case 151 /* ObjectBindingPattern */: - case 152 /* ArrayBindingPattern */: - case 154 /* ArrayLiteralExpression */: - case 155 /* ObjectLiteralExpression */: - case 156 /* PropertyAccessExpression */: - case 157 /* ElementAccessExpression */: - case 158 /* CallExpression */: - case 159 /* NewExpression */: - case 161 /* TypeAssertionExpression */: - case 162 /* ParenthesizedExpression */: - case 168 /* PrefixUnaryExpression */: - case 165 /* DeleteExpression */: - case 166 /* TypeOfExpression */: - case 167 /* VoidExpression */: - case 169 /* PostfixUnaryExpression */: - case 171 /* ConditionalExpression */: - case 174 /* SpreadElementExpression */: - case 180 /* Block */: - case 181 /* VariableStatement */: - case 183 /* ExpressionStatement */: - case 184 /* IfStatement */: - case 185 /* DoStatement */: - case 186 /* WhileStatement */: - case 187 /* ForStatement */: - case 188 /* ForInStatement */: - case 189 /* ForOfStatement */: - case 192 /* ReturnStatement */: - case 193 /* WithStatement */: - case 194 /* SwitchStatement */: - case 221 /* CaseClause */: - case 222 /* DefaultClause */: - case 195 /* LabeledStatement */: - case 196 /* ThrowStatement */: - case 197 /* TryStatement */: - case 224 /* CatchClause */: + case 153 /* ObjectBindingPattern */: + case 154 /* ArrayBindingPattern */: + case 156 /* ArrayLiteralExpression */: + case 157 /* ObjectLiteralExpression */: + case 158 /* PropertyAccessExpression */: + case 159 /* ElementAccessExpression */: + case 160 /* CallExpression */: + case 161 /* NewExpression */: + case 163 /* TypeAssertionExpression */: + case 164 /* ParenthesizedExpression */: + case 170 /* PrefixUnaryExpression */: + case 167 /* DeleteExpression */: + case 168 /* TypeOfExpression */: + case 169 /* VoidExpression */: + case 171 /* PostfixUnaryExpression */: + case 173 /* ConditionalExpression */: + case 176 /* SpreadElementExpression */: + case 182 /* Block */: + case 183 /* VariableStatement */: + case 185 /* ExpressionStatement */: + case 186 /* IfStatement */: + case 187 /* DoStatement */: + case 188 /* WhileStatement */: + case 189 /* ForStatement */: + case 190 /* ForInStatement */: + case 191 /* ForOfStatement */: + case 194 /* ReturnStatement */: + case 195 /* WithStatement */: + case 196 /* SwitchStatement */: + case 223 /* CaseClause */: + case 224 /* DefaultClause */: + case 197 /* LabeledStatement */: + case 198 /* ThrowStatement */: + case 199 /* TryStatement */: + case 226 /* CatchClause */: return ts.forEachChild(node, isAssignedIn); } return false; @@ -15613,10 +17266,10 @@ var ts; // Resolve location from top down towards node if it is a context sensitive expression // That helps in making sure not assigning types as any when resolved out of order var containerNodes = []; - for (var parent_3 = node.parent; parent_3; parent_3 = parent_3.parent) { - if ((ts.isExpression(parent_3) || ts.isObjectLiteralMethod(node)) && - isContextSensitive(parent_3)) { - containerNodes.unshift(parent_3); + for (var parent_5 = node.parent; parent_5; parent_5 = parent_5.parent) { + if ((ts.isExpression(parent_5) || ts.isObjectLiteralMethod(node)) && + isContextSensitive(parent_5)) { + containerNodes.unshift(parent_5); } } ts.forEach(containerNodes, function (node) { getTypeOfNode(node); }); @@ -15649,59 +17302,61 @@ var ts; function getNarrowedTypeOfSymbol(symbol, node) { var type = getTypeOfSymbol(symbol); // Only narrow when symbol is variable of type any or an object, union, or type parameter type - if (node && symbol.flags & 3 /* Variable */ && type.flags & (1 /* Any */ | 48128 /* ObjectType */ | 16384 /* Union */ | 512 /* TypeParameter */)) { - loop: while (node.parent) { - var child = node; - node = node.parent; - var narrowedType = type; - switch (node.kind) { - case 184 /* IfStatement */: - // In a branch of an if statement, narrow based on controlling expression - if (child !== node.expression) { - narrowedType = narrowType(type, node.expression, child === node.thenStatement); - } - break; - case 171 /* ConditionalExpression */: - // In a branch of a conditional expression, narrow based on controlling condition - if (child !== node.condition) { - narrowedType = narrowType(type, node.condition, child === node.whenTrue); - } - break; - case 170 /* BinaryExpression */: - // In the right operand of an && or ||, narrow based on left operand - if (child === node.right) { - if (node.operatorToken.kind === 48 /* AmpersandAmpersandToken */) { - narrowedType = narrowType(type, node.left, true); + if (node && symbol.flags & 3 /* Variable */) { + if (isTypeAny(type) || type.flags & (48128 /* ObjectType */ | 16384 /* Union */ | 512 /* TypeParameter */)) { + loop: while (node.parent) { + var child = node; + node = node.parent; + var narrowedType = type; + switch (node.kind) { + case 186 /* IfStatement */: + // In a branch of an if statement, narrow based on controlling expression + if (child !== node.expression) { + narrowedType = narrowType(type, node.expression, child === node.thenStatement); } - else if (node.operatorToken.kind === 49 /* BarBarToken */) { - narrowedType = narrowType(type, node.left, false); + break; + case 173 /* ConditionalExpression */: + // In a branch of a conditional expression, narrow based on controlling condition + if (child !== node.condition) { + narrowedType = narrowType(type, node.condition, child === node.whenTrue); } - } - break; - case 228 /* SourceFile */: - case 206 /* ModuleDeclaration */: - case 201 /* FunctionDeclaration */: - case 135 /* MethodDeclaration */: - case 134 /* MethodSignature */: - case 137 /* GetAccessor */: - case 138 /* SetAccessor */: - case 136 /* Constructor */: - // Stop at the first containing function or module declaration - break loop; - } - // Use narrowed type if construct contains no assignments to variable - if (narrowedType !== type) { - if (isVariableAssignedWithin(symbol, node)) { - break; + break; + case 172 /* BinaryExpression */: + // In the right operand of an && or ||, narrow based on left operand + if (child === node.right) { + if (node.operatorToken.kind === 48 /* AmpersandAmpersandToken */) { + narrowedType = narrowType(type, node.left, true); + } + else if (node.operatorToken.kind === 49 /* BarBarToken */) { + narrowedType = narrowType(type, node.left, false); + } + } + break; + case 230 /* SourceFile */: + case 208 /* ModuleDeclaration */: + case 203 /* FunctionDeclaration */: + case 136 /* MethodDeclaration */: + case 135 /* MethodSignature */: + case 138 /* GetAccessor */: + case 139 /* SetAccessor */: + case 137 /* Constructor */: + // Stop at the first containing function or module declaration + break loop; + } + // Use narrowed type if construct contains no assignments to variable + if (narrowedType !== type) { + if (isVariableAssignedWithin(symbol, node)) { + break; + } + type = narrowedType; } - type = narrowedType; } } } return type; function narrowTypeByEquality(type, expr, assumeTrue) { // Check that we have 'typeof ' on the left and string literal on the right - if (expr.left.kind !== 166 /* TypeOfExpression */ || expr.right.kind !== 8 /* StringLiteral */) { + if (expr.left.kind !== 168 /* TypeOfExpression */ || expr.right.kind !== 8 /* StringLiteral */) { return type; } var left = expr.left; @@ -15716,7 +17371,7 @@ var ts; if (assumeTrue) { // Assumed result is true. If check was not for a primitive type, remove all primitive types if (!typeInfo) { - return removeTypesFromUnionType(type, 258 /* StringLike */ | 132 /* NumberLike */ | 8 /* Boolean */ | 1048576 /* ESSymbol */, + return removeTypesFromUnionType(type, 258 /* StringLike */ | 132 /* NumberLike */ | 8 /* Boolean */ | 2097152 /* ESSymbol */, /*isOfTypeKind*/ true, false); } // Check was for a primitive type, return that primitive type if it is a subtype @@ -15766,7 +17421,7 @@ var ts; } function narrowTypeByInstanceof(type, expr, assumeTrue) { // Check that type is not any, assumed result is true, and we have variable symbol on the left - if (type.flags & 1 /* Any */ || !assumeTrue || expr.left.kind !== 65 /* Identifier */ || getResolvedSymbol(expr.left) !== symbol) { + if (isTypeAny(type) || !assumeTrue || expr.left.kind !== 65 /* Identifier */ || getResolvedSymbol(expr.left) !== symbol) { return type; } // Check that right operand is a function type with a prototype property @@ -15777,9 +17432,9 @@ var ts; var targetType; var prototypeProperty = getPropertyOfType(rightType, "prototype"); if (prototypeProperty) { - // Target type is type of the protoype property + // Target type is type of the prototype property var prototypePropertyType = getTypeOfSymbol(prototypeProperty); - if (prototypePropertyType !== anyType) { + if (!isTypeAny(prototypePropertyType)) { targetType = prototypePropertyType; } } @@ -15797,14 +17452,36 @@ var ts; } } if (targetType) { - // Narrow to the target type if it's a subtype of the current type - if (isTypeSubtypeOf(targetType, type)) { - return targetType; - } - // If the current type is a union type, remove all constituents that aren't subtypes of the target. - if (type.flags & 16384 /* Union */) { - return getUnionType(ts.filter(type.types, function (t) { return isTypeSubtypeOf(t, targetType); })); + return getNarrowedType(type, targetType); + } + return type; + } + function getNarrowedType(originalType, narrowedTypeCandidate) { + // Narrow to the target type if it's a subtype of the current type + if (isTypeSubtypeOf(narrowedTypeCandidate, originalType)) { + return narrowedTypeCandidate; + } + // If the current type is a union type, remove all constituents that aren't subtypes of the target. + if (originalType.flags & 16384 /* Union */) { + return getUnionType(ts.filter(originalType.types, function (t) { return isTypeSubtypeOf(t, narrowedTypeCandidate); })); + } + return originalType; + } + function narrowTypeByTypePredicate(type, expr, assumeTrue) { + if (type.flags & 1 /* Any */) { + return type; + } + var signature = getResolvedSignature(expr); + if (signature.typePredicate && + expr.arguments[signature.typePredicate.parameterIndex] && + getSymbolAtLocation(expr.arguments[signature.typePredicate.parameterIndex]) === symbol) { + if (!assumeTrue) { + if (type.flags & 16384 /* Union */) { + return getUnionType(ts.filter(type.types, function (t) { return !isTypeSubtypeOf(t, signature.typePredicate.type); })); + } + return type; } + return getNarrowedType(type, signature.typePredicate.type); } return type; } @@ -15812,9 +17489,11 @@ var ts; // will be a subtype or the same type as the argument. function narrowType(type, expr, assumeTrue) { switch (expr.kind) { - case 162 /* ParenthesizedExpression */: + case 160 /* CallExpression */: + return narrowTypeByTypePredicate(type, expr, assumeTrue); + case 164 /* ParenthesizedExpression */: return narrowType(type, expr.expression, assumeTrue); - case 170 /* BinaryExpression */: + case 172 /* BinaryExpression */: var operator = expr.operatorToken.kind; if (operator === 30 /* EqualsEqualsEqualsToken */ || operator === 31 /* ExclamationEqualsEqualsToken */) { return narrowTypeByEquality(type, expr, assumeTrue); @@ -15829,7 +17508,7 @@ var ts; return narrowTypeByInstanceof(type, expr, assumeTrue); } break; - case 168 /* PrefixUnaryExpression */: + case 170 /* PrefixUnaryExpression */: if (expr.operator === 46 /* ExclamationToken */) { return narrowType(type, expr.operand, !assumeTrue); } @@ -15846,7 +17525,7 @@ var ts; // 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 && ts.getContainingFunction(node).kind === 164 /* ArrowFunction */ && languageVersion < 2 /* ES6 */) { + if (symbol === argumentsSymbol && ts.getContainingFunction(node).kind === 166 /* ArrowFunction */ && languageVersion < 2 /* ES6 */) { error(node, ts.Diagnostics.The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_standard_function_expression); } if (symbol.flags & 8388608 /* Alias */ && !isInTypeQuery(node) && !isConstEnumOrConstEnumOnlyModule(resolveAlias(symbol))) { @@ -15870,7 +17549,7 @@ var ts; function checkBlockScopedBindingCapturedInLoop(node, symbol) { if (languageVersion >= 2 /* ES6 */ || (symbol.flags & 2 /* BlockScopedVariable */) === 0 || - symbol.valueDeclaration.parent.kind === 224 /* CatchClause */) { + symbol.valueDeclaration.parent.kind === 226 /* CatchClause */) { return; } // - check if binding is used in some function @@ -15879,12 +17558,12 @@ var ts; // nesting structure: // (variable declaration or binding element) -> variable declaration list -> container var container = symbol.valueDeclaration; - while (container.kind !== 200 /* VariableDeclarationList */) { + while (container.kind !== 202 /* VariableDeclarationList */) { container = container.parent; } // get the parent of variable declaration list container = container.parent; - if (container.kind === 181 /* VariableStatement */) { + if (container.kind === 183 /* VariableStatement */) { // if parent is variable statement - get its parent container = container.parent; } @@ -15903,9 +17582,9 @@ var ts; } } function captureLexicalThis(node, container) { - var classNode = container.parent && container.parent.kind === 202 /* ClassDeclaration */ ? container.parent : undefined; + var classNode = container.parent && container.parent.kind === 204 /* ClassDeclaration */ ? container.parent : undefined; getNodeLinks(node).flags |= 2 /* LexicalThis */; - if (container.kind === 133 /* PropertyDeclaration */ || container.kind === 136 /* Constructor */) { + if (container.kind === 134 /* PropertyDeclaration */ || container.kind === 137 /* Constructor */) { getNodeLinks(classNode).flags |= 4 /* CaptureThis */; } else { @@ -15918,39 +17597,39 @@ var ts; var container = ts.getThisContainer(node, true); var needToCaptureLexicalThis = false; // Now skip arrow functions to get the "real" owner of 'this'. - if (container.kind === 164 /* ArrowFunction */) { + if (container.kind === 166 /* ArrowFunction */) { container = ts.getThisContainer(container, 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 /* ES6 */); } switch (container.kind) { - case 206 /* ModuleDeclaration */: + case 208 /* 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 205 /* EnumDeclaration */: + case 207 /* 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 136 /* Constructor */: + case 137 /* Constructor */: if (isInConstructorArgumentInitializer(node, container)) { error(node, ts.Diagnostics.this_cannot_be_referenced_in_constructor_arguments); } break; - case 133 /* PropertyDeclaration */: - case 132 /* PropertySignature */: + case 134 /* PropertyDeclaration */: + case 133 /* PropertySignature */: if (container.flags & 128 /* Static */) { error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_static_property_initializer); } break; - case 128 /* ComputedPropertyName */: + case 129 /* ComputedPropertyName */: error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_computed_property_name); break; } if (needToCaptureLexicalThis) { captureLexicalThis(node, container); } - var classNode = container.parent && container.parent.kind === 202 /* ClassDeclaration */ ? container.parent : undefined; + var classNode = container.parent && container.parent.kind === 204 /* ClassDeclaration */ ? container.parent : undefined; if (classNode) { var symbol = getSymbolOfNode(classNode); return container.flags & 128 /* Static */ ? getTypeOfSymbol(symbol) : getDeclaredTypeOfSymbol(symbol); @@ -15959,23 +17638,21 @@ var ts; } function isInConstructorArgumentInitializer(node, constructorDecl) { for (var n = node; n && n !== constructorDecl; n = n.parent) { - if (n.kind === 130 /* Parameter */) { + if (n.kind === 131 /* Parameter */) { return true; } } return false; } function checkSuperExpression(node) { - var isCallExpression = node.parent.kind === 158 /* CallExpression */ && node.parent.expression === node; - var enclosingClass = ts.getAncestor(node, 202 /* ClassDeclaration */); - var baseClass; - if (enclosingClass && ts.getClassExtendsHeritageClauseElement(enclosingClass)) { - var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(enclosingClass)); - var baseTypes = getBaseTypes(classType); - baseClass = baseTypes.length && baseTypes[0]; - } - if (!baseClass) { - error(node, ts.Diagnostics.super_can_only_be_referenced_in_a_derived_class); + var isCallExpression = node.parent.kind === 160 /* CallExpression */ && node.parent.expression === node; + var classDeclaration = ts.getAncestor(node, 204 /* ClassDeclaration */); + var classType = classDeclaration && getDeclaredTypeOfSymbol(getSymbolOfNode(classDeclaration)); + var baseClassType = classType && getBaseTypes(classType)[0]; + if (!baseClassType) { + if (!classDeclaration || !ts.getClassExtendsHeritageClauseElement(classDeclaration)) { + error(node, ts.Diagnostics.super_can_only_be_referenced_in_a_derived_class); + } return unknownType; } var container = ts.getSuperContainer(node, true); @@ -15985,7 +17662,7 @@ var ts; if (isCallExpression) { // TS 1.0 SPEC (April 2014): 4.8.1 // Super calls are only permitted in constructors of derived classes - canUseSuperExpression = container.kind === 136 /* Constructor */; + canUseSuperExpression = container.kind === 137 /* Constructor */; } else { // TS 1.0 SPEC (April 2014) @@ -15994,28 +17671,28 @@ var ts; // - In a static member function or static member accessor // super property access might appear in arrow functions with arbitrary deep nesting needToCaptureLexicalThis = false; - while (container && container.kind === 164 /* ArrowFunction */) { + while (container && container.kind === 166 /* ArrowFunction */) { container = ts.getSuperContainer(container, true); needToCaptureLexicalThis = languageVersion < 2 /* ES6 */; } // topmost container must be something that is directly nested in the class declaration - if (container && container.parent && container.parent.kind === 202 /* ClassDeclaration */) { + if (container && container.parent && container.parent.kind === 204 /* ClassDeclaration */) { if (container.flags & 128 /* Static */) { canUseSuperExpression = - container.kind === 135 /* MethodDeclaration */ || - container.kind === 134 /* MethodSignature */ || - container.kind === 137 /* GetAccessor */ || - container.kind === 138 /* SetAccessor */; + container.kind === 136 /* MethodDeclaration */ || + container.kind === 135 /* MethodSignature */ || + container.kind === 138 /* GetAccessor */ || + container.kind === 139 /* SetAccessor */; } else { canUseSuperExpression = - container.kind === 135 /* MethodDeclaration */ || - container.kind === 134 /* MethodSignature */ || - container.kind === 137 /* GetAccessor */ || - container.kind === 138 /* SetAccessor */ || - container.kind === 133 /* PropertyDeclaration */ || - container.kind === 132 /* PropertySignature */ || - container.kind === 136 /* Constructor */; + container.kind === 136 /* MethodDeclaration */ || + container.kind === 135 /* MethodSignature */ || + container.kind === 138 /* GetAccessor */ || + container.kind === 139 /* SetAccessor */ || + container.kind === 134 /* PropertyDeclaration */ || + container.kind === 133 /* PropertySignature */ || + container.kind === 137 /* Constructor */; } } } @@ -16023,13 +17700,13 @@ var ts; var returnType; if ((container.flags & 128 /* Static */) || isCallExpression) { getNodeLinks(node).flags |= 32 /* SuperStatic */; - returnType = getTypeOfSymbol(baseClass.symbol); + returnType = getBaseConstructorTypeOfClass(classType); } else { getNodeLinks(node).flags |= 16 /* SuperInstance */; - returnType = baseClass; + returnType = baseClassType; } - if (container.kind === 136 /* Constructor */ && isInConstructorArgumentInitializer(node, container)) { + if (container.kind === 137 /* 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); returnType = unknownType; @@ -16043,7 +17720,7 @@ var ts; return returnType; } } - if (container && container.kind === 128 /* ComputedPropertyName */) { + if (container && container.kind === 129 /* ComputedPropertyName */) { error(node, ts.Diagnostics.super_cannot_be_referenced_in_a_computed_property_name); } else if (isCallExpression) { @@ -16061,7 +17738,7 @@ var ts; if (isContextSensitive(func)) { var contextualSignature = getContextualSignature(func); if (contextualSignature) { - var funcHasRestParameters = ts.hasRestParameters(func); + var funcHasRestParameters = ts.hasRestParameter(func); var len = func.parameters.length - (funcHasRestParameters ? 1 : 0); var indexOfParameter = ts.indexOf(func.parameters, parameter); if (indexOfParameter < len) { @@ -16088,7 +17765,7 @@ var ts; if (declaration.type) { return getTypeFromTypeNode(declaration.type); } - if (declaration.kind === 130 /* Parameter */) { + if (declaration.kind === 131 /* Parameter */) { var type = getContextuallyTypedParameterType(declaration); if (type) { return type; @@ -16101,22 +17778,40 @@ var ts; return undefined; } function getContextualTypeForReturnExpression(node) { + var func = ts.getContainingFunction(node); + if (func && !func.asteriskToken) { + return getContextualReturnType(func); + } + return undefined; + } + function getContextualTypeForYieldOperand(node) { var func = ts.getContainingFunction(node); if (func) { - // 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 (func.type || func.kind === 136 /* Constructor */ || func.kind === 137 /* GetAccessor */ && getSetAccessorTypeAnnotationNode(ts.getDeclarationOfKind(func.symbol, 138 /* SetAccessor */))) { - return getReturnTypeOfSignature(getSignatureFromDeclaration(func)); - } - // 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(func); - if (signature) { - return getReturnTypeOfSignature(signature); + var contextualReturnType = getContextualReturnType(func); + if (contextualReturnType) { + return node.asteriskToken + ? contextualReturnType + : getElementTypeOfIterableIterator(contextualReturnType); } } return undefined; } + 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 === 137 /* Constructor */ || + functionDecl.kind === 138 /* GetAccessor */ && getSetAccessorTypeAnnotationNode(ts.getDeclarationOfKind(functionDecl.symbol, 139 /* 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); @@ -16128,7 +17823,7 @@ var ts; return undefined; } function getContextualTypeForSubstitutionExpression(template, substitutionExpression) { - if (template.parent.kind === 160 /* TaggedTemplateExpression */) { + if (template.parent.kind === 162 /* TaggedTemplateExpression */) { return getContextualTypeForArgument(template.parent, substitutionExpression); } return undefined; @@ -16238,7 +17933,7 @@ var ts; var index = ts.indexOf(arrayLiteral.elements, node); return getTypeOfPropertyOfContextualType(type, "" + index) || getIndexTypeOfContextualType(type, 1 /* Number */) - || (languageVersion >= 2 /* ES6 */ ? checkIteratedType(type, undefined) : undefined); + || (languageVersion >= 2 /* ES6 */ ? getElementTypeOfIterable(type, undefined) : undefined); } return undefined; } @@ -16259,32 +17954,34 @@ var ts; } var parent = node.parent; switch (parent.kind) { - case 199 /* VariableDeclaration */: - case 130 /* Parameter */: - case 133 /* PropertyDeclaration */: - case 132 /* PropertySignature */: - case 153 /* BindingElement */: + case 201 /* VariableDeclaration */: + case 131 /* Parameter */: + case 134 /* PropertyDeclaration */: + case 133 /* PropertySignature */: + case 155 /* BindingElement */: return getContextualTypeForInitializerExpression(node); - case 164 /* ArrowFunction */: - case 192 /* ReturnStatement */: + case 166 /* ArrowFunction */: + case 194 /* ReturnStatement */: return getContextualTypeForReturnExpression(node); - case 158 /* CallExpression */: - case 159 /* NewExpression */: + case 175 /* YieldExpression */: + return getContextualTypeForYieldOperand(parent); + case 160 /* CallExpression */: + case 161 /* NewExpression */: return getContextualTypeForArgument(parent, node); - case 161 /* TypeAssertionExpression */: + case 163 /* TypeAssertionExpression */: return getTypeFromTypeNode(parent.type); - case 170 /* BinaryExpression */: + case 172 /* BinaryExpression */: return getContextualTypeForBinaryOperand(node); - case 225 /* PropertyAssignment */: + case 227 /* PropertyAssignment */: return getContextualTypeForObjectLiteralElement(parent); - case 154 /* ArrayLiteralExpression */: + case 156 /* ArrayLiteralExpression */: return getContextualTypeForElementExpression(node); - case 171 /* ConditionalExpression */: + case 173 /* ConditionalExpression */: return getContextualTypeForConditionalOperand(node); - case 178 /* TemplateSpan */: - ts.Debug.assert(parent.parent.kind === 172 /* TemplateExpression */); + case 180 /* TemplateSpan */: + ts.Debug.assert(parent.parent.kind === 174 /* TemplateExpression */); return getContextualTypeForSubstitutionExpression(parent.parent, node); - case 162 /* ParenthesizedExpression */: + case 164 /* ParenthesizedExpression */: return getContextualType(parent); } return undefined; @@ -16301,11 +17998,13 @@ var ts; } } function isFunctionExpressionOrArrowFunction(node) { - return node.kind === 163 /* FunctionExpression */ || node.kind === 164 /* ArrowFunction */; + return node.kind === 165 /* FunctionExpression */ || node.kind === 166 /* ArrowFunction */; } function getContextualSignatureForFunctionLikeDeclaration(node) { - // Only function expressions and arrow functions are contextually typed. - return isFunctionExpressionOrArrowFunction(node) ? getContextualSignature(node) : undefined; + // Only function expressions, arrow functions, and object literal methods are contextually typed. + return isFunctionExpressionOrArrowFunction(node) || ts.isObjectLiteralMethod(node) + ? getContextualSignature(node) + : undefined; } // 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. @@ -16313,7 +18012,7 @@ var ts; // 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 !== 135 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); + ts.Debug.assert(node.kind !== 136 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); var type = ts.isObjectLiteralMethod(node) ? getContextualTypeForObjectLiteralMethod(node) : getContextualType(node); @@ -16369,13 +18068,13 @@ var ts; // an assignment target. Examples include 'a = xxx', '{ p: a } = xxx', '[{ p: a}] = xxx'. function isAssignmentTarget(node) { var parent = node.parent; - if (parent.kind === 170 /* BinaryExpression */ && parent.operatorToken.kind === 53 /* EqualsToken */ && parent.left === node) { + if (parent.kind === 172 /* BinaryExpression */ && parent.operatorToken.kind === 53 /* EqualsToken */ && parent.left === node) { return true; } - if (parent.kind === 225 /* PropertyAssignment */) { + if (parent.kind === 227 /* PropertyAssignment */) { return isAssignmentTarget(parent.parent); } - if (parent.kind === 154 /* ArrayLiteralExpression */) { + if (parent.kind === 156 /* ArrayLiteralExpression */) { return isAssignmentTarget(parent); } return false; @@ -16400,7 +18099,7 @@ var ts; var inDestructuringPattern = isAssignmentTarget(node); for (var _i = 0; _i < elements.length; _i++) { var e = elements[_i]; - if (inDestructuringPattern && e.kind === 174 /* SpreadElementExpression */) { + if (inDestructuringPattern && e.kind === 176 /* SpreadElementExpression */) { // Given the following situation: // var c: {}; // [...c] = ["", 0]; @@ -16415,7 +18114,7 @@ var ts; // if there is no index type / iterated type. var restArrayType = checkExpression(e.expression, contextualMapper); var restElementType = getIndexTypeOfType(restArrayType, 1 /* Number */) || - (languageVersion >= 2 /* ES6 */ ? checkIteratedType(restArrayType, undefined) : undefined); + (languageVersion >= 2 /* ES6 */ ? getElementTypeOfIterable(restArrayType, undefined) : undefined); if (restElementType) { elementTypes.push(restElementType); } @@ -16424,7 +18123,7 @@ var ts; var type = checkExpression(e, contextualMapper); elementTypes.push(type); } - hasSpreadElement = hasSpreadElement || e.kind === 174 /* SpreadElementExpression */; + hasSpreadElement = hasSpreadElement || e.kind === 176 /* SpreadElementExpression */; } if (!hasSpreadElement) { var contextualType = getContextualType(node); @@ -16435,12 +18134,15 @@ var ts; return createArrayType(getUnionType(elementTypes)); } function isNumericName(name) { - return name.kind === 128 /* ComputedPropertyName */ ? isNumericComputedName(name) : isNumericLiteralName(name.text); + return name.kind === 129 /* 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 allConstituentTypesHaveKind(checkComputedPropertyName(name), 1 /* Any */ | 132 /* NumberLike */); + return isTypeAnyOrAllConstituentTypesHaveKind(checkComputedPropertyName(name), 132 /* NumberLike */); + } + function isTypeAnyOrAllConstituentTypesHaveKind(type, kind) { + return isTypeAny(type) || allConstituentTypesHaveKind(type, kind); } function isNumericLiteralName(name) { // The intent of numeric names is that @@ -16472,7 +18174,7 @@ var ts; links.resolvedType = checkExpression(node.expression); // This will allow types number, string, symbol or any. It will also allow enums, the unknown // type, and any union of these types (like string | number). - if (!allConstituentTypesHaveKind(links.resolvedType, 1 /* Any */ | 132 /* NumberLike */ | 258 /* StringLike */ | 1048576 /* ESSymbol */)) { + if (!isTypeAnyOrAllConstituentTypesHaveKind(links.resolvedType, 132 /* NumberLike */ | 258 /* StringLike */ | 2097152 /* ESSymbol */)) { error(node, ts.Diagnostics.A_computed_property_name_must_be_of_type_string_number_symbol_or_any); } else { @@ -16491,18 +18193,18 @@ var ts; for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { var memberDecl = _a[_i]; var member = memberDecl.symbol; - if (memberDecl.kind === 225 /* PropertyAssignment */ || - memberDecl.kind === 226 /* ShorthandPropertyAssignment */ || + if (memberDecl.kind === 227 /* PropertyAssignment */ || + memberDecl.kind === 228 /* ShorthandPropertyAssignment */ || ts.isObjectLiteralMethod(memberDecl)) { var type = void 0; - if (memberDecl.kind === 225 /* PropertyAssignment */) { + if (memberDecl.kind === 227 /* PropertyAssignment */) { type = checkPropertyAssignment(memberDecl, contextualMapper); } - else if (memberDecl.kind === 135 /* MethodDeclaration */) { + else if (memberDecl.kind === 136 /* MethodDeclaration */) { type = checkObjectLiteralMethod(memberDecl, contextualMapper); } else { - ts.Debug.assert(memberDecl.kind === 226 /* ShorthandPropertyAssignment */); + ts.Debug.assert(memberDecl.kind === 228 /* ShorthandPropertyAssignment */); type = checkExpression(memberDecl.name, contextualMapper); } typeFlags |= type.flags; @@ -16522,7 +18224,7 @@ var ts; // 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 === 137 /* GetAccessor */ || memberDecl.kind === 138 /* SetAccessor */); + ts.Debug.assert(memberDecl.kind === 138 /* GetAccessor */ || memberDecl.kind === 139 /* SetAccessor */); checkAccessorDeclaration(memberDecl); } if (!ts.hasDynamicName(memberDecl)) { @@ -16533,7 +18235,7 @@ var ts; var stringIndexType = getIndexType(0 /* String */); var numberIndexType = getIndexType(1 /* Number */); var result = createAnonymousType(node.symbol, propertiesTable, emptyArray, emptyArray, stringIndexType, numberIndexType); - result.flags |= 131072 /* ObjectLiteral */ | 524288 /* ContainsObjectLiteral */ | (typeFlags & 262144 /* ContainsUndefinedOrNull */); + result.flags |= 262144 /* ObjectLiteral */ | 1048576 /* ContainsObjectLiteral */ | (typeFlags & 524288 /* ContainsUndefinedOrNull */); return result; function getIndexType(kind) { if (contextualType && contextualTypeHasIndexSignature(contextualType, kind)) { @@ -16561,7 +18263,7 @@ var ts; // 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 : 133 /* PropertyDeclaration */; + return s.valueDeclaration ? s.valueDeclaration.kind : 134 /* PropertyDeclaration */; } function getDeclarationFlagsFromSymbol(s) { return s.valueDeclaration ? ts.getCombinedNodeFlags(s.valueDeclaration) : s.flags & 134217728 /* Prototype */ ? 16 /* Public */ | 128 /* Static */ : 0; @@ -16574,7 +18276,7 @@ var ts; } // Property is known to be private or protected at this point // Get the declaring and enclosing class instance types - var enclosingClassDeclaration = ts.getAncestor(node, 202 /* ClassDeclaration */); + var enclosingClassDeclaration = ts.getAncestor(node, 204 /* ClassDeclaration */); var enclosingClass = enclosingClassDeclaration ? getDeclaredTypeOfSymbol(getSymbolOfNode(enclosingClassDeclaration)) : undefined; var declaringClass = getDeclaredTypeOfSymbol(prop.parent); // Private property is accessible if declaring and enclosing class are the same @@ -16610,51 +18312,49 @@ var ts; return checkPropertyAccessExpressionOrQualifiedName(node, node.left, node.right); } function checkPropertyAccessExpressionOrQualifiedName(node, left, right) { - var type = checkExpressionOrQualifiedName(left); - if (type === unknownType) + var type = checkExpression(left); + if (isTypeAny(type)) { return type; - if (type !== anyType) { - var apparentType = getApparentType(getWidenedType(type)); - if (apparentType === unknownType) { - // handle cases when type is Type parameter with invalid constraint - return unknownType; - } - var prop = getPropertyOfType(apparentType, right.text); - if (!prop) { - if (right.text) { - error(right, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(right), typeToString(type)); - } - return unknownType; - } - getNodeLinks(node).resolvedSymbol = prop; - if (prop.parent && prop.parent.flags & 32 /* Class */) { - // 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 (left.kind === 91 /* SuperKeyword */ && getDeclarationKindFromSymbol(prop) !== 135 /* MethodDeclaration */) { - error(right, ts.Diagnostics.Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword); - } - else { - checkClassPropertyAccess(node, left, type, prop); - } - } - return getTypeOfSymbol(prop); } - return anyType; + var apparentType = getApparentType(getWidenedType(type)); + if (apparentType === unknownType) { + // handle cases when type is Type parameter with invalid constraint + return unknownType; + } + var prop = getPropertyOfType(apparentType, right.text); + if (!prop) { + if (right.text) { + error(right, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(right), typeToString(type)); + } + return unknownType; + } + getNodeLinks(node).resolvedSymbol = prop; + if (prop.parent && prop.parent.flags & 32 /* Class */) { + // 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 (left.kind === 91 /* SuperKeyword */ && getDeclarationKindFromSymbol(prop) !== 136 /* MethodDeclaration */) { + error(right, ts.Diagnostics.Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword); + } + else { + checkClassPropertyAccess(node, left, type, prop); + } + } + return getTypeOfSymbol(prop); } function isValidPropertyAccess(node, propertyName) { - var left = node.kind === 156 /* PropertyAccessExpression */ + var left = node.kind === 158 /* PropertyAccessExpression */ ? node.expression : node.left; - var type = checkExpressionOrQualifiedName(left); - if (type !== unknownType && type !== anyType) { + var type = checkExpression(left); + if (type !== unknownType && !isTypeAny(type)) { var prop = getPropertyOfType(getWidenedType(type), propertyName); if (prop && prop.parent && prop.parent.flags & 32 /* Class */) { - if (left.kind === 91 /* SuperKeyword */ && getDeclarationKindFromSymbol(prop) !== 135 /* MethodDeclaration */) { + if (left.kind === 91 /* SuperKeyword */ && getDeclarationKindFromSymbol(prop) !== 136 /* MethodDeclaration */) { return false; } else { @@ -16670,7 +18370,7 @@ var ts; // Grammar checking if (!node.argumentExpression) { var sourceFile = getSourceFile(node); - if (node.parent.kind === 159 /* NewExpression */ && node.parent.expression === node) { + if (node.parent.kind === 161 /* 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); @@ -16703,23 +18403,23 @@ var ts; // - Otherwise, if IndexExpr is of type Any, the String or Number primitive type, or an enum type, the property access is of type Any. // See if we can index as a property. if (node.argumentExpression) { - var name_6 = getPropertyNameForIndexedAccess(node.argumentExpression, indexType); - if (name_6 !== undefined) { - var prop = getPropertyOfType(objectType, name_6); + var name_10 = getPropertyNameForIndexedAccess(node.argumentExpression, indexType); + if (name_10 !== undefined) { + var prop = getPropertyOfType(objectType, name_10); if (prop) { getNodeLinks(node).resolvedSymbol = prop; return getTypeOfSymbol(prop); } else if (isConstEnum) { - error(node.argumentExpression, ts.Diagnostics.Property_0_does_not_exist_on_const_enum_1, name_6, symbolToString(objectType.symbol)); + error(node.argumentExpression, ts.Diagnostics.Property_0_does_not_exist_on_const_enum_1, name_10, symbolToString(objectType.symbol)); return unknownType; } } } // Check for compatible indexer types. - if (allConstituentTypesHaveKind(indexType, 1 /* Any */ | 258 /* StringLike */ | 132 /* NumberLike */ | 1048576 /* ESSymbol */)) { + if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 258 /* StringLike */ | 132 /* NumberLike */ | 2097152 /* ESSymbol */)) { // Try to use a number indexer. - if (allConstituentTypesHaveKind(indexType, 1 /* Any */ | 132 /* NumberLike */)) { + if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 132 /* NumberLike */)) { var numberIndexType = getIndexTypeOfType(objectType, 1 /* Number */); if (numberIndexType) { return numberIndexType; @@ -16731,7 +18431,7 @@ var ts; return stringIndexType; } // Fall back to any. - if (compilerOptions.noImplicitAny && !compilerOptions.suppressImplicitAnyIndexErrors && objectType !== anyType) { + if (compilerOptions.noImplicitAny && !compilerOptions.suppressImplicitAnyIndexErrors && !isTypeAny(objectType)) { error(node, ts.Diagnostics.Index_signature_of_object_type_implicitly_has_an_any_type); } return anyType; @@ -16772,7 +18472,7 @@ var ts; return false; } // Make sure the property type is the primitive symbol type - if ((expressionType.flags & 1048576 /* ESSymbol */) === 0) { + if ((expressionType.flags & 2097152 /* ESSymbol */) === 0) { if (reportError) { error(expression, ts.Diagnostics.A_computed_property_name_of_the_form_0_must_be_of_type_symbol, ts.getTextOfNode(expression)); } @@ -16799,7 +18499,7 @@ var ts; return true; } function resolveUntypedCall(node) { - if (node.kind === 160 /* TaggedTemplateExpression */) { + if (node.kind === 162 /* TaggedTemplateExpression */) { checkExpression(node.template); } else { @@ -16832,13 +18532,13 @@ var ts; for (var _i = 0; _i < signatures.length; _i++) { var signature = signatures[_i]; var symbol = signature.declaration && getSymbolOfNode(signature.declaration); - var parent_4 = signature.declaration && signature.declaration.parent; + var parent_6 = signature.declaration && signature.declaration.parent; if (!lastSymbol || symbol === lastSymbol) { - if (lastParent && parent_4 === lastParent) { + if (lastParent && parent_6 === lastParent) { index++; } else { - lastParent = parent_4; + lastParent = parent_6; index = cutoffIndex; } } @@ -16846,7 +18546,7 @@ var ts; // 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_4; + lastParent = parent_6; } lastSymbol = symbol; // specialized signatures always need to be placed before non-specialized signatures regardless @@ -16867,7 +18567,7 @@ var ts; } function getSpreadArgumentIndex(args) { for (var i = 0; i < args.length; i++) { - if (args[i].kind === 174 /* SpreadElementExpression */) { + if (args[i].kind === 176 /* SpreadElementExpression */) { return i; } } @@ -16877,13 +18577,13 @@ var ts; var adjustedArgCount; // 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 - if (node.kind === 160 /* TaggedTemplateExpression */) { + if (node.kind === 162 /* 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 adjustedArgCount = args.length; typeArguments = undefined; - if (tagExpression.template.kind === 172 /* TemplateExpression */) { + if (tagExpression.template.kind === 174 /* 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; @@ -16904,7 +18604,7 @@ var ts; var callExpression = node; if (!callExpression.arguments) { // This only happens when we have something of the form: 'new C' - ts.Debug.assert(callExpression.kind === 159 /* NewExpression */); + ts.Debug.assert(callExpression.kind === 161 /* NewExpression */); return signature.minArgumentCount === 0; } // For IDE scenarios we may have an incomplete call, so a trailing comma is tantamount to adding another argument. @@ -16981,10 +18681,10 @@ var ts; // wildcards for all context sensitive function expressions. for (var i = 0; i < args.length; i++) { var arg = args[i]; - if (arg.kind !== 176 /* OmittedExpression */) { + if (arg.kind !== 178 /* OmittedExpression */) { var paramType = getTypeAtPosition(signature, i); var argType = void 0; - if (i === 0 && args[i].parent.kind === 160 /* TaggedTemplateExpression */) { + if (i === 0 && args[i].parent.kind === 162 /* TaggedTemplateExpression */) { argType = globalTemplateStringsArrayType; } else { @@ -17031,12 +18731,12 @@ var ts; function checkApplicableSignature(node, args, signature, relation, excludeArgument, reportErrors) { for (var i = 0; i < args.length; i++) { var arg = args[i]; - if (arg.kind !== 176 /* OmittedExpression */) { + if (arg.kind !== 178 /* OmittedExpression */) { // Check spread elements against rest type (from arity check we know spread argument corresponds to a rest parameter) var paramType = getTypeAtPosition(signature, i); // A tagged template expression provides a special first argument, and string literals get string literal types // unless we're reporting errors - var argType = i === 0 && node.kind === 160 /* TaggedTemplateExpression */ + var argType = i === 0 && node.kind === 162 /* TaggedTemplateExpression */ ? globalTemplateStringsArrayType : arg.kind === 8 /* StringLiteral */ && !reportErrors ? getStringLiteralType(arg) @@ -17058,10 +18758,10 @@ var ts; */ function getEffectiveCallArguments(node) { var args; - if (node.kind === 160 /* TaggedTemplateExpression */) { + if (node.kind === 162 /* TaggedTemplateExpression */) { var template = node.template; args = [template]; - if (template.kind === 172 /* TemplateExpression */) { + if (template.kind === 174 /* TemplateExpression */) { ts.forEach(template.templateSpans, function (span) { args.push(span.expression); }); @@ -17072,32 +18772,11 @@ var ts; } return args; } - /** - * In a 'super' call, type arguments are not provided within the CallExpression node itself. - * Instead, they must be fetched from the class declaration's base type node. - * - * If 'node' is a 'super' call (e.g. super(...), new super(...)), then we attempt to fetch - * the type arguments off the containing class's first heritage clause (if one exists). Note that if - * type arguments are supplied on the 'super' call, they are ignored (though this is syntactically incorrect). - * - * In all other cases, the call's explicit type arguments are returned. - */ - function getEffectiveTypeArguments(callExpression) { - if (callExpression.expression.kind === 91 /* SuperKeyword */) { - var containingClass = ts.getAncestor(callExpression, 202 /* ClassDeclaration */); - var baseClassTypeNode = containingClass && ts.getClassExtendsHeritageClauseElement(containingClass); - return baseClassTypeNode && baseClassTypeNode.typeArguments; - } - else { - // Ordinary case - simple function invocation. - return callExpression.typeArguments; - } - } function resolveCall(node, signatures, candidatesOutArray) { - var isTaggedTemplate = node.kind === 160 /* TaggedTemplateExpression */; + var isTaggedTemplate = node.kind === 162 /* TaggedTemplateExpression */; var typeArguments; if (!isTaggedTemplate) { - typeArguments = getEffectiveTypeArguments(node); + typeArguments = node.typeArguments; // We already perform checking on the type arguments on the class declaration itself. if (node.expression.kind !== 91 /* SuperKeyword */) { ts.forEach(typeArguments, checkSourceElement); @@ -17192,8 +18871,8 @@ var ts; checkApplicableSignature(node, args, candidateForArgumentError, assignableRelation, undefined, true); } else if (candidateForTypeArgumentError) { - if (!isTaggedTemplate && node.typeArguments) { - checkTypeArguments(candidateForTypeArgumentError, node.typeArguments, [], true); + if (!isTaggedTemplate && typeArguments) { + checkTypeArguments(candidateForTypeArgumentError, typeArguments, [], true); } else { ts.Debug.assert(resultOfFailedInference.failedTypeParameterIndex >= 0); @@ -17287,7 +18966,11 @@ var ts; if (node.expression.kind === 91 /* SuperKeyword */) { var superType = checkSuperExpression(node.expression); if (superType !== unknownType) { - return resolveCall(node, getSignaturesOfType(superType, 1 /* Construct */), candidatesOutArray); + // 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.getAncestor(node, 204 /* ClassDeclaration */)); + var baseConstructors = getInstantiatedConstructorsForTypeArguments(superType, baseTypeNode.typeArguments); + return resolveCall(node, baseConstructors, candidatesOutArray); } return resolveUntypedCall(node); } @@ -17310,8 +18993,10 @@ var ts; // types are provided for the argument expressions, and the result is always of type Any. // We exclude union types because we may have a union of function types that happen to have // no common signatures. - if (funcType === anyType || (!callSignatures.length && !constructSignatures.length && !(funcType.flags & 16384 /* Union */) && isTypeAssignableTo(funcType, globalFunctionType))) { - if (node.typeArguments) { + if (isTypeAny(funcType) || (!callSignatures.length && !constructSignatures.length && !(funcType.flags & 16384 /* Union */) && isTypeAssignableTo(funcType, globalFunctionType))) { + // The unknownType indicates that an error already occured (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); @@ -17331,32 +19016,32 @@ var ts; return resolveCall(node, callSignatures, candidatesOutArray); } function resolveNewExpression(node, candidatesOutArray) { - if (node.arguments && languageVersion < 2 /* ES6 */) { + 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_6_and_higher); + error(node.arguments[spreadIndex], ts.Diagnostics.Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher); } } var expressionType = checkExpression(node.expression); - // TS 1.0 spec: 4.11 - // If ConstructExpr is of type Any, Args can be any argument - // list and the result of the operation is of type Any. - if (expressionType === anyType) { - if (node.typeArguments) { - error(node, ts.Diagnostics.Untyped_function_calls_may_not_accept_type_arguments); - } - return resolveUntypedCall(node); - } // If ConstructExpr'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 + // 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); } + // TS 1.0 spec: 4.11 + // If ConstructExpr 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 @@ -17388,7 +19073,7 @@ var ts; return resolveErrorCall(node); } var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */); - if (tagType === anyType || (!callSignatures.length && !(tagType.flags & 16384 /* Union */) && isTypeAssignableTo(tagType, globalFunctionType))) { + if (isTypeAny(tagType) || (!callSignatures.length && !(tagType.flags & 16384 /* Union */) && isTypeAssignableTo(tagType, globalFunctionType))) { return resolveUntypedCall(node); } if (!callSignatures.length) { @@ -17407,13 +19092,13 @@ var ts; // to correctly fill the candidatesOutArray. if (!links.resolvedSignature || candidatesOutArray) { links.resolvedSignature = anySignature; - if (node.kind === 158 /* CallExpression */) { + if (node.kind === 160 /* CallExpression */) { links.resolvedSignature = resolveCallExpression(node, candidatesOutArray); } - else if (node.kind === 159 /* NewExpression */) { + else if (node.kind === 161 /* NewExpression */) { links.resolvedSignature = resolveNewExpression(node, candidatesOutArray); } - else if (node.kind === 160 /* TaggedTemplateExpression */) { + else if (node.kind === 162 /* TaggedTemplateExpression */) { links.resolvedSignature = resolveTaggedTemplateExpression(node, candidatesOutArray); } else { @@ -17429,12 +19114,12 @@ var ts; if (node.expression.kind === 91 /* SuperKeyword */) { return voidType; } - if (node.kind === 159 /* NewExpression */) { + if (node.kind === 161 /* NewExpression */) { var declaration = signature.declaration; if (declaration && - declaration.kind !== 136 /* Constructor */ && - declaration.kind !== 140 /* ConstructSignature */ && - declaration.kind !== 144 /* ConstructorType */) { + declaration.kind !== 137 /* Constructor */ && + declaration.kind !== 141 /* ConstructSignature */ && + declaration.kind !== 146 /* ConstructorType */) { // When resolved signature is a call signature (and not a construct signature) the result type is any if (compilerOptions.noImplicitAny) { error(node, ts.Diagnostics.new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type); @@ -17482,21 +19167,43 @@ var ts; return unknownType; } var type; - if (func.body.kind !== 180 /* Block */) { + if (func.body.kind !== 182 /* Block */) { type = checkExpressionCached(func.body, contextualMapper); } else { - // Aggregate the types of expressions within all the return statements. - var types = checkAndAggregateReturnExpressionTypes(func.body, contextualMapper); - if (types.length === 0) { - return voidType; + var types; + var funcIsGenerator = !!func.asteriskToken; + if (funcIsGenerator) { + types = checkAndAggregateYieldOperandTypes(func.body, contextualMapper); + if (types.length === 0) { + var iterableIteratorAny = createIterableIteratorType(anyType); + if (compilerOptions.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; + } } - // When return statements are contextually typed we allow the return type to be a union type. Otherwise we require the - // return expressions to have a best common supertype. + else { + types = checkAndAggregateReturnExpressionTypes(func.body, contextualMapper); + if (types.length === 0) { + return voidType; + } + } + // When yield/return statements are contextually typed we allow the return type to be a union type. + // Otherwise we require the yield/return expressions to have a best common supertype. type = contextualSignature ? getUnionType(types) : getCommonSupertype(types); if (!type) { - error(func, ts.Diagnostics.No_best_common_type_exists_among_return_expressions); - return unknownType; + if (funcIsGenerator) { + error(func, ts.Diagnostics.No_best_common_type_exists_among_yield_expressions); + return createIterableIteratorType(unknownType); + } + else { + error(func, ts.Diagnostics.No_best_common_type_exists_among_return_expressions); + return unknownType; + } + } + if (funcIsGenerator) { + type = createIterableIteratorType(type); } } if (!contextualSignature) { @@ -17504,7 +19211,23 @@ var ts; } return getWidenedType(type); } - /// Returns a set of types relating to every return expression relating to a function block. + function checkAndAggregateYieldOperandTypes(body, contextualMapper) { + var aggregatedTypes = []; + ts.forEachYieldExpression(body, function (yieldExpression) { + var expr = yieldExpression.expression; + if (expr) { + var type = checkExpressionCached(expr, contextualMapper); + if (yieldExpression.asteriskToken) { + // A yield* expression effectively yields everything that its operand yields + type = checkElementTypeOfIterable(type, yieldExpression.expression); + } + if (!ts.contains(aggregatedTypes, type)) { + aggregatedTypes.push(type); + } + } + }); + return aggregatedTypes; + } function checkAndAggregateReturnExpressionTypes(body, contextualMapper) { var aggregatedTypes = []; ts.forEachReturnStatement(body, function (returnStatement) { @@ -17524,7 +19247,7 @@ var ts; }); } function bodyContainsSingleThrowStatement(body) { - return (body.statements.length === 1) && (body.statements[0].kind === 196 /* ThrowStatement */); + return (body.statements.length === 1) && (body.statements[0].kind === 198 /* ThrowStatement */); } // TypeScript Specification 1.0 (6.3) - July 2014 // An explicitly typed function whose return type isn't the Void or the Any type @@ -17535,11 +19258,11 @@ var ts; return; } // Functions that return 'void' or 'any' don't need any return expressions. - if (returnType === voidType || returnType === anyType) { + if (returnType === voidType || isTypeAny(returnType)) { return; } // If all we have is a function signature, or an arrow function with an expression body, then there is nothing to check. - if (ts.nodeIsMissing(func.body) || func.body.kind !== 180 /* Block */) { + if (ts.nodeIsMissing(func.body) || func.body.kind !== 182 /* Block */) { return; } var bodyBlock = func.body; @@ -17557,11 +19280,11 @@ var ts; error(func.type, ts.Diagnostics.A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value_or_consist_of_a_single_throw_statement); } function checkFunctionExpressionOrObjectLiteralMethod(node, contextualMapper) { - ts.Debug.assert(node.kind !== 135 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); + ts.Debug.assert(node.kind !== 136 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); // Grammar checking - var hasGrammarError = checkGrammarDeclarationNameInStrictMode(node) || checkGrammarFunctionLikeDeclaration(node); - if (!hasGrammarError && node.kind === 163 /* FunctionExpression */) { - checkGrammarFunctionName(node.name) || checkGrammarForGenerator(node); + var hasGrammarError = checkGrammarFunctionLikeDeclaration(node); + if (!hasGrammarError && node.kind === 165 /* FunctionExpression */) { + checkGrammarForGenerator(node); } // The identityMapper object is used to indicate that function expressions are wildcards if (contextualMapper === identityMapper && isContextSensitive(node)) { @@ -17592,19 +19315,27 @@ var ts; checkSignatureDeclaration(node); } } - if (produceDiagnostics && node.kind !== 135 /* MethodDeclaration */ && node.kind !== 134 /* MethodSignature */) { + if (produceDiagnostics && node.kind !== 136 /* MethodDeclaration */ && node.kind !== 135 /* MethodSignature */) { checkCollisionWithCapturedSuperVariable(node, node.name); checkCollisionWithCapturedThisVariable(node, node.name); } return type; } function checkFunctionExpressionOrObjectLiteralMethodBody(node) { - ts.Debug.assert(node.kind !== 135 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); + ts.Debug.assert(node.kind !== 136 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); if (node.type && !node.asteriskToken) { checkIfNonVoidFunctionHasReturnExpressionsOrSingleThrowStatment(node, getTypeFromTypeNode(node.type)); } if (node.body) { - if (node.body.kind === 180 /* Block */) { + 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 === 182 /* Block */) { checkSourceElement(node.body); } else { @@ -17617,7 +19348,7 @@ var ts; } } function checkArithmeticOperandType(operand, type, diagnostic) { - if (!allConstituentTypesHaveKind(type, 1 /* Any */ | 132 /* NumberLike */)) { + if (!isTypeAnyOrAllConstituentTypesHaveKind(type, 132 /* NumberLike */)) { error(operand, diagnostic); return false; } @@ -17646,17 +19377,17 @@ var ts; // An identifier expression that references any other kind of entity is classified as a value(and therefore cannot be the target of an assignment). return !symbol || symbol === unknownSymbol || symbol === argumentsSymbol || (symbol.flags & 3 /* Variable */) !== 0; } - case 156 /* PropertyAccessExpression */: { + case 158 /* PropertyAccessExpression */: { var symbol = findSymbol(n); // TypeScript 1.0 spec (April 2014): 4.10 // A property access expression is always classified as a reference. // NOTE (not in spec): assignment to enum members should not be allowed return !symbol || symbol === unknownSymbol || (symbol.flags & ~8 /* EnumMember */) !== 0; } - case 157 /* ElementAccessExpression */: + case 159 /* ElementAccessExpression */: // old compiler doesn't check indexed assess return true; - case 162 /* ParenthesizedExpression */: + case 164 /* ParenthesizedExpression */: return isReferenceOrErrorExpression(n.expression); default: return false; @@ -17665,21 +19396,21 @@ var ts; function isConstVariableReference(n) { switch (n.kind) { case 65 /* Identifier */: - case 156 /* PropertyAccessExpression */: { + case 158 /* PropertyAccessExpression */: { var symbol = findSymbol(n); return symbol && (symbol.flags & 3 /* Variable */) !== 0 && (getDeclarationFlagsFromSymbol(symbol) & 8192 /* Const */) !== 0; } - case 157 /* ElementAccessExpression */: { + case 159 /* ElementAccessExpression */: { var index = n.argumentExpression; var symbol = findSymbol(n.expression); if (symbol && index && index.kind === 8 /* StringLiteral */) { - var name_7 = index.text; - var prop = getPropertyOfType(getTypeOfSymbol(symbol), name_7); + var name_11 = index.text; + var prop = getPropertyOfType(getTypeOfSymbol(symbol), name_11); return prop && (prop.flags & 3 /* Variable */) !== 0 && (getDeclarationFlagsFromSymbol(prop) & 8192 /* Const */) !== 0; } return false; } - case 162 /* ParenthesizedExpression */: + case 164 /* ParenthesizedExpression */: return isConstVariableReference(n.expression); default: return false; @@ -17696,13 +19427,7 @@ var ts; return true; } function checkDeleteExpression(node) { - // Grammar checking - if (node.parserContextFlags & 1 /* StrictMode */ && node.expression.kind === 65 /* 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 - grammarErrorOnNode(node.expression, ts.Diagnostics.delete_cannot_be_called_on_an_identifier_in_strict_mode); - } - var operandType = checkExpression(node.expression); + checkExpression(node.expression); return booleanType; } function checkTypeOfExpression(node) { @@ -17714,19 +19439,12 @@ var ts; return undefinedType; } function checkPrefixUnaryExpression(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 ((node.operator === 38 /* PlusPlusToken */ || node.operator === 39 /* MinusMinusToken */)) { - checkGrammarEvalOrArgumentsInStrictMode(node, node.operand); - } var operandType = checkExpression(node.operand); switch (node.operator) { case 33 /* PlusToken */: case 34 /* MinusToken */: case 47 /* TildeToken */: - if (someConstituentTypeHasKind(operandType, 1048576 /* ESSymbol */)) { + if (someConstituentTypeHasKind(operandType, 2097152 /* ESSymbol */)) { error(node.operand, ts.Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, ts.tokenToString(node.operator)); } return numberType; @@ -17744,11 +19462,6 @@ var ts; return unknownType; } function checkPostfixUnaryExpression(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. - checkGrammarEvalOrArgumentsInStrictMode(node, node.operand); var operandType = checkExpression(node.operand); var ok = checkArithmeticOperandType(node.operand, operandType, ts.Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type); if (ok) { @@ -17804,11 +19517,11 @@ var ts; // and the right operand to be of type Any or a subtype of the 'Function' interface type. // 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 (allConstituentTypesHaveKind(leftType, 1049086 /* Primitive */)) { + if (allConstituentTypesHaveKind(leftType, 2097662 /* Primitive */)) { error(node.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 (!(rightType.flags & 1 /* Any */ || isTypeSubtypeOf(rightType, globalFunctionType))) { + if (!(isTypeAny(rightType) || isTypeSubtypeOf(rightType, globalFunctionType))) { error(node.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; @@ -17818,10 +19531,10 @@ var ts; // The in operator requires the left operand to be of type Any, the String primitive type, or the Number primitive type, // and the right operand to be of type Any, an object type, or a type parameter type. // The result is always of the Boolean primitive type. - if (!allConstituentTypesHaveKind(leftType, 1 /* Any */ | 258 /* StringLike */ | 132 /* NumberLike */ | 1048576 /* ESSymbol */)) { + if (!isTypeAnyOrAllConstituentTypesHaveKind(leftType, 258 /* StringLike */ | 132 /* NumberLike */ | 2097152 /* ESSymbol */)) { error(node.left, ts.Diagnostics.The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol); } - if (!allConstituentTypesHaveKind(rightType, 1 /* Any */ | 48128 /* ObjectType */ | 512 /* TypeParameter */)) { + if (!isTypeAnyOrAllConstituentTypesHaveKind(rightType, 48128 /* ObjectType */ | 512 /* TypeParameter */)) { error(node.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; @@ -17830,18 +19543,19 @@ var ts; var properties = node.properties; for (var _i = 0; _i < properties.length; _i++) { var p = properties[_i]; - if (p.kind === 225 /* PropertyAssignment */ || p.kind === 226 /* ShorthandPropertyAssignment */) { + if (p.kind === 227 /* PropertyAssignment */ || p.kind === 228 /* ShorthandPropertyAssignment */) { // TODO(andersh): Computed property support - var name_8 = p.name; - var type = sourceType.flags & 1 /* Any */ ? sourceType : - getTypeOfPropertyOfType(sourceType, name_8.text) || - isNumericLiteralName(name_8.text) && getIndexTypeOfType(sourceType, 1 /* Number */) || + var name_12 = p.name; + var type = isTypeAny(sourceType) + ? sourceType + : getTypeOfPropertyOfType(sourceType, name_12.text) || + isNumericLiteralName(name_12.text) && getIndexTypeOfType(sourceType, 1 /* Number */) || getIndexTypeOfType(sourceType, 0 /* String */); if (type) { - checkDestructuringAssignment(p.initializer || name_8, type); + checkDestructuringAssignment(p.initializer || name_12, type); } else { - error(name_8, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(sourceType), ts.declarationNameToString(name_8)); + error(name_12, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(sourceType), ts.declarationNameToString(name_12)); } } else { @@ -17858,11 +19572,12 @@ var ts; var elements = node.elements; for (var i = 0; i < elements.length; i++) { var e = elements[i]; - if (e.kind !== 176 /* OmittedExpression */) { - if (e.kind !== 174 /* SpreadElementExpression */) { + if (e.kind !== 178 /* OmittedExpression */) { + if (e.kind !== 176 /* SpreadElementExpression */) { var propName = "" + i; - var type = sourceType.flags & 1 /* Any */ ? sourceType : - isTupleLikeType(sourceType) + var type = isTypeAny(sourceType) + ? sourceType + : isTupleLikeType(sourceType) ? getTypeOfPropertyOfType(sourceType, propName) : elementType; if (type) { @@ -17883,7 +19598,7 @@ var ts; } else { var restExpression = e.expression; - if (restExpression.kind === 170 /* BinaryExpression */ && restExpression.operatorToken.kind === 53 /* EqualsToken */) { + if (restExpression.kind === 172 /* BinaryExpression */ && restExpression.operatorToken.kind === 53 /* EqualsToken */) { error(restExpression.operatorToken, ts.Diagnostics.A_rest_element_cannot_have_an_initializer); } else { @@ -17896,14 +19611,14 @@ var ts; return sourceType; } function checkDestructuringAssignment(target, sourceType, contextualMapper) { - if (target.kind === 170 /* BinaryExpression */ && target.operatorToken.kind === 53 /* EqualsToken */) { + if (target.kind === 172 /* BinaryExpression */ && target.operatorToken.kind === 53 /* EqualsToken */) { checkBinaryExpression(target, contextualMapper); target = target.left; } - if (target.kind === 155 /* ObjectLiteralExpression */) { + if (target.kind === 157 /* ObjectLiteralExpression */) { return checkObjectLiteralAssignment(target, sourceType, contextualMapper); } - if (target.kind === 154 /* ArrayLiteralExpression */) { + if (target.kind === 156 /* ArrayLiteralExpression */) { return checkArrayLiteralAssignment(target, sourceType, contextualMapper); } return checkReferenceAssignment(target, sourceType, contextualMapper); @@ -17916,14 +19631,8 @@ var ts; return sourceType; } function checkBinaryExpression(node, contextualMapper) { - // Grammar checking - if (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) - checkGrammarEvalOrArgumentsInStrictMode(node, node.left); - } var operator = node.operatorToken.kind; - if (operator === 53 /* EqualsToken */ && (node.left.kind === 155 /* ObjectLiteralExpression */ || node.left.kind === 154 /* ArrayLiteralExpression */)) { + if (operator === 53 /* EqualsToken */ && (node.left.kind === 157 /* ObjectLiteralExpression */ || node.left.kind === 156 /* ArrayLiteralExpression */)) { return checkDestructuringAssignment(node.left, checkExpression(node.right, contextualMapper), contextualMapper); } var leftType = checkExpression(node.left, contextualMapper); @@ -17997,10 +19706,10 @@ var ts; // If one or both operands are of the String primitive type, the result is of the String primitive type. resultType = stringType; } - else if (leftType.flags & 1 /* Any */ || rightType.flags & 1 /* Any */) { + 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 = anyType; + resultType = leftType === unknownType || rightType === unknownType ? unknownType : anyType; } // Symbols are not allowed at all in arithmetic expressions if (resultType && !checkForDisallowedESSymbolOperand(operator)) { @@ -18047,8 +19756,8 @@ var ts; } // Return true if there was no error, false if there was an error. function checkForDisallowedESSymbolOperand(operator) { - var offendingSymbolOperand = someConstituentTypeHasKind(leftType, 1048576 /* ESSymbol */) ? node.left : - someConstituentTypeHasKind(rightType, 1048576 /* ESSymbol */) ? node.right : + var offendingSymbolOperand = someConstituentTypeHasKind(leftType, 2097152 /* ESSymbol */) ? node.left : + someConstituentTypeHasKind(rightType, 2097152 /* ESSymbol */) ? node.right : undefined; if (offendingSymbolOperand) { error(offendingSymbolOperand, ts.Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, ts.tokenToString(operator)); @@ -18091,14 +19800,53 @@ var ts; error(node, ts.Diagnostics.Operator_0_cannot_be_applied_to_types_1_and_2, ts.tokenToString(node.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 (current.kind === 204 /* ClassDeclaration */ || current.kind === 177 /* ClassExpression */) { + return true; + } + current = parent; + parent = parent.parent; + } + return false; + } function checkYieldExpression(node) { // Grammar checking - if (!(node.parserContextFlags & 4 /* Yield */)) { - grammarErrorOnFirstToken(node, ts.Diagnostics.yield_expression_must_be_contained_within_a_generator_declaration); + if (!(node.parserContextFlags & 4 /* Yield */) || isYieldExpressionInClass(node)) { + grammarErrorOnFirstToken(node, ts.Diagnostics.A_yield_expression_is_only_allowed_in_a_generator_body); } - else { - grammarErrorOnFirstToken(node, ts.Diagnostics.yield_expressions_are_not_currently_supported); + 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. + if (func && func.asteriskToken) { + var expressionType = checkExpressionCached(node.expression, undefined); + var expressionElementType; + var nodeIsYieldStar = !!node.asteriskToken; + if (nodeIsYieldStar) { + expressionElementType = checkElementTypeOfIterable(expressionType, node.expression); + } + // 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 = getElementTypeOfIterableIterator(getTypeFromTypeNode(func.type)) || anyType; + if (nodeIsYieldStar) { + checkTypeAssignableTo(expressionElementType, signatureElementType, node.expression, undefined); + } + else { + checkTypeAssignableTo(expressionType, signatureElementType, node.expression, undefined); + } + } + } } + // Both yield and yield* expressions have type 'any' + return anyType; } function checkConditionalExpression(node, contextualMapper) { checkExpression(node.condition); @@ -18135,7 +19883,7 @@ var ts; // 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 === 128 /* ComputedPropertyName */) { + if (node.name.kind === 129 /* ComputedPropertyName */) { checkComputedPropertyName(node.name); } return checkExpression(node.initializer, contextualMapper); @@ -18146,7 +19894,7 @@ var ts; // 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 === 128 /* ComputedPropertyName */) { + if (node.name.kind === 129 /* ComputedPropertyName */) { checkComputedPropertyName(node.name); } var uninstantiatedType = checkFunctionExpressionOrObjectLiteralMethod(node, contextualMapper); @@ -18167,10 +19915,6 @@ var ts; } return type; } - function checkExpression(node, contextualMapper) { - checkGrammarIdentifierInStrictMode(node); - return checkExpressionOrQualifiedName(node, contextualMapper); - } // 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.12.2 in spec) and provides the type mapper to use in @@ -18178,9 +19922,9 @@ var ts; // object, it serves as an indicator that all contained function and arrow expressions should be considered to // have the wildcard function type; this form of type check is used during overload resolution to exclude // contextually typed function and arrow expressions in the initial phase. - function checkExpressionOrQualifiedName(node, contextualMapper) { + function checkExpression(node, contextualMapper) { var type; - if (node.kind == 127 /* QualifiedName */) { + if (node.kind === 128 /* QualifiedName */) { type = checkQualifiedName(node); } else { @@ -18192,9 +19936,9 @@ var ts; // - 'left' in property access // - 'object' in indexed access // - target in rhs of import statement - var ok = (node.parent.kind === 156 /* PropertyAccessExpression */ && node.parent.expression === node) || - (node.parent.kind === 157 /* ElementAccessExpression */ && node.parent.expression === node) || - ((node.kind === 65 /* Identifier */ || node.kind === 127 /* QualifiedName */) && isInRightSideOfImportOrExportAssignment(node)); + var ok = (node.parent.kind === 158 /* PropertyAccessExpression */ && node.parent.expression === node) || + (node.parent.kind === 159 /* ElementAccessExpression */ && node.parent.expression === node) || + ((node.kind === 65 /* Identifier */ || node.kind === 128 /* 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); } @@ -18221,62 +19965,60 @@ var ts; return booleanType; case 7 /* NumericLiteral */: return checkNumericLiteral(node); - case 172 /* TemplateExpression */: + case 174 /* TemplateExpression */: return checkTemplateExpression(node); case 8 /* StringLiteral */: case 10 /* NoSubstitutionTemplateLiteral */: return stringType; case 9 /* RegularExpressionLiteral */: return globalRegExpType; - case 154 /* ArrayLiteralExpression */: + case 156 /* ArrayLiteralExpression */: return checkArrayLiteral(node, contextualMapper); - case 155 /* ObjectLiteralExpression */: + case 157 /* ObjectLiteralExpression */: return checkObjectLiteral(node, contextualMapper); - case 156 /* PropertyAccessExpression */: + case 158 /* PropertyAccessExpression */: return checkPropertyAccessExpression(node); - case 157 /* ElementAccessExpression */: + case 159 /* ElementAccessExpression */: return checkIndexedAccess(node); - case 158 /* CallExpression */: - case 159 /* NewExpression */: + case 160 /* CallExpression */: + case 161 /* NewExpression */: return checkCallExpression(node); - case 160 /* TaggedTemplateExpression */: + case 162 /* TaggedTemplateExpression */: return checkTaggedTemplateExpression(node); - case 161 /* TypeAssertionExpression */: + case 163 /* TypeAssertionExpression */: return checkTypeAssertion(node); - case 162 /* ParenthesizedExpression */: + case 164 /* ParenthesizedExpression */: return checkExpression(node.expression, contextualMapper); - case 175 /* ClassExpression */: + case 177 /* ClassExpression */: return checkClassExpression(node); - case 163 /* FunctionExpression */: - case 164 /* ArrowFunction */: + case 165 /* FunctionExpression */: + case 166 /* ArrowFunction */: return checkFunctionExpressionOrObjectLiteralMethod(node, contextualMapper); - case 166 /* TypeOfExpression */: + case 168 /* TypeOfExpression */: return checkTypeOfExpression(node); - case 165 /* DeleteExpression */: + case 167 /* DeleteExpression */: return checkDeleteExpression(node); - case 167 /* VoidExpression */: + case 169 /* VoidExpression */: return checkVoidExpression(node); - case 168 /* PrefixUnaryExpression */: + case 170 /* PrefixUnaryExpression */: return checkPrefixUnaryExpression(node); - case 169 /* PostfixUnaryExpression */: + case 171 /* PostfixUnaryExpression */: return checkPostfixUnaryExpression(node); - case 170 /* BinaryExpression */: + case 172 /* BinaryExpression */: return checkBinaryExpression(node, contextualMapper); - case 171 /* ConditionalExpression */: + case 173 /* ConditionalExpression */: return checkConditionalExpression(node, contextualMapper); - case 174 /* SpreadElementExpression */: + case 176 /* SpreadElementExpression */: return checkSpreadElementExpression(node, contextualMapper); - case 176 /* OmittedExpression */: + case 178 /* OmittedExpression */: return undefinedType; - case 173 /* YieldExpression */: - checkYieldExpression(node); - return unknownType; + case 175 /* YieldExpression */: + return checkYieldExpression(node); } return unknownType; } // DECLARATION AND STATEMENT TYPE CHECKING function checkTypeParameter(node) { - checkGrammarDeclarationNameInStrictMode(node); // Grammar Checking if (node.expression) { grammarErrorOnFirstToken(node.expression, ts.Diagnostics.Type_expected); @@ -18293,15 +20035,13 @@ var ts; // 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). - // It is a SyntaxError if the identifier eval or arguments appears within a FormalParameterList of a - // strict mode FunctionLikeDeclaration or FunctionExpression(13.1) // Grammar checking - checkGrammarDecorators(node) || checkGrammarModifiers(node) || checkGrammarEvalOrArgumentsInStrictMode(node, node.name); + checkGrammarDecorators(node) || checkGrammarModifiers(node); checkVariableLikeDeclaration(node); var func = ts.getContainingFunction(node); if (node.flags & 112 /* AccessibilityModifier */) { func = ts.getContainingFunction(node); - if (!(func.kind === 136 /* Constructor */ && ts.nodeIsPresent(func.body))) { + if (!(func.kind === 137 /* Constructor */ && ts.nodeIsPresent(func.body))) { error(node, ts.Diagnostics.A_parameter_property_is_only_allowed_in_a_constructor_implementation); } } @@ -18314,38 +20054,139 @@ var ts; error(node, ts.Diagnostics.A_rest_parameter_must_be_of_an_array_type); } } + function isSyntacticallyValidGenerator(node) { + if (!node.asteriskToken || !node.body) { + return false; + } + return node.kind === 136 /* MethodDeclaration */ || + node.kind === 203 /* FunctionDeclaration */ || + node.kind === 165 /* FunctionExpression */; + } + function getTypePredicateParameterIndex(parameterList, parameter) { + if (parameterList) { + for (var i = 0; i < parameterList.length; i++) { + var param = parameterList[i]; + if (param.name.kind === 65 /* Identifier */ && + param.name.text === parameter.text) { + return i; + } + } + } + return -1; + } + function isInLegalTypePredicatePosition(node) { + switch (node.parent.kind) { + case 166 /* ArrowFunction */: + case 140 /* CallSignature */: + case 203 /* FunctionDeclaration */: + case 165 /* FunctionExpression */: + case 145 /* FunctionType */: + case 136 /* MethodDeclaration */: + case 135 /* MethodSignature */: + return node === node.parent.type; + } + return false; + } function checkSignatureDeclaration(node) { // Grammar checking - if (node.kind === 141 /* IndexSignature */) { + if (node.kind === 142 /* IndexSignature */) { checkGrammarIndexSignature(node); } - else if (node.kind === 143 /* FunctionType */ || node.kind === 201 /* FunctionDeclaration */ || node.kind === 144 /* ConstructorType */ || - node.kind === 139 /* CallSignature */ || node.kind === 136 /* Constructor */ || - node.kind === 140 /* ConstructSignature */) { + else if (node.kind === 145 /* FunctionType */ || node.kind === 203 /* FunctionDeclaration */ || node.kind === 146 /* ConstructorType */ || + node.kind === 140 /* CallSignature */ || node.kind === 137 /* Constructor */ || + node.kind === 141 /* ConstructSignature */) { checkGrammarFunctionLikeDeclaration(node); } checkTypeParameters(node.typeParameters); ts.forEach(node.parameters, checkParameter); if (node.type) { - checkSourceElement(node.type); + if (node.type.kind === 143 /* TypePredicate */) { + var typePredicate = getSignatureFromDeclaration(node).typePredicate; + var typePredicateNode = node.type; + if (isInLegalTypePredicatePosition(typePredicateNode)) { + if (typePredicate.parameterIndex >= 0) { + if (node.parameters[typePredicate.parameterIndex].dotDotDotToken) { + error(typePredicateNode.parameterName, ts.Diagnostics.A_type_predicate_cannot_reference_a_rest_parameter); + } + else { + checkTypeAssignableTo(typePredicate.type, getTypeAtLocation(node.parameters[typePredicate.parameterIndex]), typePredicateNode.type); + } + } + else if (typePredicateNode.parameterName) { + var hasReportedError = false; + for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) { + var param = _a[_i]; + if (hasReportedError) { + break; + } + if (param.name.kind === 153 /* ObjectBindingPattern */ || + param.name.kind === 154 /* ArrayBindingPattern */) { + (function checkBindingPattern(pattern) { + for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) { + var element = _a[_i]; + if (element.name.kind === 65 /* Identifier */ && + element.name.text === typePredicate.parameterName) { + error(typePredicateNode.parameterName, ts.Diagnostics.A_type_predicate_cannot_reference_element_0_in_a_binding_pattern, typePredicate.parameterName); + hasReportedError = true; + break; + } + else if (element.name.kind === 154 /* ArrayBindingPattern */ || + element.name.kind === 153 /* ObjectBindingPattern */) { + checkBindingPattern(element.name); + } + } + })(param.name); + } + } + if (!hasReportedError) { + error(typePredicateNode.parameterName, ts.Diagnostics.Cannot_find_parameter_0, typePredicate.parameterName); + } + } + } + else { + error(typePredicateNode, ts.Diagnostics.A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods); + } + } + else { + checkSourceElement(node.type); + } } if (produceDiagnostics) { checkCollisionWithArgumentsInGeneratedCode(node); if (compilerOptions.noImplicitAny && !node.type) { switch (node.kind) { - case 140 /* ConstructSignature */: + case 141 /* ConstructSignature */: error(node, ts.Diagnostics.Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type); break; - case 139 /* CallSignature */: + case 140 /* CallSignature */: error(node, ts.Diagnostics.Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type); break; } } + if (node.type) { + if (languageVersion >= 2 /* ES6 */ && isSyntacticallyValidGenerator(node)) { + var returnType = getTypeFromTypeNode(node.type); + if (returnType === voidType) { + error(node.type, ts.Diagnostics.A_generator_cannot_have_a_void_type_annotation); + } + else { + var generatorElementType = getElementTypeOfIterableIterator(returnType) || anyType; + var iterableIteratorInstantiation = createIterableIteratorType(generatorElementType); + // 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); + } + } + } } checkSpecializedSignatureDeclaration(node); } function checkTypeForDuplicateIndexSignatures(node) { - if (node.kind === 203 /* InterfaceDeclaration */) { + if (node.kind === 205 /* 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 @@ -18365,7 +20206,7 @@ var ts; var declaration = decl; if (declaration.parameters.length === 1 && declaration.parameters[0].type) { switch (declaration.parameters[0].type.kind) { - case 122 /* StringKeyword */: + case 123 /* StringKeyword */: if (!seenStringIndexer) { seenStringIndexer = true; } @@ -18373,7 +20214,7 @@ var ts; error(declaration, ts.Diagnostics.Duplicate_string_index_signature); } break; - case 120 /* NumberKeyword */: + case 121 /* NumberKeyword */: if (!seenNumericIndexer) { seenNumericIndexer = true; } @@ -18417,17 +20258,17 @@ var ts; return; } function isSuperCallExpression(n) { - return n.kind === 158 /* CallExpression */ && n.expression.kind === 91 /* SuperKeyword */; + return n.kind === 160 /* CallExpression */ && n.expression.kind === 91 /* SuperKeyword */; } function containsSuperCall(n) { if (isSuperCallExpression(n)) { return true; } switch (n.kind) { - case 163 /* FunctionExpression */: - case 201 /* FunctionDeclaration */: - case 164 /* ArrowFunction */: - case 155 /* ObjectLiteralExpression */: return false; + case 165 /* FunctionExpression */: + case 203 /* FunctionDeclaration */: + case 166 /* ArrowFunction */: + case 157 /* ObjectLiteralExpression */: return false; default: return ts.forEachChild(n, containsSuperCall); } } @@ -18435,12 +20276,12 @@ var ts; if (n.kind === 93 /* ThisKeyword */) { error(n, ts.Diagnostics.this_cannot_be_referenced_in_current_location); } - else if (n.kind !== 163 /* FunctionExpression */ && n.kind !== 201 /* FunctionDeclaration */) { + else if (n.kind !== 165 /* FunctionExpression */ && n.kind !== 203 /* FunctionDeclaration */) { ts.forEachChild(n, markThisReferencesAsErrors); } } function isInstancePropertyWithInitializer(n) { - return n.kind === 133 /* PropertyDeclaration */ && + return n.kind === 134 /* PropertyDeclaration */ && !(n.flags & 128 /* Static */) && !!n.initializer; } @@ -18457,7 +20298,7 @@ var ts; ts.forEach(node.parameters, function (p) { return p.flags & (16 /* Public */ | 32 /* Private */ | 64 /* Protected */); }); if (superCallShouldBeFirst) { var statements = node.body.statements; - if (!statements.length || statements[0].kind !== 183 /* ExpressionStatement */ || !isSuperCallExpression(statements[0].expression)) { + if (!statements.length || statements[0].kind !== 185 /* ExpressionStatement */ || !isSuperCallExpression(statements[0].expression)) { 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 { @@ -18475,7 +20316,7 @@ var ts; if (produceDiagnostics) { // Grammar checking accessors checkGrammarFunctionLikeDeclaration(node) || checkGrammarAccessor(node) || checkGrammarComputedPropertyName(node.name); - if (node.kind === 137 /* GetAccessor */) { + if (node.kind === 138 /* GetAccessor */) { if (!ts.isInAmbientContext(node) && ts.nodeIsPresent(node.body) && !(bodyContainsAReturnStatement(node.body) || bodyContainsSingleThrowStatement(node.body))) { error(node.name, ts.Diagnostics.A_get_accessor_must_return_a_value_or_consist_of_a_single_throw_statement); } @@ -18483,7 +20324,7 @@ var ts; 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 === 137 /* GetAccessor */ ? 138 /* SetAccessor */ : 137 /* GetAccessor */; + var otherKind = node.kind === 138 /* GetAccessor */ ? 139 /* SetAccessor */ : 138 /* GetAccessor */; var otherAccessor = ts.getDeclarationOfKind(node.symbol, otherKind); if (otherAccessor) { if (((node.flags & 112 /* AccessibilityModifier */) !== (otherAccessor.flags & 112 /* AccessibilityModifier */))) { @@ -18507,28 +20348,27 @@ var ts; function checkMissingDeclaration(node) { checkDecorators(node); } + function checkTypeArgumentConstraints(typeParameters, typeArguments) { + var result = true; + for (var i = 0; i < typeParameters.length; i++) { + var constraint = getConstraintOfTypeParameter(typeParameters[i]); + if (constraint) { + var typeArgument = typeArguments[i]; + result = result && checkTypeAssignableTo(getTypeFromTypeNode(typeArgument), constraint, typeArgument, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); + } + } + return result; + } function checkTypeReferenceNode(node) { - checkGrammarTypeReferenceInStrictMode(node.typeName); - return checkTypeReferenceOrExpressionWithTypeArguments(node); - } - function checkExpressionWithTypeArguments(node) { - checkGrammarExpressionWithTypeArgumentsInStrictMode(node.expression); - return checkTypeReferenceOrExpressionWithTypeArguments(node); - } - function checkTypeReferenceOrExpressionWithTypeArguments(node) { - // Grammar checking checkGrammarTypeArguments(node, node.typeArguments); - var type = getTypeFromTypeReferenceOrExpressionWithTypeArguments(node); + var type = getTypeFromTypeReference(node); if (type !== unknownType && node.typeArguments) { // Do type argument local checks only if referenced type is successfully resolved - var len = node.typeArguments.length; - for (var i = 0; i < len; i++) { - checkSourceElement(node.typeArguments[i]); - var constraint = getConstraintOfTypeParameter(type.target.typeParameters[i]); - if (produceDiagnostics && constraint) { - var typeArgument = type.typeArguments[i]; - checkTypeAssignableTo(typeArgument, constraint, node, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); - } + 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); } } } @@ -18580,9 +20420,9 @@ var ts; var signaturesToCheck; // Unnamed (call\construct) signatures in interfaces are inherited and not shadowed so examining just node symbol won't give complete answer. // Use declaring type to obtain full list of signatures. - if (!signatureDeclarationNode.name && signatureDeclarationNode.parent && signatureDeclarationNode.parent.kind === 203 /* InterfaceDeclaration */) { - ts.Debug.assert(signatureDeclarationNode.kind === 139 /* CallSignature */ || signatureDeclarationNode.kind === 140 /* ConstructSignature */); - var signatureKind = signatureDeclarationNode.kind === 139 /* CallSignature */ ? 0 /* Call */ : 1 /* Construct */; + if (!signatureDeclarationNode.name && signatureDeclarationNode.parent && signatureDeclarationNode.parent.kind === 205 /* InterfaceDeclaration */) { + ts.Debug.assert(signatureDeclarationNode.kind === 140 /* CallSignature */ || signatureDeclarationNode.kind === 141 /* ConstructSignature */); + var signatureKind = signatureDeclarationNode.kind === 140 /* CallSignature */ ? 0 /* Call */ : 1 /* Construct */; var containingSymbol = getSymbolOfNode(signatureDeclarationNode.parent); var containingType = getDeclaredTypeOfSymbol(containingSymbol); signaturesToCheck = getSignaturesOfType(containingType, signatureKind); @@ -18600,7 +20440,7 @@ var ts; } function getEffectiveDeclarationFlags(n, flagsToCheck) { var flags = ts.getCombinedNodeFlags(n); - if (n.parent.kind !== 203 /* InterfaceDeclaration */ && ts.isInAmbientContext(n)) { + if (n.parent.kind !== 205 /* InterfaceDeclaration */ && ts.isInAmbientContext(n)) { if (!(flags & 2 /* Ambient */)) { // It is nested in an ambient context, which means it is automatically exported flags |= 1 /* Export */; @@ -18683,7 +20523,7 @@ var ts; // TODO(jfreeman): These are methods, so handle computed name case if (node.name && subsequentNode.name && node.name.text === subsequentNode.name.text) { // the only situation when this is possible (same kind\same name but different symbol) - mixed static and instance class members - ts.Debug.assert(node.kind === 135 /* MethodDeclaration */ || node.kind === 134 /* MethodSignature */); + ts.Debug.assert(node.kind === 136 /* MethodDeclaration */ || node.kind === 135 /* MethodSignature */); ts.Debug.assert((node.flags & 128 /* Static */) !== (subsequentNode.flags & 128 /* Static */)); var diagnostic = node.flags & 128 /* Static */ ? ts.Diagnostics.Function_overload_must_be_static : ts.Diagnostics.Function_overload_must_not_be_static; error(errorNode_1, diagnostic); @@ -18712,7 +20552,7 @@ var ts; var current = declarations[_i]; var node = current; var inAmbientContext = ts.isInAmbientContext(node); - var inAmbientContextOrInterface = node.parent.kind === 203 /* InterfaceDeclaration */ || node.parent.kind === 146 /* TypeLiteral */ || inAmbientContext; + var inAmbientContextOrInterface = node.parent.kind === 205 /* InterfaceDeclaration */ || node.parent.kind === 148 /* TypeLiteral */ || inAmbientContext; if (inAmbientContextOrInterface) { // check if declarations are consecutive only if they are non-ambient // 1. ambient declarations can be interleaved @@ -18723,7 +20563,7 @@ var ts; // 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 === 201 /* FunctionDeclaration */ || node.kind === 135 /* MethodDeclaration */ || node.kind === 134 /* MethodSignature */ || node.kind === 136 /* Constructor */) { + if (node.kind === 203 /* FunctionDeclaration */ || node.kind === 136 /* MethodDeclaration */ || node.kind === 135 /* MethodSignature */ || node.kind === 137 /* Constructor */) { var currentNodeFlags = getEffectiveDeclarationFlags(node, flagsToCheck); someNodeFlags |= currentNodeFlags; allNodeFlags &= currentNodeFlags; @@ -18846,16 +20686,16 @@ var ts; } function getDeclarationSpaces(d) { switch (d.kind) { - case 203 /* InterfaceDeclaration */: + case 205 /* InterfaceDeclaration */: return 2097152 /* ExportType */; - case 206 /* ModuleDeclaration */: + case 208 /* ModuleDeclaration */: return d.name.kind === 8 /* StringLiteral */ || ts.getModuleInstanceState(d) !== 0 /* NonInstantiated */ ? 4194304 /* ExportNamespace */ | 1048576 /* ExportValue */ : 4194304 /* ExportNamespace */; - case 202 /* ClassDeclaration */: - case 205 /* EnumDeclaration */: + case 204 /* ClassDeclaration */: + case 207 /* EnumDeclaration */: return 2097152 /* ExportType */ | 1048576 /* ExportValue */; - case 209 /* ImportEqualsDeclaration */: + case 211 /* ImportEqualsDeclaration */: var result = 0; var target = resolveAlias(getSymbolOfNode(d)); ts.forEach(target.declarations, function (d) { result |= getDeclarationSpaces(d); }); @@ -18870,23 +20710,23 @@ var ts; var expression = node.expression; var exprType = checkExpression(expression); switch (node.parent.kind) { - case 202 /* ClassDeclaration */: + case 204 /* ClassDeclaration */: var classSymbol = getSymbolOfNode(node.parent); var classConstructorType = getTypeOfSymbol(classSymbol); var classDecoratorType = instantiateSingleCallFunctionType(getGlobalClassDecoratorType(), [classConstructorType]); checkTypeAssignableTo(exprType, classDecoratorType, node); break; - case 133 /* PropertyDeclaration */: + case 134 /* PropertyDeclaration */: checkTypeAssignableTo(exprType, getGlobalPropertyDecoratorType(), node); break; - case 135 /* MethodDeclaration */: - case 137 /* GetAccessor */: - case 138 /* SetAccessor */: + case 136 /* MethodDeclaration */: + case 138 /* GetAccessor */: + case 139 /* SetAccessor */: var methodType = getTypeOfNode(node.parent); var methodDecoratorType = instantiateSingleCallFunctionType(getGlobalMethodDecoratorType(), [methodType]); checkTypeAssignableTo(exprType, methodDecoratorType, node); break; - case 130 /* Parameter */: + case 131 /* Parameter */: checkTypeAssignableTo(exprType, getGlobalParameterDecoratorType(), node); break; } @@ -18896,14 +20736,14 @@ var ts; // When we are emitting type metadata for decorators, we need to try to check the type // as if it were an expression so that we can emit the type in a value position when we // serialize the type metadata. - if (node && node.kind === 142 /* TypeReference */) { + if (node && node.kind === 144 /* TypeReference */) { var type = getTypeFromTypeNode(node); - var shouldCheckIfUnknownType = type === unknownType && compilerOptions.separateCompilation; - if (!type || (!shouldCheckIfUnknownType && type.flags & (1048703 /* Intrinsic */ | 132 /* NumberLike */ | 258 /* StringLike */))) { + var shouldCheckIfUnknownType = type === unknownType && compilerOptions.isolatedModules; + if (!type || (!shouldCheckIfUnknownType && type.flags & (2097279 /* Intrinsic */ | 132 /* NumberLike */ | 258 /* StringLike */))) { return; } if (shouldCheckIfUnknownType || type.symbol.valueDeclaration) { - checkExpressionOrQualifiedName(node.typeName); + checkExpression(node.typeName); } } } @@ -18913,19 +20753,19 @@ var ts; */ function checkTypeAnnotationAsExpression(node) { switch (node.kind) { - case 133 /* PropertyDeclaration */: + case 134 /* PropertyDeclaration */: checkTypeNodeAsExpression(node.type); break; - case 130 /* Parameter */: + case 131 /* Parameter */: checkTypeNodeAsExpression(node.type); break; - case 135 /* MethodDeclaration */: + case 136 /* MethodDeclaration */: checkTypeNodeAsExpression(node.type); break; - case 137 /* GetAccessor */: + case 138 /* GetAccessor */: checkTypeNodeAsExpression(node.type); break; - case 138 /* SetAccessor */: + case 139 /* SetAccessor */: checkTypeNodeAsExpression(getSetAccessorTypeAnnotationNode(node)); break; } @@ -18948,51 +20788,50 @@ var ts; 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_Specify_experimentalDecorators_to_remove_this_warning); + } if (compilerOptions.emitDecoratorMetadata) { // we only need to perform these checks if we are emitting serialized type metadata for the target of a decorator. switch (node.kind) { - case 202 /* ClassDeclaration */: + case 204 /* ClassDeclaration */: var constructor = ts.getFirstConstructorWithBody(node); if (constructor) { checkParameterTypeAnnotationsAsExpressions(constructor); } break; - case 135 /* MethodDeclaration */: + case 136 /* MethodDeclaration */: checkParameterTypeAnnotationsAsExpressions(node); // fall-through - case 138 /* SetAccessor */: - case 137 /* GetAccessor */: - case 133 /* PropertyDeclaration */: - case 130 /* Parameter */: + case 139 /* SetAccessor */: + case 138 /* GetAccessor */: + case 134 /* PropertyDeclaration */: + case 131 /* Parameter */: checkTypeAnnotationAsExpression(node); break; } } emitDecorate = true; - if (node.kind === 130 /* Parameter */) { + if (node.kind === 131 /* Parameter */) { emitParam = true; } ts.forEach(node.decorators, checkDecorator); } function checkFunctionDeclaration(node) { if (produceDiagnostics) { - checkFunctionLikeDeclaration(node) || - checkGrammarDisallowedModifiersInBlockOrObjectLiteralExpression(node) || - checkGrammarFunctionName(node.name) || - checkGrammarForGenerator(node); + checkFunctionLikeDeclaration(node) || checkGrammarForGenerator(node); checkCollisionWithCapturedSuperVariable(node, node.name); checkCollisionWithCapturedThisVariable(node, node.name); checkCollisionWithRequireExportsInGeneratedCode(node, node.name); } } function checkFunctionLikeDeclaration(node) { - checkGrammarDeclarationNameInStrictMode(node); checkDecorators(node); checkSignatureDeclaration(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 === 128 /* ComputedPropertyName */) { + if (node.name && node.name.kind === 129 /* ComputedPropertyName */) { // This check will account for methods in class/interface declarations, // as well as accessors in classes/object literals checkComputedPropertyName(node.name); @@ -19020,25 +20859,33 @@ var ts; if (node.type && !isAccessor(node.kind) && !node.asteriskToken) { checkIfNonVoidFunctionHasReturnExpressionsOrSingleThrowStatment(node, getTypeFromTypeNode(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 (compilerOptions.noImplicitAny && ts.nodeIsMissing(node.body) && !node.type && !isPrivateWithinAmbient(node)) { - reportImplicitAnyError(node, anyType); + 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 (compilerOptions.noImplicitAny && ts.nodeIsMissing(node.body) && !isPrivateWithinAmbient(node)) { + reportImplicitAnyError(node, anyType); + } + if (node.asteriskToken && 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)); + } } } function checkBlock(node) { // Grammar checking for SyntaxKind.Block - if (node.kind === 180 /* Block */) { + if (node.kind === 182 /* Block */) { checkGrammarStatementInAmbientContext(node); } ts.forEach(node.statements, checkSourceElement); - if (ts.isFunctionBlock(node) || node.kind === 207 /* ModuleBlock */) { + if (ts.isFunctionBlock(node) || node.kind === 209 /* ModuleBlock */) { checkFunctionExpressionBodies(node); } } function checkCollisionWithArgumentsInGeneratedCode(node) { // no rest parameters \ declaration context \ overload - no codegen impact - if (!ts.hasRestParameters(node) || ts.isInAmbientContext(node) || ts.nodeIsMissing(node.body)) { + if (!ts.hasRestParameter(node) || ts.isInAmbientContext(node) || ts.nodeIsMissing(node.body)) { return; } ts.forEach(node.parameters, function (p) { @@ -19051,12 +20898,12 @@ var ts; if (!(identifier && identifier.text === name)) { return false; } - if (node.kind === 133 /* PropertyDeclaration */ || - node.kind === 132 /* PropertySignature */ || - node.kind === 135 /* MethodDeclaration */ || - node.kind === 134 /* MethodSignature */ || - node.kind === 137 /* GetAccessor */ || - node.kind === 138 /* SetAccessor */) { + if (node.kind === 134 /* PropertyDeclaration */ || + node.kind === 133 /* PropertySignature */ || + node.kind === 136 /* MethodDeclaration */ || + node.kind === 135 /* MethodSignature */ || + node.kind === 138 /* GetAccessor */ || + node.kind === 139 /* SetAccessor */) { // it is ok to have member named '_super' or '_this' - member access is always qualified return false; } @@ -19065,7 +20912,7 @@ var ts; return false; } var root = ts.getRootDeclaration(node); - if (root.kind === 130 /* Parameter */ && ts.nodeIsMissing(root.parent.body)) { + if (root.kind === 131 /* Parameter */ && ts.nodeIsMissing(root.parent.body)) { // just an overload - no codegen impact return false; } @@ -19098,7 +20945,7 @@ var ts; return; } // bubble up and find containing type - var enclosingClass = ts.getAncestor(node, 202 /* ClassDeclaration */); + var enclosingClass = ts.getAncestor(node, 204 /* ClassDeclaration */); // if containing type was not found or it is ambient - exit (no codegen) if (!enclosingClass || ts.isInAmbientContext(enclosingClass)) { return; @@ -19118,12 +20965,12 @@ var ts; return; } // Uninstantiated modules shouldnt do this check - if (node.kind === 206 /* ModuleDeclaration */ && ts.getModuleInstanceState(node) !== 1 /* Instantiated */) { + if (node.kind === 208 /* 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 === 228 /* SourceFile */ && ts.isExternalModule(parent)) { + if (parent.kind === 230 /* SourceFile */ && ts.isExternalModule(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)); } @@ -19158,7 +21005,7 @@ var ts; // 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 === 199 /* VariableDeclaration */ && !node.initializer) { + if (node.kind === 201 /* VariableDeclaration */ && !node.initializer) { return; } var symbol = getSymbolOfNode(node); @@ -19168,24 +21015,24 @@ var ts; localDeclarationSymbol !== symbol && localDeclarationSymbol.flags & 2 /* BlockScopedVariable */) { if (getDeclarationFlagsFromSymbol(localDeclarationSymbol) & 12288 /* BlockScoped */) { - var varDeclList = ts.getAncestor(localDeclarationSymbol.valueDeclaration, 200 /* VariableDeclarationList */); - var container = varDeclList.parent.kind === 181 /* VariableStatement */ && varDeclList.parent.parent + var varDeclList = ts.getAncestor(localDeclarationSymbol.valueDeclaration, 202 /* VariableDeclarationList */); + var container = varDeclList.parent.kind === 183 /* 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 === 180 /* Block */ && ts.isFunctionLike(container.parent) || - container.kind === 207 /* ModuleBlock */ || - container.kind === 206 /* ModuleDeclaration */ || - container.kind === 228 /* SourceFile */); + (container.kind === 182 /* Block */ && ts.isFunctionLike(container.parent) || + container.kind === 209 /* ModuleBlock */ || + container.kind === 208 /* ModuleDeclaration */ || + container.kind === 230 /* 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_9 = symbolToString(localDeclarationSymbol); - error(node, ts.Diagnostics.Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1, name_9, name_9); + var name_13 = symbolToString(localDeclarationSymbol); + error(node, ts.Diagnostics.Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1, name_13, name_13); } } } @@ -19193,7 +21040,7 @@ var ts; } // Check that a parameter initializer contains no references to parameters declared to the right of itself function checkParameterInitializer(node) { - if (ts.getRootDeclaration(node).kind !== 130 /* Parameter */) { + if (ts.getRootDeclaration(node).kind !== 131 /* Parameter */) { return; } var func = ts.getContainingFunction(node); @@ -19204,7 +21051,7 @@ var ts; // check FunctionLikeDeclaration.locals (stores parameters\function local variable) // if it contains entry with a specified name and if this entry matches the resolved symbol if (referencedSymbol && referencedSymbol !== unknownSymbol && getSymbol(func.locals, referencedSymbol.name, 107455 /* Value */) === referencedSymbol) { - if (referencedSymbol.valueDeclaration.kind === 130 /* Parameter */) { + if (referencedSymbol.valueDeclaration.kind === 131 /* Parameter */) { if (referencedSymbol.valueDeclaration === node) { error(n, ts.Diagnostics.Parameter_0_cannot_be_referenced_in_its_initializer, ts.declarationNameToString(node.name)); return; @@ -19224,14 +21071,13 @@ var ts; } // Check variable, parameter, or property declaration function checkVariableLikeDeclaration(node) { - checkGrammarDeclarationNameInStrictMode(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 === 128 /* ComputedPropertyName */) { + if (node.name.kind === 129 /* ComputedPropertyName */) { checkComputedPropertyName(node.name); if (node.initializer) { checkExpressionCached(node.initializer); @@ -19242,7 +21088,7 @@ var ts; 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 === 130 /* Parameter */ && ts.nodeIsMissing(ts.getContainingFunction(node).body)) { + if (node.initializer && ts.getRootDeclaration(node).kind === 131 /* Parameter */ && ts.nodeIsMissing(ts.getContainingFunction(node).body)) { error(node, ts.Diagnostics.A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation); return; } @@ -19274,10 +21120,10 @@ var ts; checkTypeAssignableTo(checkExpressionCached(node.initializer), declarationType, node, undefined); } } - if (node.kind !== 133 /* PropertyDeclaration */ && node.kind !== 132 /* PropertySignature */) { + if (node.kind !== 134 /* PropertyDeclaration */ && node.kind !== 133 /* PropertySignature */) { // We know we don't have a binding pattern or computed name here checkExportsOnMergedDeclarations(node); - if (node.kind === 199 /* VariableDeclaration */ || node.kind === 153 /* BindingElement */) { + if (node.kind === 201 /* VariableDeclaration */ || node.kind === 155 /* BindingElement */) { checkVarDeclaredNamesNotShadowed(node); } checkCollisionWithCapturedSuperVariable(node, node.name); @@ -19295,7 +21141,7 @@ var ts; } function checkVariableStatement(node) { // Grammar checking - checkGrammarDecorators(node) || checkGrammarDisallowedModifiersInBlockOrObjectLiteralExpression(node) || checkGrammarModifiers(node) || checkGrammarVariableDeclarationList(node.declarationList) || checkGrammarForDisallowedLetOrConstStatement(node); + checkGrammarDecorators(node) || checkGrammarModifiers(node) || checkGrammarVariableDeclarationList(node.declarationList) || checkGrammarForDisallowedLetOrConstStatement(node); ts.forEach(node.declarationList.declarations, checkSourceElement); } function checkGrammarDisallowedModifiersInBlockOrObjectLiteralExpression(node) { @@ -19307,7 +21153,7 @@ var ts; } function inBlockOrObjectLiteralExpression(node) { while (node) { - if (node.kind === 180 /* Block */ || node.kind === 155 /* ObjectLiteralExpression */) { + if (node.kind === 182 /* Block */ || node.kind === 157 /* ObjectLiteralExpression */) { return true; } node = node.parent; @@ -19340,12 +21186,12 @@ var ts; function checkForStatement(node) { // Grammar checking if (!checkGrammarStatementInAmbientContext(node)) { - if (node.initializer && node.initializer.kind == 200 /* VariableDeclarationList */) { + if (node.initializer && node.initializer.kind === 202 /* VariableDeclarationList */) { checkGrammarVariableDeclarationList(node.initializer); } } if (node.initializer) { - if (node.initializer.kind === 200 /* VariableDeclarationList */) { + if (node.initializer.kind === 202 /* VariableDeclarationList */) { ts.forEach(node.initializer.declarations, checkVariableDeclaration); } else { @@ -19365,14 +21211,14 @@ var ts; // 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 === 200 /* VariableDeclarationList */) { + if (node.initializer.kind === 202 /* VariableDeclarationList */) { checkForInOrForOfVariableDeclaration(node); } else { var varExpr = node.initializer; var iteratedType = checkRightHandSideOfForOf(node.expression); // There may be a destructuring assignment on the left side - if (varExpr.kind === 154 /* ArrayLiteralExpression */ || varExpr.kind === 155 /* ObjectLiteralExpression */) { + if (varExpr.kind === 156 /* ArrayLiteralExpression */ || varExpr.kind === 157 /* 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. @@ -19385,7 +21231,7 @@ var ts; // 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 - // getIteratedType. + // getElementTypeOfIterable. if (iteratedType) { checkTypeAssignableTo(iteratedType, leftType, varExpr, undefined); } @@ -19401,7 +21247,7 @@ var ts; // 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 === 200 /* VariableDeclarationList */) { + if (node.initializer.kind === 202 /* 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); @@ -19415,10 +21261,10 @@ var ts; // 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 === 154 /* ArrayLiteralExpression */ || varExpr.kind === 155 /* ObjectLiteralExpression */) { + if (varExpr.kind === 156 /* ArrayLiteralExpression */ || varExpr.kind === 157 /* ObjectLiteralExpression */) { error(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern); } - else if (!allConstituentTypesHaveKind(leftType, 1 /* Any */ | 258 /* StringLike */)) { + else if (!isTypeAnyOrAllConstituentTypesHaveKind(leftType, 258 /* StringLike */)) { error(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any); } else { @@ -19429,7 +21275,7 @@ var ts; var rightType = checkExpression(node.expression); // 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 (!allConstituentTypesHaveKind(rightType, 1 /* Any */ | 48128 /* ObjectType */ | 512 /* TypeParameter */)) { + if (!isTypeAnyOrAllConstituentTypesHaveKind(rightType, 48128 /* ObjectType */ | 512 /* TypeParameter */)) { 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); @@ -19447,11 +21293,11 @@ var ts; return checkIteratedTypeOrElementType(expressionType, rhsExpression, true); } function checkIteratedTypeOrElementType(inputType, errorNode, allowStringInput) { - if (inputType.flags & 1 /* Any */) { + if (isTypeAny(inputType)) { return inputType; } if (languageVersion >= 2 /* ES6 */) { - return checkIteratedType(inputType, errorNode) || anyType; + return checkElementTypeOfIterable(inputType, errorNode); } if (allowStringInput) { return checkElementTypeOfArrayOrString(inputType, errorNode); @@ -19468,88 +21314,127 @@ var ts; /** * When errorNode is undefined, it means we should not report any errors. */ - function checkIteratedType(iterable, errorNode) { - ts.Debug.assert(languageVersion >= 2 /* ES6 */); - var iteratedType = getIteratedType(iterable, errorNode); + function checkElementTypeOfIterable(iterable, errorNode) { + var elementType = getElementTypeOfIterable(iterable, errorNode); // Now even though we have extracted the iteratedType, we will have to validate that the type // passed in is actually an Iterable. - if (errorNode && iteratedType) { - checkTypeAssignableTo(iterable, createIterableType(iteratedType), errorNode); + if (errorNode && elementType) { + checkTypeAssignableTo(iterable, createIterableType(elementType), errorNode); } - return iteratedType; - function getIteratedType(iterable, errorNode) { - // 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]: { // iteratorFunction - // (): { // iterator - // next: { // iteratorNextFunction - // (): { // iteratorNextResult - // value: T // iteratorNextValue - // } - // } - // } - // } - // } - // - // 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'. - if (allConstituentTypesHaveKind(iterable, 1 /* Any */)) { - return undefined; - } + return elementType || anyType; + } + /** + * 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]: { // iteratorFunction + * (): Iterator + * } + * } + * + * 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'. + */ + function getElementTypeOfIterable(type, errorNode) { + if (isTypeAny(type)) { + return undefined; + } + var typeAsIterable = type; + if (!typeAsIterable.iterableElementType) { // As an optimization, if the type is instantiated directly using the globalIterableType (Iterable), // then just grab its type argument. - if ((iterable.flags & 4096 /* Reference */) && iterable.target === globalIterableType) { - return iterable.typeArguments[0]; + if ((type.flags & 4096 /* Reference */) && type.target === globalIterableType) { + typeAsIterable.iterableElementType = type.typeArguments[0]; } - var iteratorFunction = getTypeOfPropertyOfType(iterable, ts.getPropertyNameForKnownSymbolName("iterator")); - if (iteratorFunction && allConstituentTypesHaveKind(iteratorFunction, 1 /* Any */)) { - return undefined; - } - var iteratorFunctionSignatures = iteratorFunction ? getSignaturesOfType(iteratorFunction, 0 /* Call */) : emptyArray; - if (iteratorFunctionSignatures.length === 0) { - if (errorNode) { - error(errorNode, ts.Diagnostics.Type_must_have_a_Symbol_iterator_method_that_returns_an_iterator); + else { + var iteratorFunction = getTypeOfPropertyOfType(type, ts.getPropertyNameForKnownSymbolName("iterator")); + if (isTypeAny(iteratorFunction)) { + return undefined; } - return undefined; - } - var iterator = getUnionType(ts.map(iteratorFunctionSignatures, getReturnTypeOfSignature)); - if (allConstituentTypesHaveKind(iterator, 1 /* Any */)) { - return undefined; - } - var iteratorNextFunction = getTypeOfPropertyOfType(iterator, "next"); - if (iteratorNextFunction && allConstituentTypesHaveKind(iteratorNextFunction, 1 /* Any */)) { - return undefined; - } - var iteratorNextFunctionSignatures = iteratorNextFunction ? getSignaturesOfType(iteratorNextFunction, 0 /* Call */) : emptyArray; - if (iteratorNextFunctionSignatures.length === 0) { - if (errorNode) { - error(errorNode, ts.Diagnostics.An_iterator_must_have_a_next_method); + var iteratorFunctionSignatures = iteratorFunction ? getSignaturesOfType(iteratorFunction, 0 /* Call */) : emptyArray; + if (iteratorFunctionSignatures.length === 0) { + if (errorNode) { + error(errorNode, ts.Diagnostics.Type_must_have_a_Symbol_iterator_method_that_returns_an_iterator); + } + return undefined; } - return undefined; + typeAsIterable.iterableElementType = getElementTypeOfIterator(getUnionType(ts.map(iteratorFunctionSignatures, getReturnTypeOfSignature)), errorNode); } - var iteratorNextResult = getUnionType(ts.map(iteratorNextFunctionSignatures, getReturnTypeOfSignature)); - if (allConstituentTypesHaveKind(iteratorNextResult, 1 /* Any */)) { - return undefined; - } - var iteratorNextValue = getTypeOfPropertyOfType(iteratorNextResult, "value"); - if (!iteratorNextValue) { - if (errorNode) { - error(errorNode, ts.Diagnostics.The_type_returned_by_the_next_method_of_an_iterator_must_have_a_value_property); - } - return undefined; - } - return iteratorNextValue; } + return typeAsIterable.iterableElementType; + } + /** + * This function has very similar logic as getElementTypeOfIterable, except that it operates on + * Iterators instead of Iterables. Here is the structure: + * + * { // iterator + * next: { // iteratorNextFunction + * (): { // iteratorNextResult + * value: T // iteratorNextValue + * } + * } + * } + * + */ + function getElementTypeOfIterator(type, errorNode) { + if (isTypeAny(type)) { + return undefined; + } + var typeAsIterator = type; + if (!typeAsIterator.iteratorElementType) { + // As an optimization, if the type is instantiated directly using the globalIteratorType (Iterator), + // then just grab its type argument. + if ((type.flags & 4096 /* Reference */) && type.target === globalIteratorType) { + typeAsIterator.iteratorElementType = type.typeArguments[0]; + } + else { + var iteratorNextFunction = getTypeOfPropertyOfType(type, "next"); + if (isTypeAny(iteratorNextFunction)) { + return undefined; + } + var iteratorNextFunctionSignatures = iteratorNextFunction ? getSignaturesOfType(iteratorNextFunction, 0 /* Call */) : emptyArray; + if (iteratorNextFunctionSignatures.length === 0) { + if (errorNode) { + error(errorNode, ts.Diagnostics.An_iterator_must_have_a_next_method); + } + return undefined; + } + var iteratorNextResult = getUnionType(ts.map(iteratorNextFunctionSignatures, getReturnTypeOfSignature)); + if (isTypeAny(iteratorNextResult)) { + return undefined; + } + var iteratorNextValue = getTypeOfPropertyOfType(iteratorNextResult, "value"); + if (!iteratorNextValue) { + if (errorNode) { + error(errorNode, ts.Diagnostics.The_type_returned_by_the_next_method_of_an_iterator_must_have_a_value_property); + } + return undefined; + } + typeAsIterator.iteratorElementType = iteratorNextValue; + } + } + return typeAsIterator.iteratorElementType; + } + function getElementTypeOfIterableIterator(type) { + if (isTypeAny(type)) { + return undefined; + } + // As an optimization, if the type is instantiated directly using the globalIterableIteratorType (IterableIterator), + // then just grab its type argument. + if ((type.flags & 4096 /* Reference */) && type.target === globalIterableIteratorType) { + return type.typeArguments[0]; + } + return getElementTypeOfIterable(type, undefined) || + getElementTypeOfIterator(type, undefined); } /** * This function does the following steps: @@ -19615,7 +21500,7 @@ var ts; // TODO: Check that target label is valid } function isGetAccessorWithAnnotatatedSetAccessor(node) { - return !!(node.kind === 137 /* GetAccessor */ && getSetAccessorTypeAnnotationNode(ts.getDeclarationOfKind(node.symbol, 138 /* SetAccessor */))); + return !!(node.kind === 138 /* GetAccessor */ && getSetAccessorTypeAnnotationNode(ts.getDeclarationOfKind(node.symbol, 139 /* SetAccessor */))); } function checkReturnStatement(node) { // Grammar checking @@ -19628,31 +21513,32 @@ var ts; if (node.expression) { var func = ts.getContainingFunction(node); if (func) { - var returnType = getReturnTypeOfSignature(getSignatureFromDeclaration(func)); + var signature = getSignatureFromDeclaration(func); + var returnType = getReturnTypeOfSignature(signature); var exprType = checkExpressionCached(node.expression); - if (func.kind === 138 /* SetAccessor */) { + if (func.asteriskToken) { + // 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 === 139 /* SetAccessor */) { error(node.expression, ts.Diagnostics.Setters_cannot_return_a_value); } - else { - if (func.kind === 136 /* Constructor */) { - if (!isTypeAssignableTo(exprType, returnType)) { - error(node.expression, ts.Diagnostics.Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class); - } - } - else if (func.type || isGetAccessorWithAnnotatatedSetAccessor(func)) { - checkTypeAssignableTo(exprType, returnType, node.expression, undefined); + else if (func.kind === 137 /* Constructor */) { + if (!isTypeAssignableTo(exprType, returnType)) { + error(node.expression, ts.Diagnostics.Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class); } } + else if (func.type || isGetAccessorWithAnnotatatedSetAccessor(func) || signature.typePredicate) { + checkTypeAssignableTo(exprType, returnType, node.expression, undefined); + } } } } function checkWithStatement(node) { - // Grammar checking for withStatement - if (!checkGrammarStatementInAmbientContext(node)) { - if (node.parserContextFlags & 1 /* StrictMode */) { - grammarErrorOnFirstToken(node, ts.Diagnostics.with_statements_are_not_allowed_in_strict_mode); - } - } + checkGrammarStatementInAmbientContext(node); checkExpression(node.expression); error(node.expression, ts.Diagnostics.All_symbols_within_a_with_block_will_be_resolved_to_any); } @@ -19664,7 +21550,7 @@ var ts; var expressionType = checkExpression(node.expression); ts.forEach(node.caseBlock.clauses, function (clause) { // Grammar check for duplicate default clauses, skip if we already report duplicate default clause - if (clause.kind === 222 /* DefaultClause */ && !hasDuplicateDefaultClause) { + if (clause.kind === 224 /* DefaultClause */ && !hasDuplicateDefaultClause) { if (firstDefaultClause === undefined) { firstDefaultClause = clause; } @@ -19676,7 +21562,7 @@ var ts; hasDuplicateDefaultClause = true; } } - if (produceDiagnostics && clause.kind === 221 /* CaseClause */) { + if (produceDiagnostics && clause.kind === 223 /* 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 assignable to or from the type of the 'switch' expression. @@ -19697,7 +21583,7 @@ var ts; if (ts.isFunctionLike(current)) { break; } - if (current.kind === 195 /* LabeledStatement */ && current.label.text === node.label.text) { + if (current.kind === 197 /* 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)); break; @@ -19745,9 +21631,6 @@ var ts; grammarErrorOnNode(localSymbol.valueDeclaration, ts.Diagnostics.Cannot_redeclare_identifier_0_in_catch_clause, identifierName); } } - // 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 - checkGrammarEvalOrArgumentsInStrictMode(node, catchClause.variableDeclaration.name); } } checkBlock(catchClause.block); @@ -19767,7 +21650,7 @@ var ts; checkIndexConstraintForProperty(prop, propType, type, declaredStringIndexer, stringIndexType, 0 /* String */); checkIndexConstraintForProperty(prop, propType, type, declaredNumberIndexer, numberIndexType, 1 /* Number */); }); - if (type.flags & 1024 /* Class */ && type.symbol.valueDeclaration.kind === 202 /* ClassDeclaration */) { + if (type.flags & 1024 /* Class */ && type.symbol.valueDeclaration.kind === 204 /* ClassDeclaration */) { var classDeclaration = type.symbol.valueDeclaration; for (var _i = 0, _a = classDeclaration.members; _i < _a.length; _i++) { var member = _a[_i]; @@ -19805,7 +21688,7 @@ var ts; // perform property check if property or indexer is declared in 'type' // this allows to rule out cases when both property and indexer are inherited from the base class var errorNode; - if (prop.valueDeclaration.name.kind === 128 /* ComputedPropertyName */ || prop.parent === containingType.symbol) { + if (prop.valueDeclaration.name.kind === 129 /* ComputedPropertyName */ || prop.parent === containingType.symbol) { errorNode = prop.valueDeclaration; } else if (indexDeclaration) { @@ -19861,11 +21744,7 @@ var ts; return unknownType; } function checkClassDeclaration(node) { - checkGrammarDeclarationNameInStrictMode(node); // Grammar checking - if (node.parent.kind !== 207 /* ModuleBlock */ && node.parent.kind !== 228 /* SourceFile */) { - grammarErrorOnNode(node, ts.Diagnostics.class_declarations_are_only_supported_directly_inside_a_module_or_as_a_top_level_declaration); - } if (!node.name && !(node.flags & 256 /* Default */)) { grammarErrorOnFirstToken(node, ts.Diagnostics.A_class_declaration_without_the_default_modifier_must_have_a_name); } @@ -19883,36 +21762,42 @@ var ts; var staticType = getTypeOfSymbol(symbol); var baseTypeNode = ts.getClassExtendsHeritageClauseElement(node); if (baseTypeNode) { - if (!ts.isSupportedExpressionWithTypeArguments(baseTypeNode)) { - error(baseTypeNode.expression, ts.Diagnostics.Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_class_extends_clauses); - } emitExtends = emitExtends || !ts.isInAmbientContext(node); - checkExpressionWithTypeArguments(baseTypeNode); - } - var baseTypes = getBaseTypes(type); - if (baseTypes.length) { - if (produceDiagnostics) { + var baseTypes = getBaseTypes(type); + if (baseTypes.length && produceDiagnostics) { var baseType = baseTypes[0]; + var staticBaseType = getBaseConstructorTypeOfClass(type); + if (baseTypeNode.typeArguments) { + ts.forEach(baseTypeNode.typeArguments, checkSourceElement); + for (var _i = 0, _a = getConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments); _i < _a.length; _i++) { + var constructor = _a[_i]; + if (!checkTypeArgumentConstraints(constructor.typeParameters, baseTypeNode.typeArguments)) { + break; + } + } + } checkTypeAssignableTo(type, baseType, node.name || node, ts.Diagnostics.Class_0_incorrectly_extends_base_class_1); - var staticBaseType = getTypeOfSymbol(baseType.symbol); - checkTypeAssignableTo(staticType, getTypeWithoutConstructors(staticBaseType), node.name || node, ts.Diagnostics.Class_static_side_0_incorrectly_extends_base_class_static_side_1); - if (baseType.symbol !== resolveEntityName(baseTypeNode.expression, 107455 /* Value */)) { - error(baseTypeNode, ts.Diagnostics.Type_name_0_in_extends_clause_does_not_reference_constructor_function_for_0, typeToString(baseType)); + checkTypeAssignableTo(staticType, getTypeWithoutSignatures(staticBaseType), node.name || node, ts.Diagnostics.Class_static_side_0_incorrectly_extends_base_class_static_side_1); + if (!(staticBaseType.symbol && staticBaseType.symbol.flags & 32 /* Class */)) { + // 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); + if (ts.forEach(constructors, function (sig) { return getReturnTypeOfSignature(sig) !== baseType; })) { + error(baseTypeNode.expression, ts.Diagnostics.Base_constructors_must_all_have_the_same_return_type); + } } checkKindsOfPropertyMemberOverrides(type, baseType); } } - if (baseTypes.length || (baseTypeNode && compilerOptions.separateCompilation)) { - // Check that base type can be evaluated as expression - checkExpressionOrQualifiedName(baseTypeNode.expression); - } var implementedTypeNodes = ts.getClassImplementsHeritageClauseElements(node); if (implementedTypeNodes) { ts.forEach(implementedTypeNodes, function (typeRefNode) { if (!ts.isSupportedExpressionWithTypeArguments(typeRefNode)) { error(typeRefNode.expression, ts.Diagnostics.A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments); } - checkExpressionWithTypeArguments(typeRefNode); + checkTypeReferenceNode(typeRefNode); if (produceDiagnostics) { var t = getTypeFromTypeNode(typeRefNode); if (t !== unknownType) { @@ -20000,7 +21885,7 @@ var ts; } } function isAccessor(kind) { - return kind === 137 /* GetAccessor */ || kind === 138 /* SetAccessor */; + return kind === 138 /* GetAccessor */ || kind === 139 /* SetAccessor */; } function areTypeParametersIdentical(list1, list2) { if (!list1 && !list2) { @@ -20064,13 +21949,13 @@ var ts; } function checkInterfaceDeclaration(node) { // Grammar checking - checkGrammarDeclarationNameInStrictMode(node) || checkGrammarDecorators(node) || checkGrammarModifiers(node) || checkGrammarInterfaceDeclaration(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); - var firstInterfaceDecl = ts.getDeclarationOfKind(symbol, 203 /* InterfaceDeclaration */); + var firstInterfaceDecl = ts.getDeclarationOfKind(symbol, 205 /* InterfaceDeclaration */); if (symbol.declarations.length > 1) { if (node !== firstInterfaceDecl && !areTypeParametersIdentical(firstInterfaceDecl.typeParameters, node.typeParameters)) { error(node.name, ts.Diagnostics.All_declarations_of_an_interface_must_have_identical_type_parameters); @@ -20092,7 +21977,7 @@ var ts; if (!ts.isSupportedExpressionWithTypeArguments(heritageElement)) { error(heritageElement.expression, ts.Diagnostics.An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments); } - checkExpressionWithTypeArguments(heritageElement); + checkTypeReferenceNode(heritageElement); }); ts.forEach(node.members, checkSourceElement); if (produceDiagnostics) { @@ -20114,7 +21999,7 @@ var ts; var ambient = ts.isInAmbientContext(node); var enumIsConst = ts.isConst(node); ts.forEach(node.members, function (member) { - if (member.name.kind !== 128 /* ComputedPropertyName */ && isNumericLiteralName(member.name.text)) { + if (member.name.kind !== 129 /* ComputedPropertyName */ && isNumericLiteralName(member.name.text)) { error(member.name, ts.Diagnostics.An_enum_member_cannot_have_a_numeric_name); } var initializer = member.initializer; @@ -20154,7 +22039,7 @@ var ts; return evalConstant(initializer); function evalConstant(e) { switch (e.kind) { - case 168 /* PrefixUnaryExpression */: + case 170 /* PrefixUnaryExpression */: var value = evalConstant(e.operand); if (value === undefined) { return undefined; @@ -20165,7 +22050,7 @@ var ts; case 47 /* TildeToken */: return ~value; } return undefined; - case 170 /* BinaryExpression */: + case 172 /* BinaryExpression */: var left = evalConstant(e.left); if (left === undefined) { return undefined; @@ -20190,11 +22075,11 @@ var ts; return undefined; case 7 /* NumericLiteral */: return +e.text; - case 162 /* ParenthesizedExpression */: + case 164 /* ParenthesizedExpression */: return evalConstant(e.expression); case 65 /* Identifier */: - case 157 /* ElementAccessExpression */: - case 156 /* PropertyAccessExpression */: + case 159 /* ElementAccessExpression */: + case 158 /* PropertyAccessExpression */: var member = initializer.parent; var currentType = getTypeOfSymbol(getSymbolOfNode(member.parent)); var enumType; @@ -20207,7 +22092,7 @@ var ts; } else { var expression; - if (e.kind === 157 /* ElementAccessExpression */) { + if (e.kind === 159 /* ElementAccessExpression */) { if (e.argumentExpression === undefined || e.argumentExpression.kind !== 8 /* StringLiteral */) { return undefined; @@ -20225,7 +22110,7 @@ var ts; if (current.kind === 65 /* Identifier */) { break; } - else if (current.kind === 156 /* PropertyAccessExpression */) { + else if (current.kind === 158 /* PropertyAccessExpression */) { current = current.expression; } else { @@ -20264,15 +22149,15 @@ var ts; return; } // Grammar checking - checkGrammarDeclarationNameInStrictMode(node) || checkGrammarDecorators(node) || checkGrammarModifiers(node) || checkGrammarEnumDeclaration(node); + checkGrammarDecorators(node) || checkGrammarModifiers(node) || checkGrammarEnumDeclaration(node); checkTypeNameIsReserved(node.name, ts.Diagnostics.Enum_name_cannot_be_0); checkCollisionWithCapturedThisVariable(node, node.name); checkCollisionWithRequireExportsInGeneratedCode(node, node.name); checkExportsOnMergedDeclarations(node); computeEnumMemberValues(node); var enumIsConst = ts.isConst(node); - if (compilerOptions.separateCompilation && enumIsConst && ts.isInAmbientContext(node)) { - error(node.name, ts.Diagnostics.Ambient_const_enums_are_not_allowed_when_the_separateCompilation_flag_is_provided); + 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, @@ -20294,7 +22179,7 @@ var ts; var seenEnumMissingInitialInitializer = false; ts.forEach(enumSymbol.declarations, function (declaration) { // return true if we hit a violation of the rule, false otherwise - if (declaration.kind !== 205 /* EnumDeclaration */) { + if (declaration.kind !== 207 /* EnumDeclaration */) { return false; } var enumDeclaration = declaration; @@ -20317,8 +22202,8 @@ var ts; var declarations = symbol.declarations; for (var _i = 0; _i < declarations.length; _i++) { var declaration = declarations[_i]; - if ((declaration.kind === 202 /* ClassDeclaration */ || - (declaration.kind === 201 /* FunctionDeclaration */ && ts.nodeIsPresent(declaration.body))) && + if ((declaration.kind === 204 /* ClassDeclaration */ || + (declaration.kind === 203 /* FunctionDeclaration */ && ts.nodeIsPresent(declaration.body))) && !ts.isInAmbientContext(declaration)) { return declaration; } @@ -20341,7 +22226,15 @@ var ts; function checkModuleDeclaration(node) { if (produceDiagnostics) { // Grammar checking - if (!checkGrammarDeclarationNameInStrictMode(node) && !checkGrammarDecorators(node) && !checkGrammarModifiers(node)) { + var isAmbientExternalModule = node.name.kind === 8 /* StringLiteral */; + 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 (!ts.isInAmbientContext(node) && node.name.kind === 8 /* StringLiteral */) { grammarErrorOnNode(node.name, ts.Diagnostics.Only_ambient_modules_can_use_quoted_names); } @@ -20354,7 +22247,7 @@ var ts; if (symbol.flags & 512 /* ValueModule */ && symbol.declarations.length > 1 && !ts.isInAmbientContext(node) - && ts.isInstantiatedModule(node, compilerOptions.preserveConstEnums || compilerOptions.separateCompilation)) { + && ts.isInstantiatedModule(node, compilerOptions.preserveConstEnums || compilerOptions.isolatedModules)) { var firstNonAmbientClassOrFunc = getFirstNonAmbientClassOrFunctionDeclaration(symbol); if (firstNonAmbientClassOrFunc) { if (ts.getSourceFileOfNode(node) !== ts.getSourceFileOfNode(firstNonAmbientClassOrFunc)) { @@ -20366,14 +22259,14 @@ var ts; } // 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, 202 /* ClassDeclaration */); + var mergedClass = ts.getDeclarationOfKind(symbol, 204 /* ClassDeclaration */); if (mergedClass && inSameLexicalScope(node, mergedClass)) { getNodeLinks(node).flags |= 2048 /* LexicalModuleMergesWithClass */; } } // Checks for ambient external modules. - if (node.name.kind === 8 /* StringLiteral */) { + if (isAmbientExternalModule) { if (!isGlobalSourceFile(node.parent)) { error(node.name, ts.Diagnostics.Ambient_modules_cannot_be_nested_in_other_modules); } @@ -20386,10 +22279,10 @@ var ts; } function getFirstIdentifier(node) { while (true) { - if (node.kind === 127 /* QualifiedName */) { + if (node.kind === 128 /* QualifiedName */) { node = node.left; } - else if (node.kind === 156 /* PropertyAccessExpression */) { + else if (node.kind === 158 /* PropertyAccessExpression */) { node = node.expression; } else { @@ -20405,9 +22298,9 @@ var ts; error(moduleName, ts.Diagnostics.String_literal_expected); return false; } - var inAmbientExternalModule = node.parent.kind === 207 /* ModuleBlock */ && node.parent.parent.name.kind === 8 /* StringLiteral */; - if (node.parent.kind !== 228 /* SourceFile */ && !inAmbientExternalModule) { - error(moduleName, node.kind === 216 /* ExportDeclaration */ ? + var inAmbientExternalModule = node.parent.kind === 209 /* ModuleBlock */ && node.parent.parent.name.kind === 8 /* StringLiteral */; + if (node.parent.kind !== 230 /* SourceFile */ && !inAmbientExternalModule) { + error(moduleName, node.kind === 218 /* ExportDeclaration */ ? ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace : ts.Diagnostics.Import_declarations_in_a_namespace_cannot_reference_a_module); return false; @@ -20430,7 +22323,7 @@ var ts; (symbol.flags & 793056 /* Type */ ? 793056 /* Type */ : 0) | (symbol.flags & 1536 /* Namespace */ ? 1536 /* Namespace */ : 0); if (target.flags & excludedMeanings) { - var message = node.kind === 218 /* ExportSpecifier */ ? + var message = node.kind === 220 /* 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)); @@ -20443,7 +22336,11 @@ var ts; checkAliasSymbol(node); } function checkImportDeclaration(node) { - if (!checkGrammarImportDeclarationNameInStrictMode(node) && !checkGrammarDecorators(node) && !checkGrammarModifiers(node) && (node.flags & 499 /* Modifier */)) { + 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) && (node.flags & 499 /* Modifier */)) { grammarErrorOnFirstToken(node, ts.Diagnostics.An_import_declaration_cannot_have_modifiers); } if (checkExternalImportOrExportDeclaration(node)) { @@ -20453,7 +22350,7 @@ var ts; checkImportBinding(importClause); } if (importClause.namedBindings) { - if (importClause.namedBindings.kind === 212 /* NamespaceImport */) { + if (importClause.namedBindings.kind === 214 /* NamespaceImport */) { checkImportBinding(importClause.namedBindings); } else { @@ -20464,7 +22361,11 @@ var ts; } } function checkImportEqualsDeclaration(node) { - checkGrammarDeclarationNameInStrictMode(node) || checkGrammarDecorators(node) || checkGrammarModifiers(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 (node.flags & 1 /* Export */) { @@ -20494,6 +22395,10 @@ var ts; } } 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) && (node.flags & 499 /* Modifier */)) { grammarErrorOnFirstToken(node, ts.Diagnostics.An_export_declaration_cannot_have_modifiers); } @@ -20502,8 +22407,8 @@ var ts; // export { x, y } // export { x, y } from "foo" ts.forEach(node.exportClause.elements, checkExportSpecifier); - var inAmbientExternalModule = node.parent.kind === 207 /* ModuleBlock */ && node.parent.parent.name.kind === 8 /* StringLiteral */; - if (node.parent.kind !== 228 /* SourceFile */ && !inAmbientExternalModule) { + var inAmbientExternalModule = node.parent.kind === 209 /* ModuleBlock */ && node.parent.parent.name.kind === 8 /* StringLiteral */; + if (node.parent.kind !== 230 /* SourceFile */ && !inAmbientExternalModule) { error(node, ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace); } } @@ -20516,6 +22421,11 @@ var ts; } } } + function checkGrammarModuleElementContext(node, errorMessage) { + if (node.parent.kind !== 230 /* SourceFile */ && node.parent.kind !== 209 /* ModuleBlock */ && node.parent.kind !== 208 /* ModuleDeclaration */) { + return grammarErrorOnFirstToken(node, errorMessage); + } + } function checkExportSpecifier(node) { checkAliasSymbol(node); if (!node.parent.parent.moduleSpecifier) { @@ -20523,8 +22433,12 @@ var ts; } } function checkExportAssignment(node) { - var container = node.parent.kind === 228 /* SourceFile */ ? node.parent : node.parent.parent; - if (container.kind === 206 /* ModuleDeclaration */ && container.name.kind === 65 /* Identifier */) { + 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 === 230 /* SourceFile */ ? node.parent : node.parent.parent; + if (container.kind === 208 /* ModuleDeclaration */ && container.name.kind === 65 /* Identifier */) { error(node, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_namespace); return; } @@ -20551,10 +22465,10 @@ var ts; } } function getModuleStatements(node) { - if (node.kind === 228 /* SourceFile */) { + if (node.kind === 230 /* SourceFile */) { return node.statements; } - if (node.kind === 206 /* ModuleDeclaration */ && node.body.kind === 207 /* ModuleBlock */) { + if (node.kind === 208 /* ModuleDeclaration */ && node.body.kind === 209 /* ModuleBlock */) { return node.body.statements; } return emptyArray; @@ -20579,111 +22493,118 @@ var ts; links.exportsChecked = true; } } + function checkTypePredicate(node) { + if (!isInLegalTypePredicatePosition(node)) { + error(node, ts.Diagnostics.A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods); + } + } function checkSourceElement(node) { if (!node) return; switch (node.kind) { - case 129 /* TypeParameter */: + case 130 /* TypeParameter */: return checkTypeParameter(node); - case 130 /* Parameter */: + case 131 /* Parameter */: return checkParameter(node); - case 133 /* PropertyDeclaration */: - case 132 /* PropertySignature */: + case 134 /* PropertyDeclaration */: + case 133 /* PropertySignature */: return checkPropertyDeclaration(node); - case 143 /* FunctionType */: - case 144 /* ConstructorType */: - case 139 /* CallSignature */: - case 140 /* ConstructSignature */: + case 145 /* FunctionType */: + case 146 /* ConstructorType */: + case 140 /* CallSignature */: + case 141 /* ConstructSignature */: return checkSignatureDeclaration(node); - case 141 /* IndexSignature */: + case 142 /* IndexSignature */: return checkSignatureDeclaration(node); - case 135 /* MethodDeclaration */: - case 134 /* MethodSignature */: + case 136 /* MethodDeclaration */: + case 135 /* MethodSignature */: return checkMethodDeclaration(node); - case 136 /* Constructor */: + case 137 /* Constructor */: return checkConstructorDeclaration(node); - case 137 /* GetAccessor */: - case 138 /* SetAccessor */: + case 138 /* GetAccessor */: + case 139 /* SetAccessor */: return checkAccessorDeclaration(node); - case 142 /* TypeReference */: + case 144 /* TypeReference */: return checkTypeReferenceNode(node); - case 145 /* TypeQuery */: + case 143 /* TypePredicate */: + return checkTypePredicate(node); + case 147 /* TypeQuery */: return checkTypeQuery(node); - case 146 /* TypeLiteral */: + case 148 /* TypeLiteral */: return checkTypeLiteral(node); - case 147 /* ArrayType */: + case 149 /* ArrayType */: return checkArrayType(node); - case 148 /* TupleType */: + case 150 /* TupleType */: return checkTupleType(node); - case 149 /* UnionType */: + case 151 /* UnionType */: return checkUnionType(node); - case 150 /* ParenthesizedType */: + case 152 /* ParenthesizedType */: return checkSourceElement(node.type); - case 201 /* FunctionDeclaration */: + case 203 /* FunctionDeclaration */: return checkFunctionDeclaration(node); - case 180 /* Block */: - case 207 /* ModuleBlock */: + case 182 /* Block */: + case 209 /* ModuleBlock */: return checkBlock(node); - case 181 /* VariableStatement */: + case 183 /* VariableStatement */: return checkVariableStatement(node); - case 183 /* ExpressionStatement */: + case 185 /* ExpressionStatement */: return checkExpressionStatement(node); - case 184 /* IfStatement */: + case 186 /* IfStatement */: return checkIfStatement(node); - case 185 /* DoStatement */: + case 187 /* DoStatement */: return checkDoStatement(node); - case 186 /* WhileStatement */: + case 188 /* WhileStatement */: return checkWhileStatement(node); - case 187 /* ForStatement */: + case 189 /* ForStatement */: return checkForStatement(node); - case 188 /* ForInStatement */: + case 190 /* ForInStatement */: return checkForInStatement(node); - case 189 /* ForOfStatement */: + case 191 /* ForOfStatement */: return checkForOfStatement(node); - case 190 /* ContinueStatement */: - case 191 /* BreakStatement */: + case 192 /* ContinueStatement */: + case 193 /* BreakStatement */: return checkBreakOrContinueStatement(node); - case 192 /* ReturnStatement */: + case 194 /* ReturnStatement */: return checkReturnStatement(node); - case 193 /* WithStatement */: + case 195 /* WithStatement */: return checkWithStatement(node); - case 194 /* SwitchStatement */: + case 196 /* SwitchStatement */: return checkSwitchStatement(node); - case 195 /* LabeledStatement */: + case 197 /* LabeledStatement */: return checkLabeledStatement(node); - case 196 /* ThrowStatement */: + case 198 /* ThrowStatement */: return checkThrowStatement(node); - case 197 /* TryStatement */: + case 199 /* TryStatement */: return checkTryStatement(node); - case 199 /* VariableDeclaration */: + case 201 /* VariableDeclaration */: return checkVariableDeclaration(node); - case 153 /* BindingElement */: + case 155 /* BindingElement */: return checkBindingElement(node); - case 202 /* ClassDeclaration */: + case 204 /* ClassDeclaration */: return checkClassDeclaration(node); - case 203 /* InterfaceDeclaration */: + case 205 /* InterfaceDeclaration */: return checkInterfaceDeclaration(node); - case 204 /* TypeAliasDeclaration */: + case 206 /* TypeAliasDeclaration */: return checkTypeAliasDeclaration(node); - case 205 /* EnumDeclaration */: + case 207 /* EnumDeclaration */: return checkEnumDeclaration(node); - case 206 /* ModuleDeclaration */: + case 208 /* ModuleDeclaration */: return checkModuleDeclaration(node); - case 210 /* ImportDeclaration */: + case 212 /* ImportDeclaration */: return checkImportDeclaration(node); - case 209 /* ImportEqualsDeclaration */: + case 211 /* ImportEqualsDeclaration */: return checkImportEqualsDeclaration(node); - case 216 /* ExportDeclaration */: + case 218 /* ExportDeclaration */: return checkExportDeclaration(node); - case 215 /* ExportAssignment */: + case 217 /* ExportAssignment */: return checkExportAssignment(node); - case 182 /* EmptyStatement */: + case 184 /* EmptyStatement */: checkGrammarStatementInAmbientContext(node); return; - case 198 /* DebuggerStatement */: + case 200 /* DebuggerStatement */: checkGrammarStatementInAmbientContext(node); return; - case 219 /* MissingDeclaration */: + case 221 /* MissingDeclaration */: return checkMissingDeclaration(node); } } @@ -20698,81 +22619,83 @@ var ts; // Delaying the type check of the body ensures foo has been assigned a type. function checkFunctionExpressionBodies(node) { switch (node.kind) { - case 163 /* FunctionExpression */: - case 164 /* ArrowFunction */: + case 165 /* FunctionExpression */: + case 166 /* ArrowFunction */: ts.forEach(node.parameters, checkFunctionExpressionBodies); checkFunctionExpressionOrObjectLiteralMethodBody(node); break; - case 135 /* MethodDeclaration */: - case 134 /* MethodSignature */: + case 136 /* MethodDeclaration */: + case 135 /* MethodSignature */: + ts.forEach(node.decorators, checkFunctionExpressionBodies); ts.forEach(node.parameters, checkFunctionExpressionBodies); if (ts.isObjectLiteralMethod(node)) { checkFunctionExpressionOrObjectLiteralMethodBody(node); } break; - case 136 /* Constructor */: - case 137 /* GetAccessor */: - case 138 /* SetAccessor */: - case 201 /* FunctionDeclaration */: + case 137 /* Constructor */: + case 138 /* GetAccessor */: + case 139 /* SetAccessor */: + case 203 /* FunctionDeclaration */: ts.forEach(node.parameters, checkFunctionExpressionBodies); break; - case 193 /* WithStatement */: + case 195 /* WithStatement */: checkFunctionExpressionBodies(node.expression); break; - case 130 /* Parameter */: - case 133 /* PropertyDeclaration */: - case 132 /* PropertySignature */: - case 151 /* ObjectBindingPattern */: - case 152 /* ArrayBindingPattern */: - case 153 /* BindingElement */: - case 154 /* ArrayLiteralExpression */: - case 155 /* ObjectLiteralExpression */: - case 225 /* PropertyAssignment */: - case 156 /* PropertyAccessExpression */: - case 157 /* ElementAccessExpression */: - case 158 /* CallExpression */: - case 159 /* NewExpression */: - case 160 /* TaggedTemplateExpression */: - case 172 /* TemplateExpression */: - case 178 /* TemplateSpan */: - case 161 /* TypeAssertionExpression */: - case 162 /* ParenthesizedExpression */: - case 166 /* TypeOfExpression */: - case 167 /* VoidExpression */: - case 165 /* DeleteExpression */: - case 168 /* PrefixUnaryExpression */: - case 169 /* PostfixUnaryExpression */: - case 170 /* BinaryExpression */: - case 171 /* ConditionalExpression */: - case 174 /* SpreadElementExpression */: - case 180 /* Block */: - case 207 /* ModuleBlock */: - case 181 /* VariableStatement */: - case 183 /* ExpressionStatement */: - case 184 /* IfStatement */: - case 185 /* DoStatement */: - case 186 /* WhileStatement */: - case 187 /* ForStatement */: - case 188 /* ForInStatement */: - case 189 /* ForOfStatement */: - case 190 /* ContinueStatement */: - case 191 /* BreakStatement */: - case 192 /* ReturnStatement */: - case 194 /* SwitchStatement */: - case 208 /* CaseBlock */: - case 221 /* CaseClause */: - case 222 /* DefaultClause */: - case 195 /* LabeledStatement */: - case 196 /* ThrowStatement */: - case 197 /* TryStatement */: - case 224 /* CatchClause */: - case 199 /* VariableDeclaration */: - case 200 /* VariableDeclarationList */: - case 202 /* ClassDeclaration */: - case 205 /* EnumDeclaration */: - case 227 /* EnumMember */: - case 215 /* ExportAssignment */: - case 228 /* SourceFile */: + case 132 /* Decorator */: + case 131 /* Parameter */: + case 134 /* PropertyDeclaration */: + case 133 /* PropertySignature */: + case 153 /* ObjectBindingPattern */: + case 154 /* ArrayBindingPattern */: + case 155 /* BindingElement */: + case 156 /* ArrayLiteralExpression */: + case 157 /* ObjectLiteralExpression */: + case 227 /* PropertyAssignment */: + case 158 /* PropertyAccessExpression */: + case 159 /* ElementAccessExpression */: + case 160 /* CallExpression */: + case 161 /* NewExpression */: + case 162 /* TaggedTemplateExpression */: + case 174 /* TemplateExpression */: + case 180 /* TemplateSpan */: + case 163 /* TypeAssertionExpression */: + case 164 /* ParenthesizedExpression */: + case 168 /* TypeOfExpression */: + case 169 /* VoidExpression */: + case 167 /* DeleteExpression */: + case 170 /* PrefixUnaryExpression */: + case 171 /* PostfixUnaryExpression */: + case 172 /* BinaryExpression */: + case 173 /* ConditionalExpression */: + case 176 /* SpreadElementExpression */: + case 182 /* Block */: + case 209 /* ModuleBlock */: + case 183 /* VariableStatement */: + case 185 /* ExpressionStatement */: + case 186 /* IfStatement */: + case 187 /* DoStatement */: + case 188 /* WhileStatement */: + case 189 /* ForStatement */: + case 190 /* ForInStatement */: + case 191 /* ForOfStatement */: + case 192 /* ContinueStatement */: + case 193 /* BreakStatement */: + case 194 /* ReturnStatement */: + case 196 /* SwitchStatement */: + case 210 /* CaseBlock */: + case 223 /* CaseClause */: + case 224 /* DefaultClause */: + case 197 /* LabeledStatement */: + case 198 /* ThrowStatement */: + case 199 /* TryStatement */: + case 226 /* CatchClause */: + case 201 /* VariableDeclaration */: + case 202 /* VariableDeclarationList */: + case 204 /* ClassDeclaration */: + case 207 /* EnumDeclaration */: + case 229 /* EnumMember */: + case 217 /* ExportAssignment */: + case 230 /* SourceFile */: ts.forEachChild(node, checkFunctionExpressionBodies); break; } @@ -20786,6 +22709,11 @@ var ts; function checkSourceFileWorker(node) { var links = getNodeLinks(node); if (!(links.flags & 1 /* TypeChecked */)) { + // Check whether the file has declared it is the default lib, + // and whether the user has specifically chosen to avoid checking it. + if (node.isDefaultLib && compilerOptions.skipDefaultLibCheck) { + return; + } // Grammar checking checkGrammarSourceFile(node); emitExtends = false; @@ -20835,7 +22763,7 @@ var ts; function isInsideWithStatementBody(node) { if (node) { while (node.parent) { - if (node.parent.kind === 193 /* WithStatement */ && node.parent.statement === node) { + if (node.parent.kind === 195 /* WithStatement */ && node.parent.statement === node) { return true; } node = node.parent; @@ -20858,23 +22786,23 @@ var ts; copySymbols(location.locals, meaning); } switch (location.kind) { - case 228 /* SourceFile */: + case 230 /* SourceFile */: if (!ts.isExternalModule(location)) { break; } - case 206 /* ModuleDeclaration */: + case 208 /* ModuleDeclaration */: copySymbols(getSymbolOfNode(location).exports, meaning & 8914931 /* ModuleMember */); break; - case 205 /* EnumDeclaration */: + case 207 /* EnumDeclaration */: copySymbols(getSymbolOfNode(location).exports, meaning & 8 /* EnumMember */); break; - case 202 /* ClassDeclaration */: - case 203 /* InterfaceDeclaration */: + case 204 /* ClassDeclaration */: + case 205 /* InterfaceDeclaration */: if (!(memberFlags & 128 /* Static */)) { copySymbols(getSymbolOfNode(location).members, meaning & 793056 /* Type */); } break; - case 163 /* FunctionExpression */: + case 165 /* FunctionExpression */: if (location.name) { copySymbol(location.symbol, meaning); } @@ -20912,22 +22840,22 @@ var ts; copySymbols(location.locals, meaning); } switch (location.kind) { - case 228 /* SourceFile */: + case 230 /* SourceFile */: if (!ts.isExternalModule(location)) break; - case 206 /* ModuleDeclaration */: + case 208 /* ModuleDeclaration */: copySymbols(getSymbolOfNode(location).exports, meaning & 8914931 /* ModuleMember */); break; - case 205 /* EnumDeclaration */: + case 207 /* EnumDeclaration */: copySymbols(getSymbolOfNode(location).exports, meaning & 8 /* EnumMember */); break; - case 202 /* ClassDeclaration */: - case 203 /* InterfaceDeclaration */: + case 204 /* ClassDeclaration */: + case 205 /* InterfaceDeclaration */: if (!(memberFlags & 128 /* Static */)) { copySymbols(getSymbolOfNode(location).members, meaning & 793056 /* Type */); } break; - case 163 /* FunctionExpression */: + case 165 /* FunctionExpression */: if (location.name) { copySymbol(location.symbol, meaning); } @@ -20940,124 +22868,43 @@ var ts; return symbolsToArray(symbols); } function isTypeDeclarationName(name) { - return name.kind == 65 /* Identifier */ && + return name.kind === 65 /* Identifier */ && isTypeDeclaration(name.parent) && name.parent.name === name; } function isTypeDeclaration(node) { switch (node.kind) { - case 129 /* TypeParameter */: - case 202 /* ClassDeclaration */: - case 203 /* InterfaceDeclaration */: - case 204 /* TypeAliasDeclaration */: - case 205 /* EnumDeclaration */: + case 130 /* TypeParameter */: + case 204 /* ClassDeclaration */: + case 205 /* InterfaceDeclaration */: + case 206 /* TypeAliasDeclaration */: + case 207 /* 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 === 127 /* QualifiedName */) { + while (node.parent && node.parent.kind === 128 /* QualifiedName */) { node = node.parent; } - return node.parent && node.parent.kind === 142 /* TypeReference */; + return node.parent && node.parent.kind === 144 /* TypeReference */; } function isHeritageClauseElementIdentifier(entityName) { var node = entityName; - while (node.parent && node.parent.kind === 156 /* PropertyAccessExpression */) { + while (node.parent && node.parent.kind === 158 /* PropertyAccessExpression */) { node = node.parent; } - return node.parent && node.parent.kind === 177 /* ExpressionWithTypeArguments */; - } - function isTypeNode(node) { - if (142 /* FirstTypeNode */ <= node.kind && node.kind <= 150 /* LastTypeNode */) { - return true; - } - switch (node.kind) { - case 112 /* AnyKeyword */: - case 120 /* NumberKeyword */: - case 122 /* StringKeyword */: - case 113 /* BooleanKeyword */: - case 123 /* SymbolKeyword */: - return true; - case 99 /* VoidKeyword */: - return node.parent.kind !== 167 /* VoidExpression */; - case 8 /* StringLiteral */: - // Specialized signatures can have string literals as their parameters' type names - return node.parent.kind === 130 /* Parameter */; - case 177 /* ExpressionWithTypeArguments */: - return true; - // Identifiers and qualified names may be type nodes, depending on their context. Climb - // above them to find the lowest container - case 65 /* Identifier */: - // If the identifier is the RHS of a qualified name, then it's a type iff its parent is. - if (node.parent.kind === 127 /* QualifiedName */ && node.parent.right === node) { - node = node.parent; - } - else if (node.parent.kind === 156 /* PropertyAccessExpression */ && node.parent.name === node) { - node = node.parent; - } - // fall through - case 127 /* QualifiedName */: - case 156 /* PropertyAccessExpression */: - // At this point, node is either a qualified name or an identifier - ts.Debug.assert(node.kind === 65 /* Identifier */ || node.kind === 127 /* QualifiedName */ || node.kind === 156 /* PropertyAccessExpression */, "'node' was expected to be a qualified name, identifier or property access in 'isTypeNode'."); - var parent_5 = node.parent; - if (parent_5.kind === 145 /* TypeQuery */) { - return false; - } - // Do not recursively call isTypeNode on the parent. In the example: - // - // let a: A.B.C; - // - // Calling isTypeNode would consider the qualified name A.B a type node. Only C or - // A.B.C is a type node. - if (142 /* FirstTypeNode */ <= parent_5.kind && parent_5.kind <= 150 /* LastTypeNode */) { - return true; - } - switch (parent_5.kind) { - case 177 /* ExpressionWithTypeArguments */: - return true; - case 129 /* TypeParameter */: - return node === parent_5.constraint; - case 133 /* PropertyDeclaration */: - case 132 /* PropertySignature */: - case 130 /* Parameter */: - case 199 /* VariableDeclaration */: - return node === parent_5.type; - case 201 /* FunctionDeclaration */: - case 163 /* FunctionExpression */: - case 164 /* ArrowFunction */: - case 136 /* Constructor */: - case 135 /* MethodDeclaration */: - case 134 /* MethodSignature */: - case 137 /* GetAccessor */: - case 138 /* SetAccessor */: - return node === parent_5.type; - case 139 /* CallSignature */: - case 140 /* ConstructSignature */: - case 141 /* IndexSignature */: - return node === parent_5.type; - case 161 /* TypeAssertionExpression */: - return node === parent_5.type; - case 158 /* CallExpression */: - case 159 /* NewExpression */: - return parent_5.typeArguments && ts.indexOf(parent_5.typeArguments, node) >= 0; - case 160 /* TaggedTemplateExpression */: - // TODO (drosen): TaggedTemplateExpressions may eventually support type arguments. - return false; - } - } - return false; + return node.parent && node.parent.kind === 179 /* ExpressionWithTypeArguments */; } function getLeftSideOfImportEqualsOrExportAssignment(nodeOnRightSide) { - while (nodeOnRightSide.parent.kind === 127 /* QualifiedName */) { + while (nodeOnRightSide.parent.kind === 128 /* QualifiedName */) { nodeOnRightSide = nodeOnRightSide.parent; } - if (nodeOnRightSide.parent.kind === 209 /* ImportEqualsDeclaration */) { + if (nodeOnRightSide.parent.kind === 211 /* ImportEqualsDeclaration */) { return nodeOnRightSide.parent.moduleReference === nodeOnRightSide && nodeOnRightSide.parent; } - if (nodeOnRightSide.parent.kind === 215 /* ExportAssignment */) { + if (nodeOnRightSide.parent.kind === 217 /* ExportAssignment */) { return nodeOnRightSide.parent.expression === nodeOnRightSide && nodeOnRightSide.parent; } return undefined; @@ -21069,11 +22916,11 @@ var ts; if (ts.isDeclarationName(entityName)) { return getSymbolOfNode(entityName.parent); } - if (entityName.parent.kind === 215 /* ExportAssignment */) { + if (entityName.parent.kind === 217 /* ExportAssignment */) { return resolveEntityName(entityName, /*all meanings*/ 107455 /* Value */ | 793056 /* Type */ | 1536 /* Namespace */ | 8388608 /* Alias */); } - if (entityName.kind !== 156 /* PropertyAccessExpression */) { + if (entityName.kind !== 158 /* PropertyAccessExpression */) { if (isInRightSideOfImportOrExportAssignment(entityName)) { // Since we already checked for ExportAssignment, this really could only be an Import return getSymbolOfPartOfRightHandSideOfImportEquals(entityName); @@ -21083,7 +22930,7 @@ var ts; entityName = entityName.parent; } if (isHeritageClauseElementIdentifier(entityName)) { - var meaning = entityName.parent.kind === 177 /* ExpressionWithTypeArguments */ ? 793056 /* Type */ : 1536 /* Namespace */; + var meaning = entityName.parent.kind === 179 /* ExpressionWithTypeArguments */ ? 793056 /* Type */ : 1536 /* Namespace */; meaning |= 8388608 /* Alias */; return resolveEntityName(entityName, meaning); } @@ -21098,14 +22945,14 @@ var ts; var meaning = 107455 /* Value */ | 8388608 /* Alias */; return resolveEntityName(entityName, meaning); } - else if (entityName.kind === 156 /* PropertyAccessExpression */) { + else if (entityName.kind === 158 /* PropertyAccessExpression */) { var symbol = getNodeLinks(entityName).resolvedSymbol; if (!symbol) { checkPropertyAccessExpression(entityName); } return getNodeLinks(entityName).resolvedSymbol; } - else if (entityName.kind === 127 /* QualifiedName */) { + else if (entityName.kind === 128 /* QualifiedName */) { var symbol = getNodeLinks(entityName).resolvedSymbol; if (!symbol) { checkQualifiedName(entityName); @@ -21114,7 +22961,7 @@ var ts; } } else if (isTypeReferenceIdentifier(entityName)) { - var meaning = entityName.parent.kind === 142 /* TypeReference */ ? 793056 /* Type */ : 1536 /* Namespace */; + var meaning = entityName.parent.kind === 144 /* TypeReference */ ? 793056 /* Type */ : 1536 /* Namespace */; // Include aliases in the meaning, this ensures that we do not follow aliases to where they point and instead // return the alias symbol. meaning |= 8388608 /* Alias */; @@ -21133,14 +22980,14 @@ var ts; return getSymbolOfNode(node.parent); } if (node.kind === 65 /* Identifier */ && isInRightSideOfImportOrExportAssignment(node)) { - return node.parent.kind === 215 /* ExportAssignment */ + return node.parent.kind === 217 /* ExportAssignment */ ? getSymbolOfEntityNameOrPropertyAccessExpression(node) : getSymbolOfPartOfRightHandSideOfImportEquals(node); } switch (node.kind) { case 65 /* Identifier */: - case 156 /* PropertyAccessExpression */: - case 127 /* QualifiedName */: + case 158 /* PropertyAccessExpression */: + case 128 /* QualifiedName */: return getSymbolOfEntityNameOrPropertyAccessExpression(node); case 93 /* ThisKeyword */: case 91 /* SuperKeyword */: @@ -21149,7 +22996,7 @@ var ts; case 114 /* ConstructorKeyword */: // constructor keyword for an overload, should take us to the definition if it exist var constructorDeclaration = node.parent; - if (constructorDeclaration && constructorDeclaration.kind === 136 /* Constructor */) { + if (constructorDeclaration && constructorDeclaration.kind === 137 /* Constructor */) { return constructorDeclaration.parent.symbol; } return undefined; @@ -21158,14 +23005,14 @@ var ts; var moduleName; if ((ts.isExternalModuleImportEqualsDeclaration(node.parent.parent) && ts.getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node) || - ((node.parent.kind === 210 /* ImportDeclaration */ || node.parent.kind === 216 /* ExportDeclaration */) && + ((node.parent.kind === 212 /* ImportDeclaration */ || node.parent.kind === 218 /* ExportDeclaration */) && node.parent.moduleSpecifier === node)) { return resolveExternalModuleName(node, node); } // Intentional fall-through case 7 /* NumericLiteral */: // index access - if (node.parent.kind == 157 /* ElementAccessExpression */ && node.parent.argumentExpression === node) { + if (node.parent.kind === 159 /* ElementAccessExpression */ && node.parent.argumentExpression === node) { var objectType = checkExpression(node.parent.expression); if (objectType === unknownType) return undefined; @@ -21182,7 +23029,7 @@ var ts; // 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 === 226 /* ShorthandPropertyAssignment */) { + if (location && location.kind === 228 /* ShorthandPropertyAssignment */) { return resolveEntityName(location.name, 107455 /* Value */); } return undefined; @@ -21192,12 +23039,17 @@ var ts; // We cannot answer semantic questions within a with block, do not proceed any further return unknownType; } - if (isTypeNode(node)) { + if (ts.isTypeNode(node)) { return getTypeFromTypeNode(node); } if (ts.isExpression(node)) { return getTypeOfExpression(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. + return getBaseTypes(getDeclaredTypeOfSymbol(getSymbolOfNode(node.parent.parent)))[0]; + } if (isTypeDeclaration(node)) { // In this case, we call getSymbolOfNode instead of getSymbolInfo because it is a declaration var symbol = getSymbolOfNode(node); @@ -21246,9 +23098,9 @@ var ts; function getRootSymbols(symbol) { if (symbol.flags & 268435456 /* UnionProperty */) { var symbols = []; - var name_10 = symbol.name; + var name_14 = symbol.name; ts.forEach(getSymbolLinks(symbol).unionType.types, function (t) { - symbols.push(getPropertyOfType(t, name_10)); + symbols.push(getPropertyOfType(t, name_14)); }); return symbols; } @@ -21261,93 +23113,92 @@ var ts; return [symbol]; } // Emitter support - function isExternalModuleSymbol(symbol) { - return symbol.flags & 512 /* ValueModule */ && symbol.declarations.length === 1 && symbol.declarations[0].kind === 228 /* SourceFile */; - } - function getAliasNameSubstitution(symbol, getGeneratedNameForNode) { - // If this is es6 or higher, just use the name of the export - // no need to qualify it. - if (languageVersion >= 2 /* ES6 */) { - return undefined; - } - var node = getDeclarationOfAliasSymbol(symbol); - if (node) { - if (node.kind === 211 /* ImportClause */) { - var defaultKeyword; - if (languageVersion === 0 /* ES3 */) { - defaultKeyword = "[\"default\"]"; - } - else { - defaultKeyword = ".default"; - } - return getGeneratedNameForNode(node.parent) + defaultKeyword; - } - if (node.kind === 214 /* ImportSpecifier */) { - var moduleName = getGeneratedNameForNode(node.parent.parent.parent); - var propertyName = node.propertyName || node.name; - return moduleName + "." + ts.unescapeIdentifier(propertyName.text); - } - } - } - function getExportNameSubstitution(symbol, location, getGeneratedNameForNode) { - if (isExternalModuleSymbol(symbol.parent)) { - // 1. If this is es6 or higher, just use the name of the export - // no need to qualify it. - // 2. export mechanism for System modules is different from CJS\AMD - // and it does not need qualifications for exports - if (languageVersion >= 2 /* ES6 */ || compilerOptions.module === 4 /* System */) { - return undefined; - } - return "exports." + ts.unescapeIdentifier(symbol.name); - } - var node = location; - var containerSymbol = getParentOfSymbol(symbol); - while (node) { - if ((node.kind === 206 /* ModuleDeclaration */ || node.kind === 205 /* EnumDeclaration */) && getSymbolOfNode(node) === containerSymbol) { - return getGeneratedNameForNode(node) + "." + ts.unescapeIdentifier(symbol.name); - } - node = node.parent; - } - } - function getExpressionNameSubstitution(node, getGeneratedNameForNode) { - var symbol = getNodeLinks(node).resolvedSymbol || (ts.isDeclarationName(node) ? getSymbolOfNode(node.parent) : undefined); + // 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) { + var symbol = getReferencedValueSymbol(node); if (symbol) { - // Whan an identifier resolves to a parented symbol, it references an exported entity from - // another declaration of the same internal module. - if (symbol.parent) { - return getExportNameSubstitution(symbol, node.parent, getGeneratedNameForNode); + 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 (exportSymbol.flags & 944 /* ExportHasLocal */) { + return undefined; + } + symbol = exportSymbol; } - // 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 = getExportSymbolOfValueSymbolIfExported(symbol); - if (symbol !== exportSymbol && !(exportSymbol.flags & 944 /* ExportHasLocal */)) { - return getExportNameSubstitution(exportSymbol, node.parent, getGeneratedNameForNode); - } - // Named imports from ES6 import declarations are rewritten - if (symbol.flags & 8388608 /* Alias */) { - return getAliasNameSubstitution(symbol, getGeneratedNameForNode); + var parentSymbol = getParentOfSymbol(symbol); + if (parentSymbol) { + if (parentSymbol.flags & 512 /* ValueModule */ && parentSymbol.valueDeclaration.kind === 230 /* SourceFile */) { + return parentSymbol.valueDeclaration; + } + for (var n = node.parent; n; n = n.parent) { + if ((n.kind === 208 /* ModuleDeclaration */ || n.kind === 207 /* EnumDeclaration */) && getSymbolOfNode(n) === parentSymbol) { + return n; + } + } } } } + // 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) { + var symbol = getReferencedValueSymbol(node); + return symbol && symbol.flags & 8388608 /* Alias */ ? getDeclarationOfAliasSymbol(symbol) : undefined; + } + function isStatementWithLocals(node) { + switch (node.kind) { + case 182 /* Block */: + case 210 /* CaseBlock */: + case 189 /* ForStatement */: + case 190 /* ForInStatement */: + case 191 /* ForOfStatement */: + return true; + } + return false; + } + function isNestedRedeclarationSymbol(symbol) { + if (symbol.flags & 418 /* BlockScoped */) { + var links = getSymbolLinks(symbol); + if (links.isNestedRedeclaration === undefined) { + var container = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration); + links.isNestedRedeclaration = isStatementWithLocals(container) && + !!resolveName(container.parent, symbol.name, 107455 /* Value */, undefined, undefined); + } + return links.isNestedRedeclaration; + } + return false; + } + // When resolved as an expression identifier, if the given node references a nested block scoped entity with + // a name that hides an existing name, return the declaration of that entity. Otherwise, return undefined. + function getReferencedNestedRedeclaration(node) { + var symbol = getReferencedValueSymbol(node); + return symbol && isNestedRedeclarationSymbol(symbol) ? symbol.valueDeclaration : undefined; + } + // Return true if the given node is a declaration of a nested block scoped entity with a name that hides an + // existing name. + function isNestedRedeclaration(node) { + return isNestedRedeclarationSymbol(getSymbolOfNode(node)); + } function isValueAliasDeclaration(node) { switch (node.kind) { - case 209 /* ImportEqualsDeclaration */: - case 211 /* ImportClause */: - case 212 /* NamespaceImport */: - case 214 /* ImportSpecifier */: - case 218 /* ExportSpecifier */: + case 211 /* ImportEqualsDeclaration */: + case 213 /* ImportClause */: + case 214 /* NamespaceImport */: + case 216 /* ImportSpecifier */: + case 220 /* ExportSpecifier */: return isAliasResolvedToValue(getSymbolOfNode(node)); - case 216 /* ExportDeclaration */: + case 218 /* ExportDeclaration */: var exportClause = node.exportClause; return exportClause && ts.forEach(exportClause.elements, isValueAliasDeclaration); - case 215 /* ExportAssignment */: + case 217 /* ExportAssignment */: return node.expression && node.expression.kind === 65 /* Identifier */ ? isAliasResolvedToValue(getSymbolOfNode(node)) : true; } return false; } function isTopLevelValueImportEqualsWithEntityName(node) { - if (node.parent.kind !== 228 /* SourceFile */ || !ts.isInternalModuleImportEqualsDeclaration(node)) { + if (node.parent.kind !== 230 /* SourceFile */ || !ts.isInternalModuleImportEqualsDeclaration(node)) { // parent is not source file or it is not reference to internal module return false; } @@ -21356,7 +23207,7 @@ var ts; } function isAliasResolvedToValue(symbol) { var target = resolveAlias(symbol); - if (target === unknownSymbol && compilerOptions.separateCompilation) { + if (target === unknownSymbol && compilerOptions.isolatedModules) { return true; } // const enums and modules that contain only const enums are not considered values from the emit perespective @@ -21405,7 +23256,7 @@ var ts; return getNodeLinks(node).enumMemberValue; } function getConstantValue(node) { - if (node.kind === 227 /* EnumMember */) { + if (node.kind === 229 /* EnumMember */) { return getEnumMemberValue(node); } var symbol = getNodeLinks(node).resolvedSymbol; @@ -21418,10 +23269,13 @@ var ts; return undefined; } /** Serializes an EntityName (with substitutions) to an appropriate JS constructor value. Used by the __metadata decorator. */ - function serializeEntityName(node, getGeneratedNameForNode, fallbackPath) { + function serializeEntityName(node, fallbackPath) { if (node.kind === 65 /* Identifier */) { - var substitution = getExpressionNameSubstitution(node, getGeneratedNameForNode); - var text = substitution || node.text; + // TODO(ron.buckton): The getExpressionNameSubstitution function has been removed, but calling it + // here has no effect anyway as an identifier in a type name is not an expression. + // var substitution = getExpressionNameSubstitution(node, getGeneratedNameForNode); + // var text = substitution || (node).text; + var text = node.text; if (fallbackPath) { fallbackPath.push(text); } @@ -21430,15 +23284,15 @@ var ts; } } else { - var left = serializeEntityName(node.left, getGeneratedNameForNode, fallbackPath); - var right = serializeEntityName(node.right, getGeneratedNameForNode, fallbackPath); + var left = serializeEntityName(node.left, fallbackPath); + var right = serializeEntityName(node.right, fallbackPath); if (!fallbackPath) { return left + "." + right; } } } /** Serializes a TypeReferenceNode to an appropriate JS constructor value. Used by the __metadata decorator. */ - function serializeTypeReferenceNode(node, getGeneratedNameForNode) { + function serializeTypeReferenceNode(node) { // serialization of a TypeReferenceNode uses the following rules: // // * The serialized type of a TypeReference that is `void` is "void 0". @@ -21466,16 +23320,16 @@ var ts; else if (type.flags & 8192 /* Tuple */) { return "Array"; } - else if (type.flags & 1048576 /* ESSymbol */) { + else if (type.flags & 2097152 /* ESSymbol */) { return "Symbol"; } else if (type === unknownType) { var fallbackPath = []; - serializeEntityName(node.typeName, getGeneratedNameForNode, fallbackPath); + serializeEntityName(node.typeName, fallbackPath); return fallbackPath; } else if (type.symbol && type.symbol.valueDeclaration) { - return serializeEntityName(node.typeName, getGeneratedNameForNode); + return serializeEntityName(node.typeName); } else if (typeHasCallOrConstructSignatures(type)) { return "Function"; @@ -21483,7 +23337,7 @@ var ts; return "Object"; } /** Serializes a TypeNode to an appropriate JS constructor value. Used by the __metadata decorator. */ - function serializeTypeNode(node, getGeneratedNameForNode) { + function serializeTypeNode(node) { // serialization of a TypeNode uses the following rules: // // * The serialized type of `void` is "void 0" (undefined). @@ -21498,26 +23352,26 @@ var ts; switch (node.kind) { case 99 /* VoidKeyword */: return "void 0"; - case 150 /* ParenthesizedType */: - return serializeTypeNode(node.type, getGeneratedNameForNode); - case 143 /* FunctionType */: - case 144 /* ConstructorType */: + case 152 /* ParenthesizedType */: + return serializeTypeNode(node.type); + case 145 /* FunctionType */: + case 146 /* ConstructorType */: return "Function"; - case 147 /* ArrayType */: - case 148 /* TupleType */: + case 149 /* ArrayType */: + case 150 /* TupleType */: return "Array"; case 113 /* BooleanKeyword */: return "Boolean"; - case 122 /* StringKeyword */: + case 123 /* StringKeyword */: case 8 /* StringLiteral */: return "String"; - case 120 /* NumberKeyword */: + case 121 /* NumberKeyword */: return "Number"; - case 142 /* TypeReference */: - return serializeTypeReferenceNode(node, getGeneratedNameForNode); - case 145 /* TypeQuery */: - case 146 /* TypeLiteral */: - case 149 /* UnionType */: + case 144 /* TypeReference */: + return serializeTypeReferenceNode(node); + case 147 /* TypeQuery */: + case 148 /* TypeLiteral */: + case 151 /* UnionType */: case 112 /* AnyKeyword */: break; default: @@ -21528,7 +23382,7 @@ var ts; return "Object"; } /** Serializes the type of a declaration to an appropriate JS constructor value. Used by the __metadata decorator for a class member. */ - function serializeTypeOfNode(node, getGeneratedNameForNode) { + function serializeTypeOfNode(node) { // serialization of the type of a declaration uses the following rules: // // * The serialized type of a ClassDeclaration is "Function" @@ -21540,11 +23394,11 @@ var ts; // // For rules on serializing type annotations, see `serializeTypeNode`. switch (node.kind) { - case 202 /* ClassDeclaration */: return "Function"; - case 133 /* PropertyDeclaration */: return serializeTypeNode(node.type, getGeneratedNameForNode); - case 130 /* Parameter */: return serializeTypeNode(node.type, getGeneratedNameForNode); - case 137 /* GetAccessor */: return serializeTypeNode(node.type, getGeneratedNameForNode); - case 138 /* SetAccessor */: return serializeTypeNode(getSetAccessorTypeAnnotationNode(node), getGeneratedNameForNode); + case 204 /* ClassDeclaration */: return "Function"; + case 134 /* PropertyDeclaration */: return serializeTypeNode(node.type); + case 131 /* Parameter */: return serializeTypeNode(node.type); + case 138 /* GetAccessor */: return serializeTypeNode(node.type); + case 139 /* SetAccessor */: return serializeTypeNode(getSetAccessorTypeAnnotationNode(node)); } if (ts.isFunctionLike(node)) { return "Function"; @@ -21552,7 +23406,7 @@ var ts; return "void 0"; } /** Serializes the parameter types of a function or the constructor of a class. Used by the __metadata decorator for a method or set accessor. */ - function serializeParameterTypesOfNode(node, getGeneratedNameForNode) { + function serializeParameterTypesOfNode(node) { // serialization of parameter types uses the following rules: // // * If the declaration is a class, the parameters of the first constructor with a body are used. @@ -21561,7 +23415,7 @@ var ts; // For the rules on serializing the type of each parameter declaration, see `serializeTypeOfDeclaration`. if (node) { var valueDeclaration; - if (node.kind === 202 /* ClassDeclaration */) { + if (node.kind === 204 /* ClassDeclaration */) { valueDeclaration = ts.getFirstConstructorWithBody(node); } else if (ts.isFunctionLike(node) && ts.nodeIsPresent(node.body)) { @@ -21576,19 +23430,19 @@ var ts; for (var i = 0; i < parameterCount; i++) { if (parameters[i].dotDotDotToken) { var parameterType = parameters[i].type; - if (parameterType.kind === 147 /* ArrayType */) { + if (parameterType.kind === 149 /* ArrayType */) { parameterType = parameterType.elementType; } - else if (parameterType.kind === 142 /* TypeReference */ && parameterType.typeArguments && parameterType.typeArguments.length === 1) { + else if (parameterType.kind === 144 /* TypeReference */ && parameterType.typeArguments && parameterType.typeArguments.length === 1) { parameterType = parameterType.typeArguments[0]; } else { parameterType = undefined; } - result[i] = serializeTypeNode(parameterType, getGeneratedNameForNode); + result[i] = serializeTypeNode(parameterType); } else { - result[i] = serializeTypeOfNode(parameters[i], getGeneratedNameForNode); + result[i] = serializeTypeOfNode(parameters[i]); } } return result; @@ -21598,9 +23452,9 @@ var ts; return emptyArray; } /** Serializes the return type of function. Used by the __metadata decorator for a method. */ - function serializeReturnTypeOfNode(node, getGeneratedNameForNode) { + function serializeReturnTypeOfNode(node) { if (node && ts.isFunctionLike(node)) { - return serializeTypeNode(node.type, getGeneratedNameForNode); + return serializeTypeNode(node.type); } return "void 0"; } @@ -21623,25 +23477,25 @@ var ts; function hasGlobalName(name) { return ts.hasProperty(globals, name); } - function resolvesToSomeValue(location, name) { - ts.Debug.assert(!ts.nodeIsSynthesized(location), "resolvesToSomeValue called with a synthesized location"); - return !!resolveName(location, name, 107455 /* Value */, undefined, undefined); + function getReferencedValueSymbol(reference) { + return getNodeLinks(reference).resolvedSymbol || + resolveName(reference, reference.text, 107455 /* Value */ | 1048576 /* ExportValue */ | 8388608 /* Alias */, + /*nodeNotFoundMessage*/ undefined, undefined); } function getReferencedValueDeclaration(reference) { ts.Debug.assert(!ts.nodeIsSynthesized(reference)); - var symbol = getNodeLinks(reference).resolvedSymbol || - resolveName(reference, reference.text, 107455 /* Value */ | 8388608 /* Alias */, undefined, undefined); + var symbol = getReferencedValueSymbol(reference); return symbol && getExportSymbolOfValueSymbolIfExported(symbol).valueDeclaration; } function getBlockScopedVariableId(n) { ts.Debug.assert(!ts.nodeIsSynthesized(n)); - var isVariableDeclarationOrBindingElement = n.parent.kind === 153 /* BindingElement */ || (n.parent.kind === 199 /* VariableDeclaration */ && n.parent.name === n); + var isVariableDeclarationOrBindingElement = n.parent.kind === 155 /* BindingElement */ || (n.parent.kind === 201 /* VariableDeclaration */ && n.parent.name === n); var symbol = (isVariableDeclarationOrBindingElement ? getSymbolOfNode(n.parent) : undefined) || getNodeLinks(n).resolvedSymbol || resolveName(n, n.text, 107455 /* Value */ | 8388608 /* Alias */, undefined, undefined); var isLetOrConst = symbol && (symbol.flags & 2 /* BlockScopedVariable */) && - symbol.valueDeclaration.parent.kind !== 224 /* CatchClause */; + symbol.valueDeclaration.parent.kind !== 226 /* CatchClause */; if (isLetOrConst) { // side-effect of calling this method: // assign id to symbol if it was not yet set @@ -21663,7 +23517,10 @@ var ts; } function createResolver() { return { - getExpressionNameSubstitution: getExpressionNameSubstitution, + getReferencedExportContainer: getReferencedExportContainer, + getReferencedImportDeclaration: getReferencedImportDeclaration, + getReferencedNestedRedeclaration: getReferencedNestedRedeclaration, + isNestedRedeclaration: isNestedRedeclaration, isValueAliasDeclaration: isValueAliasDeclaration, hasGlobalName: hasGlobalName, isReferencedAliasDeclaration: isReferencedAliasDeclaration, @@ -21677,7 +23534,6 @@ var ts; isSymbolAccessible: isSymbolAccessible, isEntityNameVisible: isEntityNameVisible, getConstantValue: getConstantValue, - resolvesToSomeValue: resolvesToSomeValue, collectLinkedAliases: collectLinkedAliases, getBlockScopedVariableId: getBlockScopedVariableId, getReferencedValueDeclaration: getReferencedValueDeclaration, @@ -21703,8 +23559,7 @@ var ts; getSymbolLinks(unknownSymbol).type = unknownType; globals[undefinedSymbol.name] = undefinedSymbol; // Initialize special types - globalArraySymbol = getGlobalTypeSymbol("Array"); - globalArrayType = getTypeOfGlobalSymbol(globalArraySymbol, 1); + globalArrayType = getGlobalType("Array", 1); globalObjectType = getGlobalType("Object"); globalFunctionType = getGlobalType("Function"); globalStringType = getGlobalType("String"); @@ -21722,6 +23577,8 @@ var ts; globalESSymbolType = getGlobalType("Symbol"); globalESSymbolConstructorSymbol = getGlobalValueSymbol("Symbol"); globalIterableType = getGlobalType("Iterable", 1); + globalIteratorType = getGlobalType("Iterator", 1); + globalIterableIteratorType = getGlobalType("IterableIterator", 1); } else { globalTemplateStringsArrayType = unknownType; @@ -21730,141 +23587,13 @@ var ts; // a global Symbol already, particularly if it is a class. globalESSymbolType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); globalESSymbolConstructorSymbol = undefined; + globalIterableType = emptyGenericType; + globalIteratorType = emptyGenericType; + globalIterableIteratorType = emptyGenericType; } anyArrayType = createArrayType(anyType); } // GRAMMAR CHECKING - function isReservedWordInStrictMode(node) { - // Check that originalKeywordKind is less than LastFutureReservedWord to see if an Identifier is a strict-mode reserved word - return (node.parserContextFlags & 1 /* StrictMode */) && - (102 /* FirstFutureReservedWord */ <= node.originalKeywordKind && node.originalKeywordKind <= 110 /* LastFutureReservedWord */); - } - function reportStrictModeGrammarErrorInClassDeclaration(identifier, message, arg0, arg1, arg2) { - // We are checking if this name is inside class declaration or class expression (which are under class definitions inside ES6 spec.) - // if so, we would like to give more explicit invalid usage error. - if (ts.getAncestor(identifier, 202 /* ClassDeclaration */) || ts.getAncestor(identifier, 175 /* ClassExpression */)) { - return grammarErrorOnNode(identifier, message, arg0); - } - return false; - } - function checkGrammarImportDeclarationNameInStrictMode(node) { - // Check if the import declaration used strict-mode reserved word in its names bindings - if (node.importClause) { - var impotClause = node.importClause; - if (impotClause.namedBindings) { - var nameBindings = impotClause.namedBindings; - if (nameBindings.kind === 212 /* NamespaceImport */) { - var name_11 = nameBindings.name; - if (isReservedWordInStrictMode(name_11)) { - var nameText = ts.declarationNameToString(name_11); - return grammarErrorOnNode(name_11, ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode, nameText); - } - } - else if (nameBindings.kind === 213 /* NamedImports */) { - var reportError = false; - for (var _i = 0, _a = nameBindings.elements; _i < _a.length; _i++) { - var element = _a[_i]; - var name_12 = element.name; - if (isReservedWordInStrictMode(name_12)) { - var nameText = ts.declarationNameToString(name_12); - reportError = reportError || grammarErrorOnNode(name_12, ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode, nameText); - } - } - return reportError; - } - } - } - return false; - } - function checkGrammarDeclarationNameInStrictMode(node) { - var name = node.name; - if (name && name.kind === 65 /* Identifier */ && isReservedWordInStrictMode(name)) { - var nameText = ts.declarationNameToString(name); - switch (node.kind) { - case 130 /* Parameter */: - case 199 /* VariableDeclaration */: - case 201 /* FunctionDeclaration */: - case 129 /* TypeParameter */: - case 153 /* BindingElement */: - case 203 /* InterfaceDeclaration */: - case 204 /* TypeAliasDeclaration */: - case 205 /* EnumDeclaration */: - return checkGrammarIdentifierInStrictMode(name); - case 202 /* ClassDeclaration */: - // Report an error if the class declaration uses strict-mode reserved word. - return grammarErrorOnNode(name, ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_strict_mode, nameText); - case 206 /* ModuleDeclaration */: - // Report an error if the module declaration uses strict-mode reserved word. - // TODO(yuisu): fix this when having external module in strict mode - return grammarErrorOnNode(name, ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode, nameText); - case 209 /* ImportEqualsDeclaration */: - // TODO(yuisu): fix this when having external module in strict mode - return grammarErrorOnNode(name, ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode, nameText); - } - } - return false; - } - function checkGrammarTypeReferenceInStrictMode(typeName) { - // Check if the type reference is using strict mode keyword - // Example: - // class C { - // foo(x: public){} // Error. - // } - if (typeName.kind === 65 /* Identifier */) { - checkGrammarTypeNameInStrictMode(typeName); - } - else if (typeName.kind === 127 /* QualifiedName */) { - // Walk from right to left and report a possible error at each Identifier in QualifiedName - // Example: - // x1: public.private.package // error at public and private - checkGrammarTypeNameInStrictMode(typeName.right); - checkGrammarTypeReferenceInStrictMode(typeName.left); - } - } - // This function will report an error for every identifier in property access expression - // whether it violates strict mode reserved words. - // Example: - // public // error at public - // public.private.package // error at public - // B.private.B // no error - function checkGrammarExpressionWithTypeArgumentsInStrictMode(expression) { - // Example: - // class C extends public // error at public - if (expression && expression.kind === 65 /* Identifier */) { - return checkGrammarIdentifierInStrictMode(expression); - } - else if (expression && expression.kind === 156 /* PropertyAccessExpression */) { - // Walk from left to right in PropertyAccessExpression until we are at the left most expression - // in PropertyAccessExpression. According to grammar production of MemberExpression, - // the left component expression is a PrimaryExpression (i.e. Identifier) while the other - // component after dots can be IdentifierName. - checkGrammarExpressionWithTypeArgumentsInStrictMode(expression.expression); - } - } - // The function takes an identifier itself or an expression which has SyntaxKind.Identifier. - function checkGrammarIdentifierInStrictMode(node, nameText) { - if (node && node.kind === 65 /* Identifier */ && isReservedWordInStrictMode(node)) { - if (!nameText) { - nameText = ts.declarationNameToString(node); - } - // TODO (yuisu): Fix when module is a strict mode - var errorReport = reportStrictModeGrammarErrorInClassDeclaration(node, ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_strict_mode, nameText) || - grammarErrorOnNode(node, ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode, nameText); - return errorReport; - } - return false; - } - // The function takes an identifier when uses as a typeName in TypeReferenceNode - function checkGrammarTypeNameInStrictMode(node) { - if (node && node.kind === 65 /* Identifier */ && isReservedWordInStrictMode(node)) { - var nameText = ts.declarationNameToString(node); - // TODO (yuisu): Fix when module is a strict mode - var errorReport = reportStrictModeGrammarErrorInClassDeclaration(node, ts.Diagnostics.Type_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_strict_mode, nameText) || - grammarErrorOnNode(node, ts.Diagnostics.Type_expected_0_is_a_reserved_word_in_strict_mode, nameText); - return errorReport; - } - return false; - } function checkGrammarDecorators(node) { if (!node.decorators) { return false; @@ -21875,7 +23604,7 @@ var ts; else if (languageVersion < 1 /* ES5 */) { return grammarErrorOnFirstToken(node, ts.Diagnostics.Decorators_are_only_available_when_targeting_ECMAScript_5_and_higher); } - else if (node.kind === 137 /* GetAccessor */ || node.kind === 138 /* SetAccessor */) { + else if (node.kind === 138 /* GetAccessor */ || node.kind === 139 /* 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); @@ -21885,26 +23614,35 @@ var ts; } function checkGrammarModifiers(node) { switch (node.kind) { - case 137 /* GetAccessor */: - case 138 /* SetAccessor */: - case 136 /* Constructor */: - case 133 /* PropertyDeclaration */: - case 132 /* PropertySignature */: - case 135 /* MethodDeclaration */: - case 134 /* MethodSignature */: - case 141 /* IndexSignature */: - case 202 /* ClassDeclaration */: - case 203 /* InterfaceDeclaration */: - case 206 /* ModuleDeclaration */: - case 205 /* EnumDeclaration */: - case 181 /* VariableStatement */: - case 201 /* FunctionDeclaration */: - case 204 /* TypeAliasDeclaration */: - case 210 /* ImportDeclaration */: - case 209 /* ImportEqualsDeclaration */: - case 216 /* ExportDeclaration */: - case 215 /* ExportAssignment */: - case 130 /* Parameter */: + case 138 /* GetAccessor */: + case 139 /* SetAccessor */: + case 137 /* Constructor */: + case 134 /* PropertyDeclaration */: + case 133 /* PropertySignature */: + case 136 /* MethodDeclaration */: + case 135 /* MethodSignature */: + case 142 /* IndexSignature */: + case 208 /* ModuleDeclaration */: + case 212 /* ImportDeclaration */: + case 211 /* ImportEqualsDeclaration */: + case 218 /* ExportDeclaration */: + case 217 /* ExportAssignment */: + case 131 /* Parameter */: + break; + case 204 /* ClassDeclaration */: + case 205 /* InterfaceDeclaration */: + case 183 /* VariableStatement */: + case 203 /* FunctionDeclaration */: + case 206 /* TypeAliasDeclaration */: + if (node.modifiers && node.parent.kind !== 209 /* ModuleBlock */ && node.parent.kind !== 230 /* SourceFile */) { + return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here); + } + break; + case 207 /* EnumDeclaration */: + if (node.modifiers && (node.modifiers.length > 1 || node.modifiers[0].kind !== 70 /* ConstKeyword */) && + node.parent.kind !== 209 /* ModuleBlock */ && node.parent.kind !== 230 /* SourceFile */) { + return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here); + } break; default: return false; @@ -21938,7 +23676,7 @@ var ts; else if (flags & 128 /* Static */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "static"); } - else if (node.parent.kind === 207 /* ModuleBlock */ || node.parent.kind === 228 /* SourceFile */) { + else if (node.parent.kind === 209 /* ModuleBlock */ || node.parent.kind === 230 /* SourceFile */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_element, text); } flags |= ts.modifierToFlag(modifier.kind); @@ -21947,10 +23685,10 @@ var ts; if (flags & 128 /* Static */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "static"); } - else if (node.parent.kind === 207 /* ModuleBlock */ || node.parent.kind === 228 /* SourceFile */) { + else if (node.parent.kind === 209 /* ModuleBlock */ || node.parent.kind === 230 /* SourceFile */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_element, "static"); } - else if (node.kind === 130 /* Parameter */) { + else if (node.kind === 131 /* Parameter */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "static"); } flags |= 128 /* Static */; @@ -21963,10 +23701,10 @@ var ts; else if (flags & 2 /* Ambient */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "export", "declare"); } - else if (node.parent.kind === 202 /* ClassDeclaration */) { + else if (node.parent.kind === 204 /* ClassDeclaration */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_class_element, "export"); } - else if (node.kind === 130 /* Parameter */) { + else if (node.kind === 131 /* Parameter */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "export"); } flags |= 1 /* Export */; @@ -21975,13 +23713,13 @@ var ts; if (flags & 2 /* Ambient */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "declare"); } - else if (node.parent.kind === 202 /* ClassDeclaration */) { + else if (node.parent.kind === 204 /* ClassDeclaration */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_class_element, "declare"); } - else if (node.kind === 130 /* Parameter */) { + else if (node.kind === 131 /* Parameter */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "declare"); } - else if (ts.isInAmbientContext(node.parent) && node.parent.kind === 207 /* ModuleBlock */) { + else if (ts.isInAmbientContext(node.parent) && node.parent.kind === 209 /* ModuleBlock */) { return grammarErrorOnNode(modifier, ts.Diagnostics.A_declare_modifier_cannot_be_used_in_an_already_ambient_context); } flags |= 2 /* Ambient */; @@ -21989,7 +23727,7 @@ var ts; break; } } - if (node.kind === 136 /* Constructor */) { + if (node.kind === 137 /* Constructor */) { if (flags & 128 /* Static */) { return grammarErrorOnNode(lastStatic, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "static"); } @@ -22000,13 +23738,10 @@ var ts; return grammarErrorOnNode(lastPrivate, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "private"); } } - else if ((node.kind === 210 /* ImportDeclaration */ || node.kind === 209 /* ImportEqualsDeclaration */) && flags & 2 /* Ambient */) { + else if ((node.kind === 212 /* ImportDeclaration */ || node.kind === 211 /* ImportEqualsDeclaration */) && flags & 2 /* Ambient */) { return grammarErrorOnNode(lastDeclare, ts.Diagnostics.A_declare_modifier_cannot_be_used_with_an_import_declaration, "declare"); } - else if (node.kind === 203 /* InterfaceDeclaration */ && flags & 2 /* Ambient */) { - return grammarErrorOnNode(lastDeclare, ts.Diagnostics.A_declare_modifier_cannot_be_used_with_an_interface_declaration, "declare"); - } - else if (node.kind === 130 /* Parameter */ && (flags & 112 /* AccessibilityModifier */) && ts.isBindingPattern(node.name)) { + else if (node.kind === 131 /* Parameter */ && (flags & 112 /* AccessibilityModifier */) && ts.isBindingPattern(node.name)) { return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_may_not_be_a_binding_pattern); } } @@ -22070,7 +23805,7 @@ var ts; checkGrammarParameterList(node.parameters) || checkGrammarArrowFunction(node, file); } function checkGrammarArrowFunction(node, file) { - if (node.kind === 164 /* ArrowFunction */) { + if (node.kind === 166 /* ArrowFunction */) { var arrowFunction = node; var startLine = ts.getLineAndCharacterOfPosition(file, arrowFunction.equalsGreaterThanToken.pos).line; var endLine = ts.getLineAndCharacterOfPosition(file, arrowFunction.equalsGreaterThanToken.end).line; @@ -22105,7 +23840,7 @@ var ts; if (!parameter.type) { return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_must_have_a_type_annotation); } - if (parameter.type.kind !== 122 /* StringKeyword */ && parameter.type.kind !== 120 /* NumberKeyword */) { + if (parameter.type.kind !== 123 /* StringKeyword */ && parameter.type.kind !== 121 /* NumberKeyword */) { return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_must_be_string_or_number); } if (!node.type) { @@ -22138,7 +23873,7 @@ var ts; var sourceFile = ts.getSourceFileOfNode(node); for (var _i = 0; _i < arguments.length; _i++) { var arg = arguments[_i]; - if (arg.kind === 176 /* OmittedExpression */) { + if (arg.kind === 178 /* OmittedExpression */) { return grammarErrorAtPos(sourceFile, arg.pos, 0, ts.Diagnostics.Argument_expression_expected); } } @@ -22212,23 +23947,30 @@ var ts; } function checkGrammarComputedPropertyName(node) { // If node is not a computedPropertyName, just skip the grammar checking - if (node.kind !== 128 /* ComputedPropertyName */) { + if (node.kind !== 129 /* ComputedPropertyName */) { return false; } var computedPropertyName = node; - if (computedPropertyName.expression.kind === 170 /* BinaryExpression */ && computedPropertyName.expression.operatorToken.kind === 23 /* CommaToken */) { + if (computedPropertyName.expression.kind === 172 /* BinaryExpression */ && computedPropertyName.expression.operatorToken.kind === 23 /* CommaToken */) { return grammarErrorOnNode(computedPropertyName.expression, ts.Diagnostics.A_comma_expression_is_not_allowed_in_a_computed_property_name); } } function checkGrammarForGenerator(node) { if (node.asteriskToken) { - return grammarErrorOnNode(node.asteriskToken, ts.Diagnostics.Generators_are_not_currently_supported); + ts.Debug.assert(node.kind === 203 /* FunctionDeclaration */ || + node.kind === 165 /* FunctionExpression */ || + node.kind === 136 /* 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); + } + if (languageVersion < 2 /* ES6 */) { + return grammarErrorOnNode(node.asteriskToken, ts.Diagnostics.Generators_are_only_available_when_targeting_ECMAScript_6_or_higher); + } } } - function checkGrammarFunctionName(name) { - // It is a SyntaxError if the identifier eval or arguments appears within a FormalParameterList of a strict mode FunctionDeclaration or FunctionExpression (13.1)) - return checkGrammarEvalOrArgumentsInStrictMode(name, name); - } function checkGrammarForInvalidQuestionMark(node, questionToken, message) { if (questionToken) { return grammarErrorOnNode(questionToken, message); @@ -22240,14 +23982,13 @@ var ts; var GetAccessor = 2; var SetAccesor = 4; var GetOrSetAccessor = GetAccessor | SetAccesor; - var inStrictMode = (node.parserContextFlags & 1 /* StrictMode */) !== 0; for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { var prop = _a[_i]; - var name_13 = prop.name; - if (prop.kind === 176 /* OmittedExpression */ || - name_13.kind === 128 /* ComputedPropertyName */) { + var name_15 = prop.name; + if (prop.kind === 178 /* OmittedExpression */ || + name_15.kind === 129 /* ComputedPropertyName */) { // If the name is not a ComputedPropertyName, the grammar checking will skip it - checkGrammarComputedPropertyName(name_13); + checkGrammarComputedPropertyName(name_15); continue; } // ECMA-262 11.1.5 Object Initialiser @@ -22259,46 +24000,44 @@ var ts; // 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 === 225 /* PropertyAssignment */ || prop.kind === 226 /* ShorthandPropertyAssignment */) { + if (prop.kind === 227 /* PropertyAssignment */ || prop.kind === 228 /* ShorthandPropertyAssignment */) { // Grammar checking for computedPropertName and shorthandPropertyAssignment checkGrammarForInvalidQuestionMark(prop, prop.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional); - if (name_13.kind === 7 /* NumericLiteral */) { - checkGrammarNumericLiteral(name_13); + if (name_15.kind === 7 /* NumericLiteral */) { + checkGrammarNumericLiteral(name_15); } currentKind = Property; } - else if (prop.kind === 135 /* MethodDeclaration */) { + else if (prop.kind === 136 /* MethodDeclaration */) { currentKind = Property; } - else if (prop.kind === 137 /* GetAccessor */) { + else if (prop.kind === 138 /* GetAccessor */) { currentKind = GetAccessor; } - else if (prop.kind === 138 /* SetAccessor */) { + else if (prop.kind === 139 /* SetAccessor */) { currentKind = SetAccesor; } else { ts.Debug.fail("Unexpected syntax kind:" + prop.kind); } - if (!ts.hasProperty(seen, name_13.text)) { - seen[name_13.text] = currentKind; + if (!ts.hasProperty(seen, name_15.text)) { + seen[name_15.text] = currentKind; } else { - var existingKind = seen[name_13.text]; + var existingKind = seen[name_15.text]; if (currentKind === Property && existingKind === Property) { - if (inStrictMode) { - grammarErrorOnNode(name_13, ts.Diagnostics.An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode); - } + continue; } else if ((currentKind & GetOrSetAccessor) && (existingKind & GetOrSetAccessor)) { if (existingKind !== GetOrSetAccessor && currentKind !== existingKind) { - seen[name_13.text] = currentKind | existingKind; + seen[name_15.text] = currentKind | existingKind; } else { - return grammarErrorOnNode(name_13, ts.Diagnostics.An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name); + return grammarErrorOnNode(name_15, ts.Diagnostics.An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name); } } else { - return grammarErrorOnNode(name_13, ts.Diagnostics.An_object_literal_cannot_have_property_and_accessor_with_the_same_name); + return grammarErrorOnNode(name_15, ts.Diagnostics.An_object_literal_cannot_have_property_and_accessor_with_the_same_name); } } } @@ -22307,24 +24046,24 @@ var ts; if (checkGrammarStatementInAmbientContext(forInOrOfStatement)) { return true; } - if (forInOrOfStatement.initializer.kind === 200 /* VariableDeclarationList */) { + if (forInOrOfStatement.initializer.kind === 202 /* VariableDeclarationList */) { var variableList = forInOrOfStatement.initializer; if (!checkGrammarVariableDeclarationList(variableList)) { if (variableList.declarations.length > 1) { - var diagnostic = forInOrOfStatement.kind === 188 /* ForInStatement */ + var diagnostic = forInOrOfStatement.kind === 190 /* 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 = variableList.declarations[0]; if (firstDeclaration.initializer) { - var diagnostic = forInOrOfStatement.kind === 188 /* ForInStatement */ + var diagnostic = forInOrOfStatement.kind === 190 /* 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 === 188 /* ForInStatement */ + var diagnostic = forInOrOfStatement.kind === 190 /* 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); @@ -22347,10 +24086,10 @@ var ts; else if (accessor.typeParameters) { return grammarErrorOnNode(accessor.name, ts.Diagnostics.An_accessor_cannot_have_type_parameters); } - else if (kind === 137 /* GetAccessor */ && accessor.parameters.length) { + else if (kind === 138 /* GetAccessor */ && accessor.parameters.length) { return grammarErrorOnNode(accessor.name, ts.Diagnostics.A_get_accessor_cannot_have_parameters); } - else if (kind === 138 /* SetAccessor */) { + else if (kind === 139 /* SetAccessor */) { if (accessor.type) { return grammarErrorOnNode(accessor.name, ts.Diagnostics.A_set_accessor_cannot_have_a_return_type_annotation); } @@ -22375,7 +24114,7 @@ var ts; } } function checkGrammarForNonSymbolComputedProperty(node, message) { - if (node.kind === 128 /* ComputedPropertyName */ && !ts.isWellKnownSymbolSyntactically(node.expression)) { + if (node.kind === 129 /* ComputedPropertyName */ && !ts.isWellKnownSymbolSyntactically(node.expression)) { return grammarErrorOnNode(node, message); } } @@ -22385,7 +24124,7 @@ var ts; checkGrammarForGenerator(node)) { return true; } - if (node.parent.kind === 155 /* ObjectLiteralExpression */) { + if (node.parent.kind === 157 /* ObjectLiteralExpression */) { if (checkGrammarForInvalidQuestionMark(node, node.questionToken, ts.Diagnostics.A_class_member_cannot_be_declared_optional)) { return true; } @@ -22393,7 +24132,7 @@ var ts; return grammarErrorAtPos(getSourceFile(node), node.end - 1, ";".length, ts.Diagnostics._0_expected, "{"); } } - if (node.parent.kind === 202 /* ClassDeclaration */) { + if (node.parent.kind === 204 /* ClassDeclaration */) { if (checkGrammarForInvalidQuestionMark(node, node.questionToken, ts.Diagnostics.A_class_member_cannot_be_declared_optional)) { return true; } @@ -22409,22 +24148,22 @@ var ts; 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 === 203 /* InterfaceDeclaration */) { + else if (node.parent.kind === 205 /* 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 === 146 /* TypeLiteral */) { + else if (node.parent.kind === 148 /* TypeLiteral */) { return checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_a_type_literal_must_directly_refer_to_a_built_in_symbol); } } function isIterationStatement(node, lookInLabeledStatements) { switch (node.kind) { - case 187 /* ForStatement */: - case 188 /* ForInStatement */: - case 189 /* ForOfStatement */: - case 185 /* DoStatement */: - case 186 /* WhileStatement */: + case 189 /* ForStatement */: + case 190 /* ForInStatement */: + case 191 /* ForOfStatement */: + case 187 /* DoStatement */: + case 188 /* WhileStatement */: return true; - case 195 /* LabeledStatement */: + case 197 /* LabeledStatement */: return lookInLabeledStatements && isIterationStatement(node.statement, lookInLabeledStatements); } return false; @@ -22436,11 +24175,11 @@ var ts; return grammarErrorOnNode(node, ts.Diagnostics.Jump_target_cannot_cross_function_boundary); } switch (current.kind) { - case 195 /* LabeledStatement */: + case 197 /* 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 === 190 /* ContinueStatement */ + var isMisplacedContinueLabel = node.kind === 192 /* ContinueStatement */ && !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); @@ -22448,8 +24187,8 @@ var ts; return false; } break; - case 194 /* SwitchStatement */: - if (node.kind === 191 /* BreakStatement */ && !node.label) { + case 196 /* SwitchStatement */: + if (node.kind === 193 /* BreakStatement */ && !node.label) { // unlabeled break within switch statement - ok return false; } @@ -22464,13 +24203,13 @@ var ts; current = current.parent; } if (node.label) { - var message = node.kind === 191 /* BreakStatement */ + var message = node.kind === 193 /* 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 === 191 /* BreakStatement */ + var message = node.kind === 193 /* 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); @@ -22482,7 +24221,7 @@ var ts; if (node !== ts.lastOrUndefined(elements)) { return grammarErrorOnNode(node, ts.Diagnostics.A_rest_element_must_be_last_in_an_array_destructuring_pattern); } - if (node.name.kind === 152 /* ArrayBindingPattern */ || node.name.kind === 151 /* ObjectBindingPattern */) { + if (node.name.kind === 154 /* ArrayBindingPattern */ || node.name.kind === 153 /* ObjectBindingPattern */) { return grammarErrorOnNode(node.name, ts.Diagnostics.A_rest_element_cannot_contain_a_binding_pattern); } if (node.initializer) { @@ -22490,12 +24229,9 @@ var ts; return grammarErrorAtPos(ts.getSourceFileOfNode(node), node.initializer.pos - 1, 1, ts.Diagnostics.A_rest_element_cannot_have_an_initializer); } } - // It is a SyntaxError if a VariableDeclaration or VariableDeclarationNoIn occurs within strict code - // and its Identifier is eval or arguments - return checkGrammarEvalOrArgumentsInStrictMode(node, node.name); } function checkGrammarVariableDeclaration(node) { - if (node.parent.parent.kind !== 188 /* ForInStatement */ && node.parent.parent.kind !== 189 /* ForOfStatement */) { + if (node.parent.parent.kind !== 190 /* ForInStatement */ && node.parent.parent.kind !== 191 /* ForOfStatement */) { if (ts.isInAmbientContext(node)) { if (node.initializer) { // Error on equals token which immediate precedes the initializer @@ -22519,8 +24255,7 @@ var ts; // 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)) || - checkGrammarEvalOrArgumentsInStrictMode(node, node.name); + return checkLetConstNames && checkGrammarNameInLetOrConstDeclarations(node.name); } function checkGrammarNameInLetOrConstDeclarations(name) { if (name.kind === 65 /* Identifier */) { @@ -22532,7 +24267,7 @@ var ts; var elements = name.elements; for (var _i = 0; _i < elements.length; _i++) { var element = elements[_i]; - if (element.kind !== 176 /* OmittedExpression */) { + if (element.kind !== 178 /* OmittedExpression */) { checkGrammarNameInLetOrConstDeclarations(element.name); } } @@ -22549,15 +24284,15 @@ var ts; } function allowLetAndConstDeclarations(parent) { switch (parent.kind) { - case 184 /* IfStatement */: - case 185 /* DoStatement */: - case 186 /* WhileStatement */: - case 193 /* WithStatement */: - case 187 /* ForStatement */: - case 188 /* ForInStatement */: - case 189 /* ForOfStatement */: + case 186 /* IfStatement */: + case 187 /* DoStatement */: + case 188 /* WhileStatement */: + case 195 /* WithStatement */: + case 189 /* ForStatement */: + case 190 /* ForInStatement */: + case 191 /* ForOfStatement */: return false; - case 195 /* LabeledStatement */: + case 197 /* LabeledStatement */: return allowLetAndConstDeclarations(parent.parent); } return true; @@ -22573,7 +24308,7 @@ var ts; } } function isIntegerLiteral(expression) { - if (expression.kind === 168 /* PrefixUnaryExpression */) { + if (expression.kind === 170 /* PrefixUnaryExpression */) { var unaryExpression = expression; if (unaryExpression.operator === 33 /* PlusToken */ || unaryExpression.operator === 34 /* MinusToken */) { expression = unaryExpression.operand; @@ -22602,7 +24337,7 @@ var ts; // 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 === 128 /* ComputedPropertyName */) { + if (node.name.kind === 129 /* ComputedPropertyName */) { hasError = grammarErrorOnNode(node.name, ts.Diagnostics.Computed_property_names_are_not_allowed_in_enums); } else if (inAmbientContext) { @@ -22644,26 +24379,6 @@ var ts; return true; } } - function checkGrammarEvalOrArgumentsInStrictMode(contextNode, name) { - if (name && name.kind === 65 /* Identifier */) { - var identifier = name; - if (contextNode && (contextNode.parserContextFlags & 1 /* StrictMode */) && isEvalOrArgumentsIdentifier(identifier)) { - var nameText = ts.declarationNameToString(identifier); - // We check first if the name is inside class declaration or class expression; if so give explicit message - // otherwise report generic error message. - // reportGrammarErrorInClassDeclaration only return true if grammar error is successfully reported and false otherwise - var reportErrorInClassDeclaration = reportStrictModeGrammarErrorInClassDeclaration(identifier, ts.Diagnostics.Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode, nameText); - if (!reportErrorInClassDeclaration) { - return grammarErrorOnNode(identifier, ts.Diagnostics.Invalid_use_of_0_in_strict_mode, nameText); - } - return reportErrorInClassDeclaration; - } - } - } - function isEvalOrArgumentsIdentifier(node) { - return node.kind === 65 /* Identifier */ && - (node.text === "eval" || node.text === "arguments"); - } 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); @@ -22675,18 +24390,18 @@ var ts; } } function checkGrammarProperty(node) { - if (node.parent.kind === 202 /* ClassDeclaration */) { + if (node.parent.kind === 204 /* ClassDeclaration */) { if (checkGrammarForInvalidQuestionMark(node, node.questionToken, ts.Diagnostics.A_class_member_cannot_be_declared_optional) || 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 === 203 /* InterfaceDeclaration */) { + else if (node.parent.kind === 205 /* InterfaceDeclaration */) { if (checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_an_interface_must_directly_refer_to_a_built_in_symbol)) { return true; } } - else if (node.parent.kind === 146 /* TypeLiteral */) { + else if (node.parent.kind === 148 /* 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; } @@ -22706,11 +24421,11 @@ var ts; // export_opt ExternalImportDeclaration // export_opt AmbientDeclaration // - if (node.kind === 203 /* InterfaceDeclaration */ || - node.kind === 210 /* ImportDeclaration */ || - node.kind === 209 /* ImportEqualsDeclaration */ || - node.kind === 216 /* ExportDeclaration */ || - node.kind === 215 /* ExportAssignment */ || + if (node.kind === 205 /* InterfaceDeclaration */ || + node.kind === 212 /* ImportDeclaration */ || + node.kind === 211 /* ImportEqualsDeclaration */ || + node.kind === 218 /* ExportDeclaration */ || + node.kind === 217 /* ExportAssignment */ || (node.flags & 2 /* Ambient */) || (node.flags & (1 /* Export */ | 256 /* Default */))) { return false; @@ -22720,7 +24435,7 @@ var ts; function checkGrammarTopLevelElementsForRequiredDeclareModifier(file) { for (var _i = 0, _a = file.statements; _i < _a.length; _i++) { var decl = _a[_i]; - if (ts.isDeclaration(decl) || decl.kind === 181 /* VariableStatement */) { + if (ts.isDeclaration(decl) || decl.kind === 183 /* VariableStatement */) { if (checkGrammarTopLevelElementForRequiredDeclareModifier(decl)) { return true; } @@ -22746,7 +24461,7 @@ var ts; // to prevent noisyness. 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 === 180 /* Block */ || node.parent.kind === 207 /* ModuleBlock */ || node.parent.kind === 228 /* SourceFile */) { + if (node.parent.kind === 182 /* Block */ || node.parent.kind === 209 /* ModuleBlock */ || node.parent.kind === 230 /* SourceFile */) { var links_1 = getNodeLinks(node.parent); // Check if the containing block ever report this error if (!links_1.hasReportedStatementInAmbientContext) { @@ -22759,13 +24474,8 @@ var ts; } function checkGrammarNumericLiteral(node) { // Grammar checking - if (node.flags & 16384 /* OctalLiteral */) { - if (node.parserContextFlags & 1 /* StrictMode */) { - return grammarErrorOnNode(node, ts.Diagnostics.Octal_literals_are_not_allowed_in_strict_mode); - } - else if (languageVersion >= 1 /* ES5 */) { - return grammarErrorOnNode(node, ts.Diagnostics.Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher); - } + if (node.flags & 16384 /* OctalLiteral */ && languageVersion >= 1 /* ES5 */) { + return grammarErrorOnNode(node, ts.Diagnostics.Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher); } } function grammarErrorAfterFirstToken(node, message, arg0, arg1, arg2) { @@ -22776,8 +24486,6 @@ var ts; return true; } } - initializeTypeChecker(); - return checker; } ts.createTypeChecker = createTypeChecker; })(ts || (ts = {})); @@ -22836,7 +24544,7 @@ var ts; var oldWriter = writer; ts.forEach(moduleElementDeclarationEmitInfo, function (aliasEmitInfo) { if (aliasEmitInfo.isVisible) { - ts.Debug.assert(aliasEmitInfo.node.kind === 210 /* ImportDeclaration */); + ts.Debug.assert(aliasEmitInfo.node.kind === 212 /* ImportDeclaration */); createAndSetNewTextWriterWithSymbolWriter(); ts.Debug.assert(aliasEmitInfo.indent === 0); writeImportDeclaration(aliasEmitInfo.node); @@ -22912,10 +24620,10 @@ var ts; var oldWriter = writer; ts.forEach(nodes, function (declaration) { var nodeToCheck; - if (declaration.kind === 199 /* VariableDeclaration */) { + if (declaration.kind === 201 /* VariableDeclaration */) { nodeToCheck = declaration.parent.parent; } - else if (declaration.kind === 213 /* NamedImports */ || declaration.kind === 214 /* ImportSpecifier */ || declaration.kind === 211 /* ImportClause */) { + else if (declaration.kind === 215 /* NamedImports */ || declaration.kind === 216 /* ImportSpecifier */ || declaration.kind === 213 /* ImportClause */) { ts.Debug.fail("We should be getting ImportDeclaration instead to write"); } else { @@ -22933,7 +24641,7 @@ var ts; // Writing of function bar would mark alias declaration foo as visible but we haven't yet visited that declaration so do nothing, // we would write alias foo declaration when we visit it since it would now be marked as visible if (moduleElementEmitInfo) { - if (moduleElementEmitInfo.node.kind === 210 /* ImportDeclaration */) { + if (moduleElementEmitInfo.node.kind === 212 /* ImportDeclaration */) { // we have to create asynchronous output only after we have collected complete information // because it is possible to enable multiple bindings as asynchronously visible moduleElementEmitInfo.isVisible = true; @@ -22943,12 +24651,12 @@ var ts; for (var declarationIndent = moduleElementEmitInfo.indent; declarationIndent; declarationIndent--) { increaseIndent(); } - if (nodeToCheck.kind === 206 /* ModuleDeclaration */) { + if (nodeToCheck.kind === 208 /* ModuleDeclaration */) { ts.Debug.assert(asynchronousSubModuleDeclarationEmitInfo === undefined); asynchronousSubModuleDeclarationEmitInfo = []; } writeModuleElement(nodeToCheck); - if (nodeToCheck.kind === 206 /* ModuleDeclaration */) { + if (nodeToCheck.kind === 208 /* ModuleDeclaration */) { moduleElementEmitInfo.subModuleElementDeclarationEmitInfo = asynchronousSubModuleDeclarationEmitInfo; asynchronousSubModuleDeclarationEmitInfo = undefined; } @@ -23041,41 +24749,41 @@ var ts; function emitType(type) { switch (type.kind) { case 112 /* AnyKeyword */: - case 122 /* StringKeyword */: - case 120 /* NumberKeyword */: + case 123 /* StringKeyword */: + case 121 /* NumberKeyword */: case 113 /* BooleanKeyword */: - case 123 /* SymbolKeyword */: + case 124 /* SymbolKeyword */: case 99 /* VoidKeyword */: case 8 /* StringLiteral */: return writeTextOfNode(currentSourceFile, type); - case 177 /* ExpressionWithTypeArguments */: + case 179 /* ExpressionWithTypeArguments */: return emitExpressionWithTypeArguments(type); - case 142 /* TypeReference */: + case 144 /* TypeReference */: return emitTypeReference(type); - case 145 /* TypeQuery */: + case 147 /* TypeQuery */: return emitTypeQuery(type); - case 147 /* ArrayType */: + case 149 /* ArrayType */: return emitArrayType(type); - case 148 /* TupleType */: + case 150 /* TupleType */: return emitTupleType(type); - case 149 /* UnionType */: + case 151 /* UnionType */: return emitUnionType(type); - case 150 /* ParenthesizedType */: + case 152 /* ParenthesizedType */: return emitParenType(type); - case 143 /* FunctionType */: - case 144 /* ConstructorType */: + case 145 /* FunctionType */: + case 146 /* ConstructorType */: return emitSignatureDeclarationWithJsDocComments(type); - case 146 /* TypeLiteral */: + case 148 /* TypeLiteral */: return emitTypeLiteral(type); case 65 /* Identifier */: return emitEntityName(type); - case 127 /* QualifiedName */: + case 128 /* QualifiedName */: return emitEntityName(type); } function emitEntityName(entityName) { var visibilityResult = resolver.isEntityNameVisible(entityName, // Aliases can be written asynchronously so use correct enclosing declaration - entityName.parent.kind === 209 /* ImportEqualsDeclaration */ ? entityName.parent : enclosingDeclaration); + entityName.parent.kind === 211 /* ImportEqualsDeclaration */ ? entityName.parent : enclosingDeclaration); handleSymbolAccessibilityError(visibilityResult); writeEntityName(entityName); function writeEntityName(entityName) { @@ -23083,8 +24791,8 @@ var ts; writeTextOfNode(currentSourceFile, entityName); } else { - var left = entityName.kind === 127 /* QualifiedName */ ? entityName.left : entityName.expression; - var right = entityName.kind === 127 /* QualifiedName */ ? entityName.right : entityName.name; + var left = entityName.kind === 128 /* QualifiedName */ ? entityName.left : entityName.expression; + var right = entityName.kind === 128 /* QualifiedName */ ? entityName.right : entityName.name; writeEntityName(left); write("."); writeTextOfNode(currentSourceFile, right); @@ -23093,7 +24801,7 @@ var ts; } function emitExpressionWithTypeArguments(node) { if (ts.isSupportedExpressionWithTypeArguments(node)) { - ts.Debug.assert(node.expression.kind === 65 /* Identifier */ || node.expression.kind === 156 /* PropertyAccessExpression */); + ts.Debug.assert(node.expression.kind === 65 /* Identifier */ || node.expression.kind === 158 /* PropertyAccessExpression */); emitEntityName(node.expression); if (node.typeArguments) { write("<"); @@ -23159,9 +24867,9 @@ var ts; } var count = 0; while (true) { - var name_14 = baseName + "_" + (++count); - if (!ts.hasProperty(currentSourceFile.identifiers, name_14)) { - return name_14; + var name_16 = baseName + "_" + (++count); + if (!ts.hasProperty(currentSourceFile.identifiers, name_16)) { + return name_16; } } } @@ -23205,10 +24913,10 @@ var ts; if (isModuleElementVisible) { writeModuleElement(node); } - else if (node.kind === 209 /* ImportEqualsDeclaration */ || - (node.parent.kind === 228 /* SourceFile */ && ts.isExternalModule(currentSourceFile))) { + else if (node.kind === 211 /* ImportEqualsDeclaration */ || + (node.parent.kind === 230 /* SourceFile */ && ts.isExternalModule(currentSourceFile))) { var isVisible; - if (asynchronousSubModuleDeclarationEmitInfo && node.parent.kind !== 228 /* SourceFile */) { + if (asynchronousSubModuleDeclarationEmitInfo && node.parent.kind !== 230 /* SourceFile */) { // Import declaration of another module that is visited async so lets put it in right spot asynchronousSubModuleDeclarationEmitInfo.push({ node: node, @@ -23218,7 +24926,7 @@ var ts; }); } else { - if (node.kind === 210 /* ImportDeclaration */) { + if (node.kind === 212 /* ImportDeclaration */) { var importDeclaration = node; if (importDeclaration.importClause) { isVisible = (importDeclaration.importClause.name && resolver.isDeclarationVisible(importDeclaration.importClause)) || @@ -23236,23 +24944,23 @@ var ts; } function writeModuleElement(node) { switch (node.kind) { - case 201 /* FunctionDeclaration */: + case 203 /* FunctionDeclaration */: return writeFunctionDeclaration(node); - case 181 /* VariableStatement */: + case 183 /* VariableStatement */: return writeVariableStatement(node); - case 203 /* InterfaceDeclaration */: + case 205 /* InterfaceDeclaration */: return writeInterfaceDeclaration(node); - case 202 /* ClassDeclaration */: + case 204 /* ClassDeclaration */: return writeClassDeclaration(node); - case 204 /* TypeAliasDeclaration */: + case 206 /* TypeAliasDeclaration */: return writeTypeAliasDeclaration(node); - case 205 /* EnumDeclaration */: + case 207 /* EnumDeclaration */: return writeEnumDeclaration(node); - case 206 /* ModuleDeclaration */: + case 208 /* ModuleDeclaration */: return writeModuleDeclaration(node); - case 209 /* ImportEqualsDeclaration */: + case 211 /* ImportEqualsDeclaration */: return writeImportEqualsDeclaration(node); - case 210 /* ImportDeclaration */: + case 212 /* ImportDeclaration */: return writeImportDeclaration(node); default: ts.Debug.fail("Unknown symbol kind"); @@ -23268,7 +24976,7 @@ var ts; if (node.flags & 256 /* Default */) { write("default "); } - else if (node.kind !== 203 /* InterfaceDeclaration */) { + else if (node.kind !== 205 /* InterfaceDeclaration */) { write("declare "); } } @@ -23314,7 +25022,7 @@ var ts; } function isVisibleNamedBinding(namedBindings) { if (namedBindings) { - if (namedBindings.kind === 212 /* NamespaceImport */) { + if (namedBindings.kind === 214 /* NamespaceImport */) { return resolver.isDeclarationVisible(namedBindings); } else { @@ -23342,7 +25050,7 @@ var ts; // If the default binding was emitted, write the separated write(", "); } - if (node.importClause.namedBindings.kind === 212 /* NamespaceImport */) { + if (node.importClause.namedBindings.kind === 214 /* NamespaceImport */) { write("* as "); writeTextOfNode(currentSourceFile, node.importClause.namedBindings.name); } @@ -23393,9 +25101,14 @@ var ts; function writeModuleDeclaration(node) { emitJsDocComments(node); emitModuleElementDeclarationFlags(node); - write("module "); + if (node.flags & 32768 /* Namespace */) { + write("namespace "); + } + else { + write("module "); + } writeTextOfNode(currentSourceFile, node.name); - while (node.body.kind !== 207 /* ModuleBlock */) { + while (node.body.kind !== 209 /* ModuleBlock */) { node = node.body; write("."); writeTextOfNode(currentSourceFile, node.name); @@ -23456,7 +25169,7 @@ var ts; writeLine(); } function isPrivateMethodTypeParameter(node) { - return node.parent.kind === 135 /* MethodDeclaration */ && (node.parent.flags & 32 /* Private */); + return node.parent.kind === 136 /* MethodDeclaration */ && (node.parent.flags & 32 /* Private */); } function emitTypeParameters(typeParameters) { function emitTypeParameter(node) { @@ -23467,15 +25180,15 @@ var ts; // If there is constraint present and this is not a type parameter of the private method emit the constraint if (node.constraint && !isPrivateMethodTypeParameter(node)) { write(" extends "); - if (node.parent.kind === 143 /* FunctionType */ || - node.parent.kind === 144 /* ConstructorType */ || - (node.parent.parent && node.parent.parent.kind === 146 /* TypeLiteral */)) { - ts.Debug.assert(node.parent.kind === 135 /* MethodDeclaration */ || - node.parent.kind === 134 /* MethodSignature */ || - node.parent.kind === 143 /* FunctionType */ || - node.parent.kind === 144 /* ConstructorType */ || - node.parent.kind === 139 /* CallSignature */ || - node.parent.kind === 140 /* ConstructSignature */); + if (node.parent.kind === 145 /* FunctionType */ || + node.parent.kind === 146 /* ConstructorType */ || + (node.parent.parent && node.parent.parent.kind === 148 /* TypeLiteral */)) { + ts.Debug.assert(node.parent.kind === 136 /* MethodDeclaration */ || + node.parent.kind === 135 /* MethodSignature */ || + node.parent.kind === 145 /* FunctionType */ || + node.parent.kind === 146 /* ConstructorType */ || + node.parent.kind === 140 /* CallSignature */ || + node.parent.kind === 141 /* ConstructSignature */); emitType(node.constraint); } else { @@ -23486,31 +25199,31 @@ var ts; // Type parameter constraints are named by user so we should always be able to name it var diagnosticMessage; switch (node.parent.kind) { - case 202 /* ClassDeclaration */: + case 204 /* ClassDeclaration */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_class_has_or_is_using_private_name_1; break; - case 203 /* InterfaceDeclaration */: + case 205 /* InterfaceDeclaration */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1; break; - case 140 /* ConstructSignature */: + case 141 /* ConstructSignature */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1; break; - case 139 /* CallSignature */: + case 140 /* CallSignature */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1; break; - case 135 /* MethodDeclaration */: - case 134 /* MethodSignature */: + case 136 /* MethodDeclaration */: + case 135 /* MethodSignature */: if (node.parent.flags & 128 /* Static */) { diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1; } - else if (node.parent.parent.kind === 202 /* ClassDeclaration */) { + else if (node.parent.parent.kind === 204 /* ClassDeclaration */) { diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1; } else { diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1; } break; - case 201 /* FunctionDeclaration */: + case 203 /* FunctionDeclaration */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_function_has_or_is_using_private_name_1; break; default: @@ -23541,7 +25254,7 @@ var ts; function getHeritageClauseVisibilityError(symbolAccesibilityResult) { var diagnosticMessage; // Heritage clause is written by user so it can always be named - if (node.parent.parent.kind === 202 /* ClassDeclaration */) { + if (node.parent.parent.kind === 204 /* ClassDeclaration */) { // Class or Interface implemented/extended is inaccessible diagnosticMessage = isImplementsList ? ts.Diagnostics.Implements_clause_of_exported_class_0_has_or_is_using_private_name_1 : @@ -23622,7 +25335,7 @@ var ts; function emitVariableDeclaration(node) { // If we are emitting property it isn't moduleElement and hence we already know it needs to be emitted // so there is no check needed to see if declaration is visible - if (node.kind !== 199 /* VariableDeclaration */ || resolver.isDeclarationVisible(node)) { + if (node.kind !== 201 /* VariableDeclaration */ || resolver.isDeclarationVisible(node)) { if (ts.isBindingPattern(node.name)) { emitBindingPattern(node.name); } @@ -23632,10 +25345,10 @@ var ts; // what we want, namely the name expression enclosed in brackets. writeTextOfNode(currentSourceFile, node.name); // If optional property emit ? - if ((node.kind === 133 /* PropertyDeclaration */ || node.kind === 132 /* PropertySignature */) && ts.hasQuestionToken(node)) { + if ((node.kind === 134 /* PropertyDeclaration */ || node.kind === 133 /* PropertySignature */) && ts.hasQuestionToken(node)) { write("?"); } - if ((node.kind === 133 /* PropertyDeclaration */ || node.kind === 132 /* PropertySignature */) && node.parent.kind === 146 /* TypeLiteral */) { + if ((node.kind === 134 /* PropertyDeclaration */ || node.kind === 133 /* PropertySignature */) && node.parent.kind === 148 /* TypeLiteral */) { emitTypeOfVariableDeclarationFromTypeLiteral(node); } else if (!(node.flags & 32 /* Private */)) { @@ -23644,14 +25357,14 @@ var ts; } } function getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccesibilityResult) { - if (node.kind === 199 /* VariableDeclaration */) { + if (node.kind === 201 /* VariableDeclaration */) { return symbolAccesibilityResult.errorModuleName ? symbolAccesibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : ts.Diagnostics.Exported_variable_0_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Exported_variable_0_has_or_is_using_private_name_1; } - else if (node.kind === 133 /* PropertyDeclaration */ || node.kind === 132 /* PropertySignature */) { + else if (node.kind === 134 /* PropertyDeclaration */ || node.kind === 133 /* PropertySignature */) { // TODO(jfreeman): Deal with computed properties in error reporting. if (node.flags & 128 /* Static */) { return symbolAccesibilityResult.errorModuleName ? @@ -23660,7 +25373,7 @@ var ts; ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_private_name_1; } - else if (node.parent.kind === 202 /* ClassDeclaration */) { + else if (node.parent.kind === 204 /* ClassDeclaration */) { return symbolAccesibilityResult.errorModuleName ? symbolAccesibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : @@ -23692,7 +25405,7 @@ var ts; var elements = []; for (var _i = 0, _a = bindingPattern.elements; _i < _a.length; _i++) { var element = _a[_i]; - if (element.kind !== 176 /* OmittedExpression */) { + if (element.kind !== 178 /* OmittedExpression */) { elements.push(element); } } @@ -23762,7 +25475,7 @@ var ts; var type = getTypeAnnotationFromAccessor(node); if (!type) { // couldn't get type for the first accessor, try the another one - var anotherAccessor = node.kind === 137 /* GetAccessor */ ? accessors.setAccessor : accessors.getAccessor; + var anotherAccessor = node.kind === 138 /* GetAccessor */ ? accessors.setAccessor : accessors.getAccessor; type = getTypeAnnotationFromAccessor(anotherAccessor); if (type) { accessorWithTypeAnnotation = anotherAccessor; @@ -23775,7 +25488,7 @@ var ts; } function getTypeAnnotationFromAccessor(accessor) { if (accessor) { - return accessor.kind === 137 /* GetAccessor */ + return accessor.kind === 138 /* GetAccessor */ ? accessor.type // Getter - return type : accessor.parameters.length > 0 ? accessor.parameters[0].type // Setter parameter type @@ -23784,7 +25497,7 @@ var ts; } function getAccessorDeclarationTypeVisibilityError(symbolAccesibilityResult) { var diagnosticMessage; - if (accessorWithTypeAnnotation.kind === 138 /* SetAccessor */) { + if (accessorWithTypeAnnotation.kind === 139 /* SetAccessor */) { // Setters have to have type named and cannot infer it so, the type should always be named if (accessorWithTypeAnnotation.parent.flags & 128 /* Static */) { diagnosticMessage = symbolAccesibilityResult.errorModuleName ? @@ -23834,17 +25547,17 @@ var ts; // so no need to verify if the declaration is visible if (!resolver.isImplementationOfOverload(node)) { emitJsDocComments(node); - if (node.kind === 201 /* FunctionDeclaration */) { + if (node.kind === 203 /* FunctionDeclaration */) { emitModuleElementDeclarationFlags(node); } - else if (node.kind === 135 /* MethodDeclaration */) { + else if (node.kind === 136 /* MethodDeclaration */) { emitClassMemberDeclarationFlags(node); } - if (node.kind === 201 /* FunctionDeclaration */) { + if (node.kind === 203 /* FunctionDeclaration */) { write("function "); writeTextOfNode(currentSourceFile, node.name); } - else if (node.kind === 136 /* Constructor */) { + else if (node.kind === 137 /* Constructor */) { write("constructor"); } else { @@ -23862,11 +25575,11 @@ var ts; } function emitSignatureDeclaration(node) { // Construct signature or constructor type write new Signature - if (node.kind === 140 /* ConstructSignature */ || node.kind === 144 /* ConstructorType */) { + if (node.kind === 141 /* ConstructSignature */ || node.kind === 146 /* ConstructorType */) { write("new "); } emitTypeParameters(node.typeParameters); - if (node.kind === 141 /* IndexSignature */) { + if (node.kind === 142 /* IndexSignature */) { write("["); } else { @@ -23876,22 +25589,22 @@ var ts; enclosingDeclaration = node; // Parameters emitCommaList(node.parameters, emitParameterDeclaration); - if (node.kind === 141 /* IndexSignature */) { + if (node.kind === 142 /* IndexSignature */) { write("]"); } else { write(")"); } // If this is not a constructor and is not private, emit the return type - var isFunctionTypeOrConstructorType = node.kind === 143 /* FunctionType */ || node.kind === 144 /* ConstructorType */; - if (isFunctionTypeOrConstructorType || node.parent.kind === 146 /* TypeLiteral */) { + var isFunctionTypeOrConstructorType = node.kind === 145 /* FunctionType */ || node.kind === 146 /* ConstructorType */; + if (isFunctionTypeOrConstructorType || node.parent.kind === 148 /* TypeLiteral */) { // Emit type literal signature return type only if specified if (node.type) { write(isFunctionTypeOrConstructorType ? " => " : ": "); emitType(node.type); } } - else if (node.kind !== 136 /* Constructor */ && !(node.flags & 32 /* Private */)) { + else if (node.kind !== 137 /* Constructor */ && !(node.flags & 32 /* Private */)) { writeReturnTypeAtSignature(node, getReturnTypeVisibilityError); } enclosingDeclaration = prevEnclosingDeclaration; @@ -23902,26 +25615,26 @@ var ts; function getReturnTypeVisibilityError(symbolAccesibilityResult) { var diagnosticMessage; switch (node.kind) { - case 140 /* ConstructSignature */: + case 141 /* ConstructSignature */: // Interfaces cannot have return types that cannot be named diagnosticMessage = symbolAccesibilityResult.errorModuleName ? ts.Diagnostics.Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0; break; - case 139 /* CallSignature */: + case 140 /* CallSignature */: // Interfaces cannot have return types that cannot be named diagnosticMessage = symbolAccesibilityResult.errorModuleName ? ts.Diagnostics.Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0; break; - case 141 /* IndexSignature */: + case 142 /* IndexSignature */: // Interfaces cannot have return types that cannot be named diagnosticMessage = symbolAccesibilityResult.errorModuleName ? ts.Diagnostics.Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0; break; - case 135 /* MethodDeclaration */: - case 134 /* MethodSignature */: + case 136 /* MethodDeclaration */: + case 135 /* MethodSignature */: if (node.flags & 128 /* Static */) { diagnosticMessage = symbolAccesibilityResult.errorModuleName ? symbolAccesibilityResult.accessibility === 2 /* CannotBeNamed */ ? @@ -23929,7 +25642,7 @@ var ts; ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0; } - else if (node.parent.kind === 202 /* ClassDeclaration */) { + else if (node.parent.kind === 204 /* ClassDeclaration */) { diagnosticMessage = symbolAccesibilityResult.errorModuleName ? symbolAccesibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : @@ -23943,7 +25656,7 @@ var ts; ts.Diagnostics.Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0; } break; - case 201 /* FunctionDeclaration */: + case 203 /* FunctionDeclaration */: diagnosticMessage = symbolAccesibilityResult.errorModuleName ? symbolAccesibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : @@ -23978,9 +25691,9 @@ var ts; write("?"); } decreaseIndent(); - if (node.parent.kind === 143 /* FunctionType */ || - node.parent.kind === 144 /* ConstructorType */ || - node.parent.parent.kind === 146 /* TypeLiteral */) { + if (node.parent.kind === 145 /* FunctionType */ || + node.parent.kind === 146 /* ConstructorType */ || + node.parent.parent.kind === 148 /* TypeLiteral */) { emitTypeOfVariableDeclarationFromTypeLiteral(node); } else if (!(node.parent.flags & 32 /* Private */)) { @@ -23996,24 +25709,24 @@ var ts; } function getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccesibilityResult) { switch (node.parent.kind) { - case 136 /* Constructor */: + case 137 /* Constructor */: return symbolAccesibilityResult.errorModuleName ? symbolAccesibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1; - case 140 /* ConstructSignature */: + case 141 /* ConstructSignature */: // Interfaces cannot have parameter types that cannot be named return symbolAccesibilityResult.errorModuleName ? ts.Diagnostics.Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1; - case 139 /* CallSignature */: + case 140 /* CallSignature */: // Interfaces cannot have parameter types that cannot be named return symbolAccesibilityResult.errorModuleName ? ts.Diagnostics.Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1; - case 135 /* MethodDeclaration */: - case 134 /* MethodSignature */: + case 136 /* MethodDeclaration */: + case 135 /* MethodSignature */: if (node.parent.flags & 128 /* Static */) { return symbolAccesibilityResult.errorModuleName ? symbolAccesibilityResult.accessibility === 2 /* CannotBeNamed */ ? @@ -24021,7 +25734,7 @@ var ts; ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1; } - else if (node.parent.parent.kind === 202 /* ClassDeclaration */) { + else if (node.parent.parent.kind === 204 /* ClassDeclaration */) { return symbolAccesibilityResult.errorModuleName ? symbolAccesibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : @@ -24034,7 +25747,7 @@ var ts; ts.Diagnostics.Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1; } - case 201 /* FunctionDeclaration */: + case 203 /* FunctionDeclaration */: return symbolAccesibilityResult.errorModuleName ? symbolAccesibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : @@ -24046,12 +25759,12 @@ var ts; } function emitBindingPattern(bindingPattern) { // We have to explicitly emit square bracket and bracket because these tokens are not store inside the node. - if (bindingPattern.kind === 151 /* ObjectBindingPattern */) { + if (bindingPattern.kind === 153 /* ObjectBindingPattern */) { write("{"); emitCommaList(bindingPattern.elements, emitBindingElement); write("}"); } - else if (bindingPattern.kind === 152 /* ArrayBindingPattern */) { + else if (bindingPattern.kind === 154 /* ArrayBindingPattern */) { write("["); var elements = bindingPattern.elements; emitCommaList(elements, emitBindingElement); @@ -24070,7 +25783,7 @@ var ts; typeName: bindingElement.name } : undefined; } - if (bindingElement.kind === 176 /* OmittedExpression */) { + if (bindingElement.kind === 178 /* OmittedExpression */) { // If bindingElement is an omittedExpression (i.e. containing elision), // we will emit blank space (although this may differ from users' original code, // it allows emitSeparatedList to write separator appropriately) @@ -24079,7 +25792,7 @@ var ts; // emit : function foo([ , x, , ]) {} write(" "); } - else if (bindingElement.kind === 153 /* BindingElement */) { + else if (bindingElement.kind === 155 /* BindingElement */) { if (bindingElement.propertyName) { // bindingElement has propertyName property in the following case: // { y: [a,b,c] ...} -> bindingPattern will have a property called propertyName for "y" @@ -24120,40 +25833,40 @@ var ts; } function emitNode(node) { switch (node.kind) { - case 201 /* FunctionDeclaration */: - case 206 /* ModuleDeclaration */: - case 209 /* ImportEqualsDeclaration */: - case 203 /* InterfaceDeclaration */: - case 202 /* ClassDeclaration */: - case 204 /* TypeAliasDeclaration */: - case 205 /* EnumDeclaration */: + case 203 /* FunctionDeclaration */: + case 208 /* ModuleDeclaration */: + case 211 /* ImportEqualsDeclaration */: + case 205 /* InterfaceDeclaration */: + case 204 /* ClassDeclaration */: + case 206 /* TypeAliasDeclaration */: + case 207 /* EnumDeclaration */: return emitModuleElement(node, isModuleElementVisible(node)); - case 181 /* VariableStatement */: + case 183 /* VariableStatement */: return emitModuleElement(node, isVariableStatementVisible(node)); - case 210 /* ImportDeclaration */: + case 212 /* ImportDeclaration */: // Import declaration without import clause is visible, otherwise it is not visible return emitModuleElement(node, !node.importClause); - case 216 /* ExportDeclaration */: + case 218 /* ExportDeclaration */: return emitExportDeclaration(node); - case 136 /* Constructor */: - case 135 /* MethodDeclaration */: - case 134 /* MethodSignature */: + case 137 /* Constructor */: + case 136 /* MethodDeclaration */: + case 135 /* MethodSignature */: return writeFunctionDeclaration(node); - case 140 /* ConstructSignature */: - case 139 /* CallSignature */: - case 141 /* IndexSignature */: + case 141 /* ConstructSignature */: + case 140 /* CallSignature */: + case 142 /* IndexSignature */: return emitSignatureDeclarationWithJsDocComments(node); - case 137 /* GetAccessor */: - case 138 /* SetAccessor */: + case 138 /* GetAccessor */: + case 139 /* SetAccessor */: return emitAccessorDeclaration(node); - case 133 /* PropertyDeclaration */: - case 132 /* PropertySignature */: + case 134 /* PropertyDeclaration */: + case 133 /* PropertySignature */: return emitPropertyDeclaration(node); - case 227 /* EnumMember */: + case 229 /* EnumMember */: return emitEnumMemberDeclaration(node); - case 215 /* ExportAssignment */: + case 217 /* ExportAssignment */: return emitExportAssignment(node); - case 228 /* SourceFile */: + case 230 /* SourceFile */: return emitSourceFile(node); } } @@ -24214,7 +25927,7 @@ var ts; // 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) { // emit output for the __extends helper function - var extendsHelper = "\nvar __extends = (this && this.__extends) || function (d, b) {\n for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];\n function __() { this.constructor = d; }\n __.prototype = b.prototype;\n d.prototype = new __();\n};"; + var extendsHelper = "\nvar __extends = (this && this.__extends) || function (d, b) {\n for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n};"; // emit output for the __decorate helper function var decorateHelper = "\nvar __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") return Reflect.decorate(decorators, target, key, desc);\n switch (arguments.length) {\n case 2: return decorators.reduceRight(function(o, d) { return (d && d(o)) || o; }, target);\n case 3: return decorators.reduceRight(function(o, d) { return (d && d(target, key)), void 0; }, void 0);\n case 4: return decorators.reduceRight(function(o, d) { return (d && d(target, key, o)) || o; }, desc);\n }\n};"; // emit output for the __metadata helper function @@ -24290,7 +26003,6 @@ var ts; var exportFunctionForFile; var generatedNameSet = {}; var nodeToGeneratedName = []; - var blockScopedVariableToGeneratedName; var computedPropertyNamesToGeneratedNames; var extendsEmitted = false; var decorateEmitted = false; @@ -24370,9 +26082,9 @@ var ts; tempFlags++; // Skip over 'i' and 'n' if (count !== 8 && count !== 13) { - var name_15 = count < 26 ? "_" + String.fromCharCode(97 /* a */ + count) : "_" + (count - 26); - if (isUniqueName(name_15)) { - return name_15; + var name_17 = count < 26 ? "_" + String.fromCharCode(97 /* a */ + count) : "_" + (count - 26); + if (isUniqueName(name_17)) { + return name_17; } } } @@ -24395,73 +26107,40 @@ var ts; i++; } } - function assignGeneratedName(node, name) { - nodeToGeneratedName[ts.getNodeId(node)] = ts.unescapeIdentifier(name); - } - function generateNameForFunctionOrClassDeclaration(node) { - if (!node.name) { - assignGeneratedName(node, makeUniqueName("default")); - } - } function generateNameForModuleOrEnum(node) { - if (node.name.kind === 65 /* Identifier */) { - var name_16 = node.name.text; - // Use module/enum name itself if it is unique, otherwise make a unique variation - assignGeneratedName(node, isUniqueLocalName(name_16, node) ? name_16 : makeUniqueName(name_16)); - } + var name = node.name.text; + // Use module/enum name itself if it is unique, otherwise make a unique variation + return isUniqueLocalName(name, node) ? name : makeUniqueName(name); } function generateNameForImportOrExportDeclaration(node) { var expr = ts.getExternalModuleName(node); var baseName = expr.kind === 8 /* StringLiteral */ ? ts.escapeIdentifier(ts.makeIdentifierFromModuleName(expr.text)) : "module"; - assignGeneratedName(node, makeUniqueName(baseName)); + return makeUniqueName(baseName); } - function generateNameForImportDeclaration(node) { - if (node.importClause) { - generateNameForImportOrExportDeclaration(node); - } - } - function generateNameForExportDeclaration(node) { - if (node.moduleSpecifier) { - generateNameForImportOrExportDeclaration(node); - } - } - function generateNameForExportAssignment(node) { - if (node.expression && node.expression.kind !== 65 /* Identifier */) { - assignGeneratedName(node, makeUniqueName("default")); - } + function generateNameForExportDefault() { + return makeUniqueName("default"); } function generateNameForNode(node) { switch (node.kind) { - case 201 /* FunctionDeclaration */: - case 202 /* ClassDeclaration */: - case 175 /* ClassExpression */: - generateNameForFunctionOrClassDeclaration(node); - break; - case 206 /* ModuleDeclaration */: - generateNameForModuleOrEnum(node); - generateNameForNode(node.body); - break; - case 205 /* EnumDeclaration */: - generateNameForModuleOrEnum(node); - break; - case 210 /* ImportDeclaration */: - generateNameForImportDeclaration(node); - break; - case 216 /* ExportDeclaration */: - generateNameForExportDeclaration(node); - break; - case 215 /* ExportAssignment */: - generateNameForExportAssignment(node); - break; + case 65 /* Identifier */: + return makeUniqueName(node.text); + case 208 /* ModuleDeclaration */: + case 207 /* EnumDeclaration */: + return generateNameForModuleOrEnum(node); + case 212 /* ImportDeclaration */: + case 218 /* ExportDeclaration */: + return generateNameForImportOrExportDeclaration(node); + case 203 /* FunctionDeclaration */: + case 204 /* ClassDeclaration */: + case 177 /* ClassExpression */: + case 217 /* ExportAssignment */: + return generateNameForExportDefault(); } } function getGeneratedNameForNode(node) { - var nodeId = ts.getNodeId(node); - if (!nodeToGeneratedName[nodeId]) { - generateNameForNode(node); - } - return nodeToGeneratedName[nodeId]; + var id = ts.getNodeId(node); + return nodeToGeneratedName[id] || (nodeToGeneratedName[id] = ts.unescapeIdentifier(generateNameForNode(node))); } function initializeEmitterWithSourceMaps() { var sourceMapDir; // The directory in which sourcemap will be @@ -24490,7 +26169,7 @@ var ts; } var prevEncodedEmittedColumn = lastEncodedSourceMapSpan.emittedColumn; // Line/Comma delimiters - if (lastEncodedSourceMapSpan.emittedLine == lastRecordedSourceMapSpan.emittedLine) { + if (lastEncodedSourceMapSpan.emittedLine === lastRecordedSourceMapSpan.emittedLine) { // Emit comma to separate the entry if (sourceMapData.sourceMapMappings) { sourceMapData.sourceMapMappings += ","; @@ -24559,8 +26238,8 @@ var ts; var emittedColumn = writer.getColumn(); // If this location wasn't recorded or the location in source is going backwards, record the span if (!lastRecordedSourceMapSpan || - lastRecordedSourceMapSpan.emittedLine != emittedLine || - lastRecordedSourceMapSpan.emittedColumn != emittedColumn || + lastRecordedSourceMapSpan.emittedLine !== emittedLine || + lastRecordedSourceMapSpan.emittedColumn !== emittedColumn || (lastRecordedSourceMapSpan.sourceIndex === sourceMapSourceIndex && (lastRecordedSourceMapSpan.sourceLine > sourceLinePos.line || (lastRecordedSourceMapSpan.sourceLine === sourceLinePos.line && lastRecordedSourceMapSpan.sourceColumn > sourceLinePos.character)))) { @@ -24626,8 +26305,8 @@ var ts; // Child scopes are always shown with a dot (even if they have no name), // unless it is a computed property. Then it is shown with brackets, // but the brackets are included in the name. - var name_17 = node.name; - if (!name_17 || name_17.kind !== 128 /* ComputedPropertyName */) { + var name_18 = node.name; + if (!name_18 || name_18.kind !== 129 /* ComputedPropertyName */) { scopeName = "." + scopeName; } scopeName = sourceMapData.sourceMapNames[parentIndex] + scopeName; @@ -24645,21 +26324,21 @@ var ts; // The scope was already given a name use it recordScopeNameStart(scopeName); } - else if (node.kind === 201 /* FunctionDeclaration */ || - node.kind === 163 /* FunctionExpression */ || - node.kind === 135 /* MethodDeclaration */ || - node.kind === 134 /* MethodSignature */ || - node.kind === 137 /* GetAccessor */ || - node.kind === 138 /* SetAccessor */ || - node.kind === 206 /* ModuleDeclaration */ || - node.kind === 202 /* ClassDeclaration */ || - node.kind === 205 /* EnumDeclaration */) { + else if (node.kind === 203 /* FunctionDeclaration */ || + node.kind === 165 /* FunctionExpression */ || + node.kind === 136 /* MethodDeclaration */ || + node.kind === 135 /* MethodSignature */ || + node.kind === 138 /* GetAccessor */ || + node.kind === 139 /* SetAccessor */ || + node.kind === 208 /* ModuleDeclaration */ || + node.kind === 204 /* ClassDeclaration */ || + node.kind === 207 /* EnumDeclaration */) { // Declaration and has associated name use it if (node.name) { - var name_18 = node.name; + var name_19 = node.name; // For computed property names, the text will include the brackets - scopeName = name_18.kind === 128 /* ComputedPropertyName */ - ? ts.getTextOfNode(name_18) + scopeName = name_19.kind === 129 /* ComputedPropertyName */ + ? ts.getTextOfNode(name_19) : node.name.text; } recordScopeNameStart(scopeName); @@ -24763,19 +26442,19 @@ var ts; else { sourceMapDir = ts.getDirectoryPath(ts.normalizePath(jsFilePath)); } - function emitNodeWithSourceMap(node, allowGeneratedIdentifiers) { + function emitNodeWithSourceMap(node) { if (node) { if (ts.nodeIsSynthesized(node)) { - return emitNodeWithoutSourceMap(node, false); + return emitNodeWithoutSourceMap(node); } - if (node.kind != 228 /* SourceFile */) { + if (node.kind !== 230 /* SourceFile */) { recordEmitNodeStartSpan(node); - emitNodeWithoutSourceMap(node, allowGeneratedIdentifiers); + emitNodeWithoutSourceMap(node); recordEmitNodeEndSpan(node); } else { recordNewSourceFileStart(node); - emitNodeWithoutSourceMap(node, false); + emitNodeWithoutSourceMap(node); } } } @@ -25031,10 +26710,10 @@ var ts; write("("); emit(tempVariable); // Now we emit the expressions - if (node.template.kind === 172 /* TemplateExpression */) { + if (node.template.kind === 174 /* TemplateExpression */) { ts.forEach(node.template.templateSpans, function (templateSpan) { write(", "); - var needsParens = templateSpan.expression.kind === 170 /* BinaryExpression */ + var needsParens = templateSpan.expression.kind === 172 /* BinaryExpression */ && templateSpan.expression.operatorToken.kind === 23 /* CommaToken */; emitParenthesizedIf(templateSpan.expression, needsParens); }); @@ -25069,7 +26748,7 @@ var ts; // ("abc" + 1) << (2 + "") // rather than // "abc" + (1 << 2) + "" - var needsParens = templateSpan.expression.kind !== 162 /* ParenthesizedExpression */ + var needsParens = templateSpan.expression.kind !== 164 /* ParenthesizedExpression */ && comparePrecedenceToBinaryPlus(templateSpan.expression) !== 1 /* GreaterThan */; if (i > 0 || headEmitted) { // If this is the first span and the head was not emitted, then this templateSpan's @@ -25111,11 +26790,11 @@ var ts; } function templateNeedsParens(template, parent) { switch (parent.kind) { - case 158 /* CallExpression */: - case 159 /* NewExpression */: + case 160 /* CallExpression */: + case 161 /* NewExpression */: return parent.expression === template; - case 160 /* TaggedTemplateExpression */: - case 162 /* ParenthesizedExpression */: + case 162 /* TaggedTemplateExpression */: + case 164 /* ParenthesizedExpression */: return false; default: return comparePrecedenceToBinaryPlus(parent) !== -1 /* LessThan */; @@ -25136,7 +26815,7 @@ var ts; // TODO (drosen): Note that we need to account for the upcoming 'yield' and // spread ('...') unary operators that are anticipated for ES6. switch (expression.kind) { - case 170 /* BinaryExpression */: + case 172 /* BinaryExpression */: switch (expression.operatorToken.kind) { case 35 /* AsteriskToken */: case 36 /* SlashToken */: @@ -25148,8 +26827,8 @@ var ts; default: return -1 /* LessThan */; } - case 173 /* YieldExpression */: - case 171 /* ConditionalExpression */: + case 175 /* YieldExpression */: + case 173 /* ConditionalExpression */: return -1 /* LessThan */; default: return 1 /* GreaterThan */; @@ -25164,11 +26843,11 @@ var ts; // In a sense, it does not actually emit identifiers as much as it declares a name for a specific property. // For example, this is utilized when feeding in a result to Object.defineProperty. function emitExpressionForPropertyName(node) { - ts.Debug.assert(node.kind !== 153 /* BindingElement */); + ts.Debug.assert(node.kind !== 155 /* BindingElement */); if (node.kind === 8 /* StringLiteral */) { emitLiteral(node); } - else if (node.kind === 128 /* ComputedPropertyName */) { + else if (node.kind === 129 /* ComputedPropertyName */) { // if this is a decorated computed property, we will need to capture the result // of the property expression so that we can apply decorators later. This is to ensure // we don't introduce unintended side effects: @@ -25209,75 +26888,126 @@ var ts; write("\""); } } - function isNotExpressionIdentifier(node) { + function isExpressionIdentifier(node) { var parent = node.parent; switch (parent.kind) { - case 130 /* Parameter */: - case 199 /* VariableDeclaration */: - case 153 /* BindingElement */: - case 133 /* PropertyDeclaration */: - case 132 /* PropertySignature */: - case 225 /* PropertyAssignment */: - case 226 /* ShorthandPropertyAssignment */: - case 227 /* EnumMember */: - case 135 /* MethodDeclaration */: - case 134 /* MethodSignature */: - case 201 /* FunctionDeclaration */: - case 137 /* GetAccessor */: - case 138 /* SetAccessor */: - case 163 /* FunctionExpression */: - case 202 /* ClassDeclaration */: - case 203 /* InterfaceDeclaration */: - case 205 /* EnumDeclaration */: - case 206 /* ModuleDeclaration */: - case 209 /* ImportEqualsDeclaration */: - case 211 /* ImportClause */: - case 212 /* NamespaceImport */: - return parent.name === node; - case 214 /* ImportSpecifier */: - case 218 /* ExportSpecifier */: - return parent.name === node || parent.propertyName === node; - case 191 /* BreakStatement */: - case 190 /* ContinueStatement */: - case 215 /* ExportAssignment */: - return false; - case 195 /* LabeledStatement */: - return node.parent.label === node; + case 156 /* ArrayLiteralExpression */: + case 172 /* BinaryExpression */: + case 160 /* CallExpression */: + case 223 /* CaseClause */: + case 129 /* ComputedPropertyName */: + case 173 /* ConditionalExpression */: + case 132 /* Decorator */: + case 167 /* DeleteExpression */: + case 187 /* DoStatement */: + case 159 /* ElementAccessExpression */: + case 217 /* ExportAssignment */: + case 185 /* ExpressionStatement */: + case 179 /* ExpressionWithTypeArguments */: + case 189 /* ForStatement */: + case 190 /* ForInStatement */: + case 191 /* ForOfStatement */: + case 186 /* IfStatement */: + case 161 /* NewExpression */: + case 164 /* ParenthesizedExpression */: + case 171 /* PostfixUnaryExpression */: + case 170 /* PrefixUnaryExpression */: + case 194 /* ReturnStatement */: + case 228 /* ShorthandPropertyAssignment */: + case 176 /* SpreadElementExpression */: + case 196 /* SwitchStatement */: + case 162 /* TaggedTemplateExpression */: + case 180 /* TemplateSpan */: + case 198 /* ThrowStatement */: + case 163 /* TypeAssertionExpression */: + case 168 /* TypeOfExpression */: + case 169 /* VoidExpression */: + case 188 /* WhileStatement */: + case 195 /* WithStatement */: + case 175 /* YieldExpression */: + return true; + case 155 /* BindingElement */: + case 229 /* EnumMember */: + case 131 /* Parameter */: + case 227 /* PropertyAssignment */: + case 134 /* PropertyDeclaration */: + case 201 /* VariableDeclaration */: + return parent.initializer === node; + case 158 /* PropertyAccessExpression */: + return parent.expression === node; + case 166 /* ArrowFunction */: + case 165 /* FunctionExpression */: + return parent.body === node; + case 211 /* ImportEqualsDeclaration */: + return parent.moduleReference === node; + case 128 /* QualifiedName */: + return parent.left === node; } + return false; } function emitExpressionIdentifier(node) { - var substitution = resolver.getExpressionNameSubstitution(node, getGeneratedNameForNode); - if (substitution) { - write(substitution); + var container = resolver.getReferencedExportContainer(node); + if (container) { + if (container.kind === 230 /* SourceFile */) { + // Identifier references module export + if (languageVersion < 2 /* ES6 */ && compilerOptions.module !== 4 /* System */) { + write("exports."); + } + } + else { + // Identifier references namespace export + write(getGeneratedNameForNode(container)); + write("."); + } } - else { - writeTextOfNode(currentSourceFile, node); - } - } - function getGeneratedNameForIdentifier(node) { - if (ts.nodeIsSynthesized(node) || !blockScopedVariableToGeneratedName) { - return undefined; - } - var variableId = resolver.getBlockScopedVariableId(node); - if (variableId === undefined) { - return undefined; - } - return blockScopedVariableToGeneratedName[variableId]; - } - function emitIdentifier(node, allowGeneratedIdentifiers) { - if (allowGeneratedIdentifiers) { - var generatedName = getGeneratedNameForIdentifier(node); - if (generatedName) { - write(generatedName); + else if (languageVersion < 2 /* ES6 */) { + var declaration = resolver.getReferencedImportDeclaration(node); + if (declaration) { + if (declaration.kind === 213 /* ImportClause */) { + // Identifier references default import + write(getGeneratedNameForNode(declaration.parent)); + write(languageVersion === 0 /* ES3 */ ? '["default"]' : ".default"); + return; + } + else if (declaration.kind === 216 /* ImportSpecifier */) { + // Identifier references named import + write(getGeneratedNameForNode(declaration.parent.parent.parent)); + write("."); + writeTextOfNode(currentSourceFile, declaration.propertyName || declaration.name); + return; + } + } + declaration = resolver.getReferencedNestedRedeclaration(node); + if (declaration) { + write(getGeneratedNameForNode(declaration.name)); return; } } + writeTextOfNode(currentSourceFile, node); + } + function isNameOfNestedRedeclaration(node) { + if (languageVersion < 2 /* ES6 */) { + var parent_7 = node.parent; + switch (parent_7.kind) { + case 155 /* BindingElement */: + case 204 /* ClassDeclaration */: + case 207 /* EnumDeclaration */: + case 201 /* VariableDeclaration */: + return parent_7.name === node && resolver.isNestedRedeclaration(parent_7); + } + } + return false; + } + function emitIdentifier(node) { if (!node.parent) { write(node.text); } - else if (!isNotExpressionIdentifier(node)) { + else if (isExpressionIdentifier(node)) { emitExpressionIdentifier(node); } + else if (isNameOfNestedRedeclaration(node)) { + write(getGeneratedNameForNode(node)); + } else { writeTextOfNode(currentSourceFile, node); } @@ -25318,7 +27048,7 @@ var ts; } function emitBindingElement(node) { if (node.propertyName) { - emit(node.propertyName, false); + emit(node.propertyName); write(": "); } if (node.dotDotDotToken) { @@ -25349,41 +27079,41 @@ var ts; function needsParenthesisForPropertyAccessOrInvocation(node) { switch (node.kind) { case 65 /* Identifier */: - case 154 /* ArrayLiteralExpression */: - case 156 /* PropertyAccessExpression */: - case 157 /* ElementAccessExpression */: - case 158 /* CallExpression */: - case 162 /* ParenthesizedExpression */: + case 156 /* ArrayLiteralExpression */: + case 158 /* PropertyAccessExpression */: + case 159 /* ElementAccessExpression */: + case 160 /* CallExpression */: + case 164 /* ParenthesizedExpression */: // This list is not exhaustive and only includes those cases that are relevant // to the check in emitArrayLiteral. More cases can be added as needed. return false; } return true; } - function emitListWithSpread(elements, alwaysCopy, multiLine, trailingComma) { + function emitListWithSpread(elements, needsUniqueCopy, multiLine, trailingComma, useConcat) { var pos = 0; var group = 0; var length = elements.length; while (pos < length) { // Emit using the pattern .concat(, , ...) - if (group === 1) { + if (group === 1 && useConcat) { write(".concat("); } - else if (group > 1) { + else if (group > 0) { write(", "); } var e = elements[pos]; - if (e.kind === 174 /* SpreadElementExpression */) { + if (e.kind === 176 /* SpreadElementExpression */) { e = e.expression; emitParenthesizedIf(e, group === 0 && needsParenthesisForPropertyAccessOrInvocation(e)); pos++; - if (pos === length && group === 0 && alwaysCopy && e.kind !== 154 /* ArrayLiteralExpression */) { + if (pos === length && group === 0 && needsUniqueCopy && e.kind !== 156 /* ArrayLiteralExpression */) { write(".slice()"); } } else { var i = pos; - while (i < length && elements[i].kind !== 174 /* SpreadElementExpression */) { + while (i < length && elements[i].kind !== 176 /* SpreadElementExpression */) { i++; } write("["); @@ -25400,11 +27130,13 @@ var ts; group++; } if (group > 1) { - write(")"); + if (useConcat) { + write(")"); + } } } function isSpreadElementExpression(node) { - return node.kind === 174 /* SpreadElementExpression */; + return node.kind === 176 /* SpreadElementExpression */; } function emitArrayLiteral(node) { var elements = node.elements; @@ -25418,7 +27150,7 @@ var ts; } else { emitListWithSpread(elements, true, (node.flags & 512 /* MultiLine */) !== 0, - /*trailingComma*/ elements.hasTrailingComma); + /*trailingComma*/ elements.hasTrailingComma, true); } } function emitObjectLiteralBody(node, numElements) { @@ -25474,7 +27206,7 @@ var ts; writeComma(); var property = properties[i]; emitStart(property); - if (property.kind === 137 /* GetAccessor */ || property.kind === 138 /* SetAccessor */) { + if (property.kind === 138 /* GetAccessor */ || property.kind === 139 /* SetAccessor */) { // TODO (drosen): Reconcile with 'emitMemberFunctions'. var accessors = ts.getAllAccessorDeclarations(node.properties, property); if (property !== accessors.firstAccessor) { @@ -25526,13 +27258,13 @@ var ts; emitMemberAccessForPropertyName(property.name); emitEnd(property.name); write(" = "); - if (property.kind === 225 /* PropertyAssignment */) { + if (property.kind === 227 /* PropertyAssignment */) { emit(property.initializer); } - else if (property.kind === 226 /* ShorthandPropertyAssignment */) { + else if (property.kind === 228 /* ShorthandPropertyAssignment */) { emitExpressionIdentifier(property.name); } - else if (property.kind === 135 /* MethodDeclaration */) { + else if (property.kind === 136 /* MethodDeclaration */) { emitFunctionDeclaration(property); } else { @@ -25566,7 +27298,7 @@ var ts; // Everything until that point can be emitted as part of the initial object literal. var numInitialNonComputedProperties = numProperties; for (var i = 0, n = properties.length; i < n; i++) { - if (properties[i].name.kind === 128 /* ComputedPropertyName */) { + if (properties[i].name.kind === 129 /* ComputedPropertyName */) { numInitialNonComputedProperties = i; break; } @@ -25582,26 +27314,31 @@ var ts; emitObjectLiteralBody(node, properties.length); } function createBinaryExpression(left, operator, right, startsOnNewLine) { - var result = ts.createSynthesizedNode(170 /* BinaryExpression */, startsOnNewLine); + var result = ts.createSynthesizedNode(172 /* BinaryExpression */, startsOnNewLine); result.operatorToken = ts.createSynthesizedNode(operator); result.left = left; result.right = right; return result; } function createPropertyAccessExpression(expression, name) { - var result = ts.createSynthesizedNode(156 /* PropertyAccessExpression */); + var result = ts.createSynthesizedNode(158 /* PropertyAccessExpression */); result.expression = parenthesizeForAccess(expression); result.dotToken = ts.createSynthesizedNode(20 /* DotToken */); result.name = name; return result; } function createElementAccessExpression(expression, argumentExpression) { - var result = ts.createSynthesizedNode(157 /* ElementAccessExpression */); + var result = ts.createSynthesizedNode(159 /* ElementAccessExpression */); result.expression = parenthesizeForAccess(expression); result.argumentExpression = argumentExpression; return result; } function parenthesizeForAccess(expr) { + // When diagnosing whether the expression needs parentheses, the decision should be based + // on the innermost expression in a chain of nested type assertions. + while (expr.kind === 163 /* TypeAssertionExpression */) { + expr = expr.expression; + } // isLeftHandSideExpression is almost the correct criterion for when it is not necessary // to parenthesize the expression before a dot. The known exceptions are: // @@ -25610,10 +27347,12 @@ var ts; // NumberLiteral // 1.x -> not the same as (1).x // - if (ts.isLeftHandSideExpression(expr) && expr.kind !== 159 /* NewExpression */ && expr.kind !== 7 /* NumericLiteral */) { + if (ts.isLeftHandSideExpression(expr) && + expr.kind !== 161 /* NewExpression */ && + expr.kind !== 7 /* NumericLiteral */) { return expr; } - var node = ts.createSynthesizedNode(162 /* ParenthesizedExpression */); + var node = ts.createSynthesizedNode(164 /* ParenthesizedExpression */); node.expression = expr; return node; } @@ -25626,50 +27365,43 @@ var ts; if (languageVersion >= 2 /* ES6 */ && node.asteriskToken) { write("*"); } - emit(node.name, false); + emit(node.name); if (languageVersion < 2 /* ES6 */) { write(": function "); } emitSignatureAndBody(node); } function emitPropertyAssignment(node) { - emit(node.name, false); + emit(node.name); write(": "); emit(node.initializer); } + // Return true if identifier resolves to an exported member of a namespace + function isNamespaceExportReference(node) { + var container = resolver.getReferencedExportContainer(node); + return container && container.kind !== 230 /* SourceFile */; + } function emitShorthandPropertyAssignment(node) { - emit(node.name, false); - // If short-hand property has a prefix, then regardless of the target version, we will emit it as normal property assignment. For example: - // module m { - // export let y; - // } - // module m { - // export let obj = { y }; - // } - // The short-hand property in obj need to emit as such ... = { y : m.y } regardless of the TargetScript version - if (languageVersion < 2 /* ES6 */) { + // The name property of a short-hand property assignment is considered an expression position, so here + // we manually emit the identifier to avoid rewriting. + writeTextOfNode(currentSourceFile, node.name); + // If emitting pre-ES6 code, or if the name requires rewriting when resolved as an expression identifier, + // we emit a normal property assignment. For example: + // module m { + // export let y; + // } + // module m { + // let obj = { y }; + // } + // Here we need to emit obj = { y : m.y } regardless of the output target. + if (languageVersion < 2 /* ES6 */ || isNamespaceExportReference(node.name)) { // Emit identifier as an identifier write(": "); - var generatedName = getGeneratedNameForIdentifier(node.name); - if (generatedName) { - write(generatedName); - } - else { - // Even though this is stored as identifier treat it as an expression - // Short-hand, { x }, is equivalent of normal form { x: x } - emitExpressionIdentifier(node.name); - } - } - else if (resolver.getExpressionNameSubstitution(node.name, getGeneratedNameForNode)) { - // Emit identifier as an identifier - write(": "); - // Even though this is stored as identifier treat it as an expression - // Short-hand, { x }, is equivalent of normal form { x: x } - emitExpressionIdentifier(node.name); + emit(node.name); } } function tryEmitConstantValue(node) { - if (compilerOptions.separateCompilation) { + if (compilerOptions.isolatedModules) { // do not inline enum values in separate compilation mode return false; } @@ -25677,7 +27409,7 @@ var ts; if (constantValue !== undefined) { write(constantValue.toString()); if (!compilerOptions.removeComments) { - var propertyName = node.kind === 156 /* PropertyAccessExpression */ ? ts.declarationNameToString(node.name) : ts.getTextOfNode(node.argumentExpression); + var propertyName = node.kind === 158 /* PropertyAccessExpression */ ? ts.declarationNameToString(node.name) : ts.getTextOfNode(node.argumentExpression); write(" /* " + propertyName + " */"); } return true; @@ -25711,7 +27443,7 @@ var ts; var indentedBeforeDot = indentIfOnDifferentLines(node, node.expression, node.dotToken); write("."); var indentedAfterDot = indentIfOnDifferentLines(node, node.dotToken, node.name); - emit(node.name, false); + emit(node.name); decreaseIndentIf(indentedBeforeDot, indentedAfterDot); } function emitQualifiedName(node) { @@ -25729,10 +27461,10 @@ var ts; write("]"); } function hasSpreadElement(elements) { - return ts.forEach(elements, function (e) { return e.kind === 174 /* SpreadElementExpression */; }); + return ts.forEach(elements, function (e) { return e.kind === 176 /* SpreadElementExpression */; }); } function skipParentheses(node) { - while (node.kind === 162 /* ParenthesizedExpression */ || node.kind === 161 /* TypeAssertionExpression */) { + while (node.kind === 164 /* ParenthesizedExpression */ || node.kind === 163 /* TypeAssertionExpression */) { node = node.expression; } return node; @@ -25753,13 +27485,13 @@ var ts; function emitCallWithSpread(node) { var target; var expr = skipParentheses(node.expression); - if (expr.kind === 156 /* PropertyAccessExpression */) { + if (expr.kind === 158 /* PropertyAccessExpression */) { // Target will be emitted as "this" argument target = emitCallTarget(expr.expression); write("."); emit(expr.name); } - else if (expr.kind === 157 /* ElementAccessExpression */) { + else if (expr.kind === 159 /* ElementAccessExpression */) { // Target will be emitted as "this" argument target = emitCallTarget(expr.expression); write("["); @@ -25789,7 +27521,7 @@ var ts; write("void 0"); } write(", "); - emitListWithSpread(node.arguments, false, false, false); + emitListWithSpread(node.arguments, false, false, false, true); write(")"); } function emitCallExpression(node) { @@ -25804,7 +27536,7 @@ var ts; } else { emit(node.expression); - superCall = node.expression.kind === 156 /* PropertyAccessExpression */ && node.expression.expression.kind === 91 /* SuperKeyword */; + superCall = node.expression.kind === 158 /* PropertyAccessExpression */ && node.expression.expression.kind === 91 /* SuperKeyword */; } if (superCall && languageVersion < 2 /* ES6 */) { write(".call("); @@ -25823,11 +27555,40 @@ var ts; } function emitNewExpression(node) { write("new "); - emit(node.expression); - if (node.arguments) { + // Spread operator logic is supported in new expressions in ES5 using a combination + // of Function.prototype.bind() and Function.prototype.apply(). + // + // Example: + // + // var args = [1, 2, 3, 4, 5]; + // new Array(...args); + // + // is compiled into the following ES5: + // + // var args = [1, 2, 3, 4, 5]; + // new (Array.bind.apply(Array, [void 0].concat(args))); + // + // The 'thisArg' to 'bind' is ignored when invoking the result of 'bind' with 'new', + // Thus, we set it to undefined ('void 0'). + if (languageVersion === 1 /* ES5 */ && + node.arguments && + hasSpreadElement(node.arguments)) { write("("); - emitCommaList(node.arguments); - write(")"); + var target = emitCallTarget(node.expression); + write(".bind.apply("); + emit(target); + write(", [void 0].concat("); + emitListWithSpread(node.arguments, false, false, false, false); + write(")))"); + write("()"); + } + else { + emit(node.expression); + if (node.arguments) { + write("("); + emitCommaList(node.arguments); + write(")"); + } } } function emitTaggedTemplateExpression(node) { @@ -25841,12 +27602,15 @@ var ts; } } function emitParenExpression(node) { - if (!node.parent || node.parent.kind !== 164 /* ArrowFunction */) { - if (node.expression.kind === 161 /* TypeAssertionExpression */) { + // 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 (!ts.nodeIsSynthesized(node) && node.parent.kind !== 166 /* ArrowFunction */) { + if (node.expression.kind === 163 /* TypeAssertionExpression */) { var operand = node.expression.expression; // Make sure we consider all nested cast expressions, e.g.: // (-A).x; - while (operand.kind == 161 /* TypeAssertionExpression */) { + while (operand.kind === 163 /* TypeAssertionExpression */) { operand = operand.expression; } // We have an expression of the form: (SubExpr) @@ -25857,14 +27621,14 @@ var ts; // (typeof A).toString() should be emitted as (typeof A).toString() and not typeof A.toString() // new (A()) should be emitted as new (A()) and not new A() // (function foo() { })() should be emitted as an IIF (function foo(){})() and not declaration function foo(){} () - if (operand.kind !== 168 /* PrefixUnaryExpression */ && - operand.kind !== 167 /* VoidExpression */ && - operand.kind !== 166 /* TypeOfExpression */ && - operand.kind !== 165 /* DeleteExpression */ && - operand.kind !== 169 /* PostfixUnaryExpression */ && - operand.kind !== 159 /* NewExpression */ && - !(operand.kind === 158 /* CallExpression */ && node.parent.kind === 159 /* NewExpression */) && - !(operand.kind === 163 /* FunctionExpression */ && node.parent.kind === 158 /* CallExpression */)) { + if (operand.kind !== 170 /* PrefixUnaryExpression */ && + operand.kind !== 169 /* VoidExpression */ && + operand.kind !== 168 /* TypeOfExpression */ && + operand.kind !== 167 /* DeleteExpression */ && + operand.kind !== 171 /* PostfixUnaryExpression */ && + operand.kind !== 161 /* NewExpression */ && + !(operand.kind === 160 /* CallExpression */ && node.parent.kind === 161 /* NewExpression */) && + !(operand.kind === 165 /* FunctionExpression */ && node.parent.kind === 160 /* CallExpression */)) { emit(operand); return; } @@ -25893,7 +27657,7 @@ var ts; if (!isCurrentFileSystemExternalModule() || node.kind !== 65 /* Identifier */ || ts.nodeIsSynthesized(node)) { return false; } - var isVariableDeclarationOrBindingElement = node.parent && (node.parent.kind === 199 /* VariableDeclaration */ || node.parent.kind === 153 /* BindingElement */); + var isVariableDeclarationOrBindingElement = node.parent && (node.parent.kind === 201 /* VariableDeclaration */ || node.parent.kind === 155 /* BindingElement */); var targetDeclaration = isVariableDeclarationOrBindingElement ? node.parent : resolver.getReferencedValueDeclaration(node); @@ -25923,7 +27687,7 @@ var ts; // the resulting expression a prefix increment operation. And in the second, it will make the resulting // expression a prefix increment whose operand is a plus expression - (++(+x)) // The same is true of minus of course. - if (node.operand.kind === 168 /* PrefixUnaryExpression */) { + if (node.operand.kind === 170 /* PrefixUnaryExpression */) { var operand = node.operand; if (node.operator === 33 /* PlusToken */ && (operand.operator === 33 /* PlusToken */ || operand.operator === 38 /* PlusPlusToken */)) { write(" "); @@ -25979,10 +27743,10 @@ var ts; } var current = node; while (current) { - if (current.kind === 228 /* SourceFile */) { + if (current.kind === 230 /* SourceFile */) { return !isExported || ((ts.getCombinedNodeFlags(node) & 1 /* Export */) !== 0); } - else if (ts.isFunctionLike(current) || current.kind === 207 /* ModuleBlock */) { + else if (ts.isFunctionLike(current) || current.kind === 209 /* ModuleBlock */) { return false; } else { @@ -25992,8 +27756,8 @@ var ts; } function emitBinaryExpression(node) { if (languageVersion < 2 /* ES6 */ && node.operatorToken.kind === 53 /* EqualsToken */ && - (node.left.kind === 155 /* ObjectLiteralExpression */ || node.left.kind === 154 /* ArrayLiteralExpression */)) { - emitDestructuring(node, node.parent.kind === 183 /* ExpressionStatement */); + (node.left.kind === 157 /* ObjectLiteralExpression */ || node.left.kind === 156 /* ArrayLiteralExpression */)) { + emitDestructuring(node, node.parent.kind === 185 /* ExpressionStatement */); } else { var exportChanged = node.operatorToken.kind >= 53 /* FirstAssignment */ && @@ -26045,7 +27809,7 @@ var ts; } } function isSingleLineEmptyBlock(node) { - if (node && node.kind === 180 /* Block */) { + if (node && node.kind === 182 /* Block */) { var block = node; return block.statements.length === 0 && nodeEndIsOnSameLineAsNodeStart(block, block); } @@ -26060,12 +27824,12 @@ var ts; emitToken(14 /* OpenBraceToken */, node.pos); increaseIndent(); scopeEmitStart(node.parent); - if (node.kind === 207 /* ModuleBlock */) { - ts.Debug.assert(node.parent.kind === 206 /* ModuleDeclaration */); + if (node.kind === 209 /* ModuleBlock */) { + ts.Debug.assert(node.parent.kind === 208 /* ModuleDeclaration */); emitCaptureThisForNodeIfNecessary(node.parent); } emitLines(node.statements); - if (node.kind === 207 /* ModuleBlock */) { + if (node.kind === 209 /* ModuleBlock */) { emitTempDeclarations(true); } decreaseIndent(); @@ -26074,7 +27838,7 @@ var ts; scopeEmitEnd(); } function emitEmbeddedStatement(node) { - if (node.kind === 180 /* Block */) { + if (node.kind === 182 /* Block */) { write(" "); emit(node); } @@ -26086,7 +27850,7 @@ var ts; } } function emitExpressionStatement(node) { - emitParenthesizedIf(node.expression, node.expression.kind === 164 /* ArrowFunction */); + emitParenthesizedIf(node.expression, node.expression.kind === 166 /* ArrowFunction */); write(";"); } function emitIfStatement(node) { @@ -26099,7 +27863,7 @@ var ts; if (node.elseStatement) { writeLine(); emitToken(76 /* ElseKeyword */, node.thenStatement.end); - if (node.elseStatement.kind === 184 /* IfStatement */) { + if (node.elseStatement.kind === 186 /* IfStatement */) { write(" "); emit(node.elseStatement); } @@ -26111,7 +27875,7 @@ var ts; function emitDoStatement(node) { write("do"); emitEmbeddedStatement(node.statement); - if (node.statement.kind === 180 /* Block */) { + if (node.statement.kind === 182 /* Block */) { write(" "); } else { @@ -26127,9 +27891,10 @@ var ts; write(")"); emitEmbeddedStatement(node.statement); } - /* Returns true if start of variable declaration list was emitted. - * Return false if nothing was written - this can happen for source file level variable declarations - * in system modules - such variable declarations are hoisted. + /** + * Returns true if start of variable declaration list was emitted. + * Returns false if nothing was written - this can happen for source file level variable declarations + * in system modules where such variable declarations are hoisted. */ function tryEmitStartOfVariableDeclarationList(decl, startPos) { if (shouldHoistVariable(decl, true)) { @@ -26185,7 +27950,7 @@ var ts; var endPos = emitToken(82 /* ForKeyword */, node.pos); write(" "); endPos = emitToken(16 /* OpenParenToken */, endPos); - if (node.initializer && node.initializer.kind === 200 /* VariableDeclarationList */) { + if (node.initializer && node.initializer.kind === 202 /* VariableDeclarationList */) { var variableDeclarationList = node.initializer; var startIsEmitted = tryEmitStartOfVariableDeclarationList(variableDeclarationList, endPos); if (startIsEmitted) { @@ -26206,13 +27971,13 @@ var ts; emitEmbeddedStatement(node.statement); } function emitForInOrForOfStatement(node) { - if (languageVersion < 2 /* ES6 */ && node.kind === 189 /* ForOfStatement */) { + if (languageVersion < 2 /* ES6 */ && node.kind === 191 /* ForOfStatement */) { return emitDownLevelForOfStatement(node); } var endPos = emitToken(82 /* ForKeyword */, node.pos); write(" "); endPos = emitToken(16 /* OpenParenToken */, endPos); - if (node.initializer.kind === 200 /* VariableDeclarationList */) { + if (node.initializer.kind === 202 /* VariableDeclarationList */) { var variableDeclarationList = node.initializer; if (variableDeclarationList.declarations.length >= 1) { tryEmitStartOfVariableDeclarationList(variableDeclarationList, endPos); @@ -26222,7 +27987,7 @@ var ts; else { emit(node.initializer); } - if (node.kind === 188 /* ForInStatement */) { + if (node.kind === 190 /* ForInStatement */) { write(" in "); } else { @@ -26307,7 +28072,7 @@ var ts; // let v = _a[_i]; var rhsIterationValue = createElementAccessExpression(rhsReference, counter); emitStart(node.initializer); - if (node.initializer.kind === 200 /* VariableDeclarationList */) { + if (node.initializer.kind === 202 /* VariableDeclarationList */) { write("var "); var variableDeclarationList = node.initializer; if (variableDeclarationList.declarations.length > 0) { @@ -26337,7 +28102,7 @@ var ts; // Initializer is an expression. Emit the expression in the body, so that it's // evaluated on every iteration. var assignmentExpression = createBinaryExpression(node.initializer, 53 /* EqualsToken */, rhsIterationValue, false); - if (node.initializer.kind === 154 /* ArrayLiteralExpression */ || node.initializer.kind === 155 /* ObjectLiteralExpression */) { + if (node.initializer.kind === 156 /* ArrayLiteralExpression */ || node.initializer.kind === 157 /* ObjectLiteralExpression */) { // This is a destructuring pattern, so call emitDestructuring instead of emit. Calling emit will not work, because it will cause // the BinaryExpression to be passed in instead of the expression statement, which will cause emitDestructuring to crash. emitDestructuring(assignmentExpression, true, undefined); @@ -26348,7 +28113,7 @@ var ts; } emitEnd(node.initializer); write(";"); - if (node.statement.kind === 180 /* Block */) { + if (node.statement.kind === 182 /* Block */) { emitLines(node.statement.statements); } else { @@ -26360,7 +28125,7 @@ var ts; write("}"); } function emitBreakOrContinueStatement(node) { - emitToken(node.kind === 191 /* BreakStatement */ ? 66 /* BreakKeyword */ : 71 /* ContinueKeyword */, node.pos); + emitToken(node.kind === 193 /* BreakStatement */ ? 66 /* BreakKeyword */ : 71 /* ContinueKeyword */, node.pos); emitOptional(" ", node.label); write(";"); } @@ -26405,7 +28170,7 @@ var ts; ts.getLineOfLocalPosition(currentSourceFile, ts.skipTrivia(currentSourceFile.text, node2.pos)); } function emitCaseOrDefaultClause(node) { - if (node.kind === 221 /* CaseClause */) { + if (node.kind === 223 /* CaseClause */) { write("case "); emit(node.expression); write(":"); @@ -26460,7 +28225,7 @@ var ts; function getContainingModule(node) { do { node = node.parent; - } while (node && node.kind !== 206 /* ModuleDeclaration */); + } while (node && node.kind !== 208 /* ModuleDeclaration */); return node; } function emitContainingModuleName(node) { @@ -26485,7 +28250,7 @@ var ts; function createVoidZero() { var zero = ts.createSynthesizedNode(7 /* NumericLiteral */); zero.text = "0"; - var result = ts.createSynthesizedNode(167 /* VoidExpression */); + var result = ts.createSynthesizedNode(169 /* VoidExpression */); result.expression = zero; return result; } @@ -26561,15 +28326,15 @@ var ts; // Also temporary variables should be explicitly allocated for source level declarations when module target is system // because actual variable declarations are hoisted var canDefineTempVariablesInPlace = false; - if (root.kind === 199 /* VariableDeclaration */) { + if (root.kind === 201 /* VariableDeclaration */) { var isExported = ts.getCombinedNodeFlags(root) & 1 /* Export */; var isSourceLevelForSystemModuleKind = shouldHoistDeclarationInSystemJsModule(root); canDefineTempVariablesInPlace = !isExported && !isSourceLevelForSystemModuleKind; } - else if (root.kind === 130 /* Parameter */) { + else if (root.kind === 131 /* Parameter */) { canDefineTempVariablesInPlace = true; } - if (root.kind === 170 /* BinaryExpression */) { + if (root.kind === 172 /* BinaryExpression */) { emitAssignmentExpression(root); } else { @@ -26580,8 +28345,7 @@ var ts; if (emitCount++) { write(", "); } - renameNonTopLevelLetAndConst(name); - var isVariableDeclarationOrBindingElement = name.parent && (name.parent.kind === 199 /* VariableDeclaration */ || name.parent.kind === 153 /* BindingElement */); + var isVariableDeclarationOrBindingElement = name.parent && (name.parent.kind === 201 /* VariableDeclaration */ || name.parent.kind === 155 /* BindingElement */); var exportChanged = isNameOfExportedSourceLevelDeclarationInSystemExternalModule(name); if (exportChanged) { write(exportFunctionForFile + "(\""); @@ -26616,14 +28380,14 @@ var ts; // we need to generate a temporary variable value = ensureIdentifier(value); // Return the expression 'value === void 0 ? defaultValue : value' - var equals = ts.createSynthesizedNode(170 /* BinaryExpression */); + var equals = ts.createSynthesizedNode(172 /* BinaryExpression */); equals.left = value; equals.operatorToken = ts.createSynthesizedNode(30 /* EqualsEqualsEqualsToken */); equals.right = createVoidZero(); return createConditionalExpression(equals, defaultValue, value); } function createConditionalExpression(condition, whenTrue, whenFalse) { - var cond = ts.createSynthesizedNode(171 /* ConditionalExpression */); + var cond = ts.createSynthesizedNode(173 /* ConditionalExpression */); cond.condition = condition; cond.questionToken = ts.createSynthesizedNode(50 /* QuestionToken */); cond.whenTrue = whenTrue; @@ -26637,13 +28401,17 @@ var ts; return node; } function createPropertyAccessForDestructuringProperty(object, propName) { - if (propName.kind !== 65 /* Identifier */) { - return createElementAccessExpression(object, propName); + // We create a synthetic copy of the identifier in order to avoid the rewriting that might + // otherwise occur when the identifier is emitted. + var syntheticName = ts.createSynthesizedNode(propName.kind); + syntheticName.text = propName.text; + if (syntheticName.kind !== 65 /* Identifier */) { + return createElementAccessExpression(object, syntheticName); } - return createPropertyAccessExpression(object, propName); + return createPropertyAccessExpression(object, syntheticName); } function createSliceCall(value, sliceIndex) { - var call = ts.createSynthesizedNode(158 /* CallExpression */); + var call = ts.createSynthesizedNode(160 /* CallExpression */); var sliceIdentifier = ts.createSynthesizedNode(65 /* Identifier */); sliceIdentifier.text = "slice"; call.expression = createPropertyAccessExpression(value, sliceIdentifier); @@ -26660,9 +28428,8 @@ var ts; } for (var _a = 0; _a < properties.length; _a++) { var p = properties[_a]; - if (p.kind === 225 /* PropertyAssignment */ || p.kind === 226 /* ShorthandPropertyAssignment */) { - // TODO(andersh): Computed property support - var propName = (p.name); + if (p.kind === 227 /* PropertyAssignment */ || p.kind === 228 /* ShorthandPropertyAssignment */) { + var propName = p.name; emitDestructuringAssignment(p.initializer || propName, createPropertyAccessForDestructuringProperty(value, propName)); } } @@ -26676,8 +28443,8 @@ var ts; } for (var i = 0; i < elements.length; i++) { var e = elements[i]; - if (e.kind !== 176 /* OmittedExpression */) { - if (e.kind !== 174 /* SpreadElementExpression */) { + if (e.kind !== 178 /* OmittedExpression */) { + if (e.kind !== 176 /* SpreadElementExpression */) { emitDestructuringAssignment(e, createElementAccessExpression(value, createNumericLiteral(i))); } else if (i === elements.length - 1) { @@ -26687,14 +28454,14 @@ var ts; } } function emitDestructuringAssignment(target, value) { - if (target.kind === 170 /* BinaryExpression */ && target.operatorToken.kind === 53 /* EqualsToken */) { + if (target.kind === 172 /* BinaryExpression */ && target.operatorToken.kind === 53 /* EqualsToken */) { value = createDefaultValueCheck(value, target.right); target = target.left; } - if (target.kind === 155 /* ObjectLiteralExpression */) { + if (target.kind === 157 /* ObjectLiteralExpression */) { emitObjectLiteralAssignment(target, value); } - else if (target.kind === 154 /* ArrayLiteralExpression */) { + else if (target.kind === 156 /* ArrayLiteralExpression */) { emitArrayLiteralAssignment(target, value); } else { @@ -26708,14 +28475,14 @@ var ts; emitDestructuringAssignment(target, value); } else { - if (root.parent.kind !== 162 /* ParenthesizedExpression */) { + if (root.parent.kind !== 164 /* ParenthesizedExpression */) { write("("); } value = ensureIdentifier(value); emitDestructuringAssignment(target, value); write(", "); emit(value); - if (root.parent.kind !== 162 /* ParenthesizedExpression */) { + if (root.parent.kind !== 164 /* ParenthesizedExpression */) { write(")"); } } @@ -26739,12 +28506,12 @@ var ts; } for (var i = 0; i < elements.length; i++) { var element = elements[i]; - if (pattern.kind === 151 /* ObjectBindingPattern */) { + if (pattern.kind === 153 /* ObjectBindingPattern */) { // Rewrite element to a declaration with an initializer that fetches property var propName = element.propertyName || element.name; emitBindingElement(element, createPropertyAccessForDestructuringProperty(value, propName)); } - else if (element.kind !== 176 /* OmittedExpression */) { + else if (element.kind !== 178 /* OmittedExpression */) { if (!element.dotDotDotToken) { // Rewrite element to a declaration that accesses array element at index i emitBindingElement(element, createElementAccessExpression(value, createNumericLiteral(i))); @@ -26771,7 +28538,6 @@ var ts; } } else { - renameNonTopLevelLetAndConst(node.name); var initializer = node.initializer; if (!initializer && languageVersion < 2 /* ES6 */) { // downlevel emit for non-initialized let bindings defined in loops @@ -26784,8 +28550,8 @@ var ts; (getCombinedFlagsForIdentifier(node.name) & 4096 /* Let */); // NOTE: default initialization should not be added to let bindings in for-in\for-of statements if (isUninitializedLet && - node.parent.parent.kind !== 188 /* ForInStatement */ && - node.parent.parent.kind !== 189 /* ForOfStatement */) { + node.parent.parent.kind !== 190 /* ForInStatement */ && + node.parent.parent.kind !== 191 /* ForOfStatement */) { initializer = createVoidZero(); } } @@ -26803,7 +28569,7 @@ var ts; } } function emitExportVariableAssignments(node) { - if (node.kind === 176 /* OmittedExpression */) { + if (node.kind === 178 /* OmittedExpression */) { return; } var name = node.name; @@ -26815,56 +28581,15 @@ var ts; } } function getCombinedFlagsForIdentifier(node) { - if (!node.parent || (node.parent.kind !== 199 /* VariableDeclaration */ && node.parent.kind !== 153 /* BindingElement */)) { + if (!node.parent || (node.parent.kind !== 201 /* VariableDeclaration */ && node.parent.kind !== 155 /* BindingElement */)) { return 0; } return ts.getCombinedNodeFlags(node.parent); } - function renameNonTopLevelLetAndConst(node) { - // do not rename if - // - language version is ES6+ - // - node is synthesized - // - node is not identifier (can happen when tree is malformed) - // - node is definitely not name of variable declaration. - // it still can be part of parameter declaration, this check will be done next - if (languageVersion >= 2 /* ES6 */ || - ts.nodeIsSynthesized(node) || - node.kind !== 65 /* Identifier */ || - (node.parent.kind !== 199 /* VariableDeclaration */ && node.parent.kind !== 153 /* BindingElement */)) { - return; - } - var combinedFlags = getCombinedFlagsForIdentifier(node); - if (((combinedFlags & 12288 /* BlockScoped */) === 0) || combinedFlags & 1 /* Export */) { - // do not rename exported or non-block scoped variables - return; - } - // here it is known that node is a block scoped variable - var list = ts.getAncestor(node, 200 /* VariableDeclarationList */); - if (list.parent.kind === 181 /* VariableStatement */) { - var isSourceFileLevelBinding = list.parent.parent.kind === 228 /* SourceFile */; - var isModuleLevelBinding = list.parent.parent.kind === 207 /* ModuleBlock */; - var isFunctionLevelBinding = list.parent.parent.kind === 180 /* Block */ && ts.isFunctionLike(list.parent.parent.parent); - if (isSourceFileLevelBinding || isModuleLevelBinding || isFunctionLevelBinding) { - return; - } - } - var blockScopeContainer = ts.getEnclosingBlockScopeContainer(node); - var parent = blockScopeContainer.kind === 228 /* SourceFile */ - ? blockScopeContainer - : blockScopeContainer.parent; - if (resolver.resolvesToSomeValue(parent, node.text)) { - var variableId = resolver.getBlockScopedVariableId(node); - if (!blockScopedVariableToGeneratedName) { - blockScopedVariableToGeneratedName = []; - } - var generatedName = makeUniqueName(node.text); - blockScopedVariableToGeneratedName[variableId] = generatedName; - } - } function isES6ExportedDeclaration(node) { return !!(node.flags & 1 /* Export */) && languageVersion >= 2 /* ES6 */ && - node.parent.kind === 228 /* SourceFile */; + node.parent.kind === 230 /* SourceFile */; } function emitVariableStatement(node) { var startIsEmitted = false; @@ -26892,15 +28617,35 @@ var ts; ts.forEach(node.declarationList.declarations, emitExportVariableAssignments); } } + function shouldEmitLeadingAndTrailingCommentsForVariableStatement(node) { + // If we're not exporting the variables, there's nothing special here. + // Always emit comments for these nodes. + if (!(node.flags & 1 /* Export */)) { + return true; + } + // If we are exporting, but it's a top-level ES6 module exports, + // we'll emit the declaration list verbatim, so emit comments too. + if (isES6ExportedDeclaration(node)) { + return true; + } + // Otherwise, only emit if we have at least one initializer present. + for (var _a = 0, _b = node.declarationList.declarations; _a < _b.length; _a++) { + var declaration = _b[_a]; + if (declaration.initializer) { + return true; + } + } + return false; + } function emitParameter(node) { if (languageVersion < 2 /* ES6 */) { if (ts.isBindingPattern(node.name)) { - var name_19 = createTempVariable(0 /* Auto */); + var name_20 = createTempVariable(0 /* Auto */); if (!tempParameters) { tempParameters = []; } - tempParameters.push(name_19); - emit(name_19); + tempParameters.push(name_20); + emit(name_20); } else { emit(node.name); @@ -26949,7 +28694,7 @@ var ts; } } function emitRestParameter(node) { - if (languageVersion < 2 /* ES6 */ && ts.hasRestParameters(node)) { + if (languageVersion < 2 /* ES6 */ && ts.hasRestParameter(node)) { var restIndex = node.parameters.length - 1; var restParam = node.parameters[restIndex]; // A rest parameter cannot have a binding pattern, so let's just ignore it if it does. @@ -26991,12 +28736,12 @@ var ts; } } function emitAccessor(node) { - write(node.kind === 137 /* GetAccessor */ ? "get " : "set "); - emit(node.name, false); + write(node.kind === 138 /* GetAccessor */ ? "get " : "set "); + emit(node.name); emitSignatureAndBody(node); } function shouldEmitAsArrowFunction(node) { - return node.kind === 164 /* ArrowFunction */ && languageVersion >= 2 /* ES6 */; + return node.kind === 166 /* ArrowFunction */ && languageVersion >= 2 /* ES6 */; } function emitDeclarationName(node) { if (node.name) { @@ -27007,11 +28752,11 @@ var ts; } } function shouldEmitFunctionName(node) { - if (node.kind === 163 /* FunctionExpression */) { + if (node.kind === 165 /* FunctionExpression */) { // Emit name if one is present return !!node.name; } - if (node.kind === 201 /* FunctionDeclaration */) { + if (node.kind === 203 /* FunctionDeclaration */) { // Emit name if one is present, or emit generated name in down-level case (for export default case) return !!node.name || languageVersion < 2 /* ES6 */; } @@ -27020,7 +28765,7 @@ var ts; if (ts.nodeIsMissing(node.body)) { return emitOnlyPinnedOrTripleSlashComments(node); } - if (node.kind !== 135 /* MethodDeclaration */ && node.kind !== 134 /* MethodSignature */) { + if (node.kind !== 136 /* MethodDeclaration */ && node.kind !== 135 /* MethodSignature */) { // Methods will emit the comments as part of emitting method declaration emitLeadingComments(node); } @@ -27043,10 +28788,10 @@ var ts; emitDeclarationName(node); } emitSignatureAndBody(node); - if (languageVersion < 2 /* ES6 */ && node.kind === 201 /* FunctionDeclaration */ && node.parent === currentSourceFile && node.name) { + if (languageVersion < 2 /* ES6 */ && node.kind === 203 /* FunctionDeclaration */ && node.parent === currentSourceFile && node.name) { emitExportMemberAssignments(node.name); } - if (node.kind !== 135 /* MethodDeclaration */ && node.kind !== 134 /* MethodSignature */) { + if (node.kind !== 136 /* MethodDeclaration */ && node.kind !== 135 /* MethodSignature */) { emitTrailingComments(node); } } @@ -27063,7 +28808,7 @@ var ts; write("("); if (node) { var parameters = node.parameters; - var omitCount = languageVersion < 2 /* ES6 */ && ts.hasRestParameters(node) ? 1 : 0; + var omitCount = languageVersion < 2 /* ES6 */ && ts.hasRestParameter(node) ? 1 : 0; emitList(parameters, 0, parameters.length - omitCount, false, false); } write(")"); @@ -27097,7 +28842,7 @@ var ts; // in that case. write(" { }"); } - else if (node.body.kind === 180 /* Block */) { + else if (node.body.kind === 182 /* Block */) { emitBlockFunctionBody(node, node.body); } else { @@ -27128,10 +28873,10 @@ var ts; write(" "); // Unwrap all type assertions. var current = body; - while (current.kind === 161 /* TypeAssertionExpression */) { + while (current.kind === 163 /* TypeAssertionExpression */) { current = current.expression; } - emitParenthesizedIf(body, current.kind === 155 /* ObjectLiteralExpression */); + emitParenthesizedIf(body, current.kind === 157 /* ObjectLiteralExpression */); } function emitDownLevelExpressionFunctionBody(node, body) { write(" {"); @@ -27207,9 +28952,9 @@ var ts; function findInitialSuperCall(ctor) { if (ctor.body) { var statement = ctor.body.statements[0]; - if (statement && statement.kind === 183 /* ExpressionStatement */) { + if (statement && statement.kind === 185 /* ExpressionStatement */) { var expr = statement.expression; - if (expr && expr.kind === 158 /* CallExpression */) { + if (expr && expr.kind === 160 /* CallExpression */) { var func = expr.expression; if (func && func.kind === 91 /* SuperKeyword */) { return statement; @@ -27241,7 +28986,7 @@ var ts; emitNodeWithoutSourceMap(memberName); write("]"); } - else if (memberName.kind === 128 /* ComputedPropertyName */) { + else if (memberName.kind === 129 /* ComputedPropertyName */) { emitComputedPropertyName(memberName); } else { @@ -27253,7 +28998,7 @@ var ts; var properties = []; for (var _a = 0, _b = node.members; _a < _b.length; _a++) { var member = _b[_a]; - if (member.kind === 133 /* PropertyDeclaration */ && isStatic === ((member.flags & 128 /* Static */) !== 0) && member.initializer) { + if (member.kind === 134 /* PropertyDeclaration */ && isStatic === ((member.flags & 128 /* Static */) !== 0) && member.initializer) { properties.push(member); } } @@ -27293,11 +29038,11 @@ var ts; } function emitMemberFunctionsForES5AndLower(node) { ts.forEach(node.members, function (member) { - if (member.kind === 179 /* SemicolonClassElement */) { + if (member.kind === 181 /* SemicolonClassElement */) { writeLine(); write(";"); } - else if (member.kind === 135 /* MethodDeclaration */ || node.kind === 134 /* MethodSignature */) { + else if (member.kind === 136 /* MethodDeclaration */ || node.kind === 135 /* MethodSignature */) { if (!member.body) { return emitOnlyPinnedOrTripleSlashComments(member); } @@ -27316,7 +29061,7 @@ var ts; write(";"); emitTrailingComments(member); } - else if (member.kind === 137 /* GetAccessor */ || member.kind === 138 /* SetAccessor */) { + else if (member.kind === 138 /* GetAccessor */ || member.kind === 139 /* SetAccessor */) { var accessors = ts.getAllAccessorDeclarations(node.members, member); if (member === accessors.firstAccessor) { writeLine(); @@ -27366,22 +29111,22 @@ var ts; function emitMemberFunctionsForES6AndHigher(node) { for (var _a = 0, _b = node.members; _a < _b.length; _a++) { var member = _b[_a]; - if ((member.kind === 135 /* MethodDeclaration */ || node.kind === 134 /* MethodSignature */) && !member.body) { + if ((member.kind === 136 /* MethodDeclaration */ || node.kind === 135 /* MethodSignature */) && !member.body) { emitOnlyPinnedOrTripleSlashComments(member); } - else if (member.kind === 135 /* MethodDeclaration */ || - member.kind === 137 /* GetAccessor */ || - member.kind === 138 /* SetAccessor */) { + else if (member.kind === 136 /* MethodDeclaration */ || + member.kind === 138 /* GetAccessor */ || + member.kind === 139 /* SetAccessor */) { writeLine(); emitLeadingComments(member); emitStart(member); if (member.flags & 128 /* Static */) { write("static "); } - if (member.kind === 137 /* GetAccessor */) { + if (member.kind === 138 /* GetAccessor */) { write("get "); } - else if (member.kind === 138 /* SetAccessor */) { + else if (member.kind === 139 /* SetAccessor */) { write("set "); } if (member.asteriskToken) { @@ -27392,7 +29137,7 @@ var ts; emitEnd(member); emitTrailingComments(member); } - else if (member.kind === 179 /* SemicolonClassElement */) { + else if (member.kind === 181 /* SemicolonClassElement */) { writeLine(); write(";"); } @@ -27417,11 +29162,11 @@ var ts; var hasInstancePropertyWithInitializer = false; // Emit the constructor overload pinned comments ts.forEach(node.members, function (member) { - if (member.kind === 136 /* Constructor */ && !member.body) { + if (member.kind === 137 /* Constructor */ && !member.body) { emitOnlyPinnedOrTripleSlashComments(member); } // Check if there is any non-static property assignment - if (member.kind === 133 /* PropertyDeclaration */ && member.initializer && (member.flags & 128 /* Static */) === 0) { + if (member.kind === 134 /* PropertyDeclaration */ && member.initializer && (member.flags & 128 /* Static */) === 0) { hasInstancePropertyWithInitializer = true; } }); @@ -27529,7 +29274,7 @@ var ts; } function emitClassLikeDeclarationForES6AndHigher(node) { var thisNodeIsDecorated = ts.nodeIsDecorated(node); - if (node.kind === 202 /* ClassDeclaration */) { + if (node.kind === 204 /* ClassDeclaration */) { if (thisNodeIsDecorated) { // To preserve the correct runtime semantics when decorators are applied to the class, // the emit needs to follow one of the following rules: @@ -27609,7 +29354,7 @@ var ts; // This keeps the expression as an expression, while ensuring that the static parts // of it have been initialized by the time it is used. var staticProperties = getInitializedProperties(node, true); - var isClassExpressionWithStaticProperties = staticProperties.length > 0 && node.kind === 175 /* ClassExpression */; + var isClassExpressionWithStaticProperties = staticProperties.length > 0 && node.kind === 177 /* ClassExpression */; var tempVariable; if (isClassExpressionWithStaticProperties) { tempVariable = createAndRecordTempVariable(0 /* Auto */); @@ -27693,7 +29438,7 @@ var ts; } } function emitClassLikeDeclarationBelowES6(node) { - if (node.kind === 202 /* ClassDeclaration */) { + if (node.kind === 204 /* ClassDeclaration */) { // source file level classes in system modules are hoisted so 'var's for them are already defined if (!shouldHoistDeclarationInSystemJsModule(node)) { write("var "); @@ -27752,11 +29497,11 @@ var ts; emit(baseTypeNode.expression); } write(")"); - if (node.kind === 202 /* ClassDeclaration */) { + if (node.kind === 204 /* ClassDeclaration */) { write(";"); } emitEnd(node); - if (node.kind === 202 /* ClassDeclaration */) { + if (node.kind === 204 /* ClassDeclaration */) { emitExportMemberAssignment(node); } if (languageVersion < 2 /* ES6 */ && node.parent === currentSourceFile && node.name) { @@ -27848,7 +29593,7 @@ var ts; else { decorators = member.decorators; // we only decorate the parameters here if this is a method - if (member.kind === 135 /* MethodDeclaration */) { + if (member.kind === 136 /* MethodDeclaration */) { functionLikeMember = member; } } @@ -27886,7 +29631,7 @@ var ts; // writeLine(); emitStart(member); - if (member.kind !== 133 /* PropertyDeclaration */) { + if (member.kind !== 134 /* PropertyDeclaration */) { write("Object.defineProperty("); emitStart(member.name); emitClassMemberPrefix(node, member); @@ -27916,7 +29661,7 @@ var ts; write(", "); emitExpressionForPropertyName(member.name); emitEnd(member.name); - if (member.kind !== 133 /* PropertyDeclaration */) { + if (member.kind !== 134 /* PropertyDeclaration */) { write(", Object.getOwnPropertyDescriptor("); emitStart(member.name); emitClassMemberPrefix(node, member); @@ -27958,10 +29703,10 @@ var ts; // The caller should have already tested whether the node has decorators and whether the emitDecoratorMetadata // compiler option is set. switch (node.kind) { - case 135 /* MethodDeclaration */: - case 137 /* GetAccessor */: - case 138 /* SetAccessor */: - case 133 /* PropertyDeclaration */: + case 136 /* MethodDeclaration */: + case 138 /* GetAccessor */: + case 139 /* SetAccessor */: + case 134 /* PropertyDeclaration */: return true; } return false; @@ -27971,7 +29716,7 @@ var ts; // The caller should have already tested whether the node has decorators and whether the emitDecoratorMetadata // compiler option is set. switch (node.kind) { - case 135 /* MethodDeclaration */: + case 136 /* MethodDeclaration */: return true; } return false; @@ -27981,9 +29726,9 @@ var ts; // The caller should have already tested whether the node has decorators and whether the emitDecoratorMetadata // compiler option is set. switch (node.kind) { - case 202 /* ClassDeclaration */: - case 135 /* MethodDeclaration */: - case 138 /* SetAccessor */: + case 204 /* ClassDeclaration */: + case 136 /* MethodDeclaration */: + case 139 /* SetAccessor */: return true; } return false; @@ -27994,7 +29739,7 @@ var ts; var argumentsWritten = 0; if (compilerOptions.emitDecoratorMetadata) { if (shouldEmitTypeMetadata(node)) { - var serializedType = resolver.serializeTypeOfNode(node, getGeneratedNameForNode); + var serializedType = resolver.serializeTypeOfNode(node); if (serializedType) { if (writeComma) { write(", "); @@ -28007,7 +29752,7 @@ var ts; } } if (shouldEmitParamTypesMetadata(node)) { - var serializedTypes = resolver.serializeParameterTypesOfNode(node, getGeneratedNameForNode); + var serializedTypes = resolver.serializeParameterTypesOfNode(node); if (serializedTypes) { if (writeComma || argumentsWritten) { write(", "); @@ -28025,7 +29770,7 @@ var ts; } } if (shouldEmitReturnTypeMetadata(node)) { - var serializedType = resolver.serializeReturnTypeOfNode(node, getGeneratedNameForNode); + var serializedType = resolver.serializeReturnTypeOfNode(node); if (serializedType) { if (writeComma || argumentsWritten) { write(", "); @@ -28066,7 +29811,7 @@ var ts; } function shouldEmitEnumDeclaration(node) { var isConstEnum = ts.isConst(node); - return !isConstEnum || compilerOptions.preserveConstEnums || compilerOptions.separateCompilation; + return !isConstEnum || compilerOptions.preserveConstEnums || compilerOptions.isolatedModules; } function emitEnumDeclaration(node) { // const enums are completely erased during compilation. @@ -28125,7 +29870,7 @@ var ts; emitDeclarationName(node); write("\", "); emitDeclarationName(node); - write(")"); + write(");"); } emitExportMemberAssignments(node.name); } @@ -28159,13 +29904,13 @@ var ts; } } function getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration) { - if (moduleDeclaration.body.kind === 206 /* ModuleDeclaration */) { + if (moduleDeclaration.body.kind === 208 /* ModuleDeclaration */) { var recursiveInnerModule = getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration.body); return recursiveInnerModule || moduleDeclaration.body; } } function shouldEmitModuleDeclaration(node) { - return ts.isInstantiatedModule(node, compilerOptions.preserveConstEnums || compilerOptions.separateCompilation); + return ts.isInstantiatedModule(node, compilerOptions.preserveConstEnums || compilerOptions.isolatedModules); } function isModuleMergedWithES6Class(node) { return languageVersion === 2 /* ES6 */ && !!(resolver.getNodeCheckFlags(node) & 2048 /* LexicalModuleMergesWithClass */); @@ -28195,7 +29940,7 @@ var ts; write(getGeneratedNameForNode(node)); emitEnd(node.name); write(") "); - if (node.body.kind === 207 /* ModuleBlock */) { + if (node.body.kind === 209 /* ModuleBlock */) { var saveTempFlags = tempFlags; var saveTempVariables = tempVariables; tempFlags = 0; @@ -28235,7 +29980,7 @@ var ts; emitDeclarationName(node); write("\", "); emitDeclarationName(node); - write(")"); + write(");"); } emitExportMemberAssignments(node.name); } @@ -28253,16 +29998,16 @@ var ts; } } function getNamespaceDeclarationNode(node) { - if (node.kind === 209 /* ImportEqualsDeclaration */) { + if (node.kind === 211 /* ImportEqualsDeclaration */) { return node; } var importClause = node.importClause; - if (importClause && importClause.namedBindings && importClause.namedBindings.kind === 212 /* NamespaceImport */) { + if (importClause && importClause.namedBindings && importClause.namedBindings.kind === 214 /* NamespaceImport */) { return importClause.namedBindings; } } function isDefaultImport(node) { - return node.kind === 210 /* ImportDeclaration */ && node.importClause && !!node.importClause.name; + return node.kind === 212 /* ImportDeclaration */ && node.importClause && !!node.importClause.name; } function emitExportImportAssignments(node) { if (ts.isAliasSymbolDeclaration(node) && resolver.isValueAliasDeclaration(node)) { @@ -28290,7 +30035,7 @@ var ts; if (shouldEmitNamedBindings) { emitLeadingComments(node.importClause.namedBindings); emitStart(node.importClause.namedBindings); - if (node.importClause.namedBindings.kind === 212 /* NamespaceImport */) { + if (node.importClause.namedBindings.kind === 214 /* NamespaceImport */) { write("* as "); emit(node.importClause.namedBindings.name); } @@ -28316,7 +30061,7 @@ var ts; } function emitExternalImportDeclaration(node) { if (ts.contains(externalImports, node)) { - var isExportedImport = node.kind === 209 /* ImportEqualsDeclaration */ && (node.flags & 1 /* Export */) !== 0; + var isExportedImport = node.kind === 211 /* ImportEqualsDeclaration */ && (node.flags & 1 /* Export */) !== 0; var namespaceDeclaration = getNamespaceDeclarationNode(node); if (compilerOptions.module !== 2 /* AMD */) { emitLeadingComments(node); @@ -28335,7 +30080,7 @@ var ts; // import { x, y } from "foo" // import d, * as x from "foo" // import d, { x, y } from "foo" - var isNakedImport = 210 /* ImportDeclaration */ && !node.importClause; + var isNakedImport = 212 /* ImportDeclaration */ && !node.importClause; if (!isNakedImport) { write("var "); write(getGeneratedNameForNode(node)); @@ -28499,8 +30244,8 @@ var ts; write("export default "); var expression = node.expression; emit(expression); - if (expression.kind !== 201 /* FunctionDeclaration */ && - expression.kind !== 202 /* ClassDeclaration */) { + if (expression.kind !== 203 /* FunctionDeclaration */ && + expression.kind !== 204 /* ClassDeclaration */) { write(";"); } emitEnd(node); @@ -28536,7 +30281,7 @@ var ts; for (var _a = 0, _b = sourceFile.statements; _a < _b.length; _a++) { var node = _b[_a]; switch (node.kind) { - case 210 /* ImportDeclaration */: + case 212 /* ImportDeclaration */: if (!node.importClause || resolver.isReferencedAliasDeclaration(node.importClause, true)) { // import "mod" @@ -28546,13 +30291,13 @@ var ts; externalImports.push(node); } break; - case 209 /* ImportEqualsDeclaration */: - if (node.moduleReference.kind === 220 /* ExternalModuleReference */ && resolver.isReferencedAliasDeclaration(node)) { + case 211 /* ImportEqualsDeclaration */: + if (node.moduleReference.kind === 222 /* ExternalModuleReference */ && resolver.isReferencedAliasDeclaration(node)) { // import x = require("mod") where x is referenced externalImports.push(node); } break; - case 216 /* ExportDeclaration */: + case 218 /* ExportDeclaration */: if (node.moduleSpecifier) { if (!node.exportClause) { // export * from "mod" @@ -28568,12 +30313,12 @@ var ts; // export { x, y } for (var _c = 0, _d = node.exportClause.elements; _c < _d.length; _c++) { var specifier = _d[_c]; - var name_20 = (specifier.propertyName || specifier.name).text; - (exportSpecifiers[name_20] || (exportSpecifiers[name_20] = [])).push(specifier); + var name_21 = (specifier.propertyName || specifier.name).text; + (exportSpecifiers[name_21] || (exportSpecifiers[name_21] = [])).push(specifier); } } break; - case 215 /* ExportAssignment */: + case 217 /* ExportAssignment */: if (node.isExportEquals && !exportEquals) { // export = x exportEquals = node; @@ -28594,13 +30339,16 @@ var ts; write("}"); } } - function getLocalNameForExternalImport(importNode) { - var namespaceDeclaration = getNamespaceDeclarationNode(importNode); - if (namespaceDeclaration && !isDefaultImport(importNode)) { + function getLocalNameForExternalImport(node) { + var namespaceDeclaration = getNamespaceDeclarationNode(node); + if (namespaceDeclaration && !isDefaultImport(node)) { return ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, namespaceDeclaration.name); } - else { - return getGeneratedNameForNode(importNode); + if (node.kind === 212 /* ImportDeclaration */ && node.importClause) { + return getGeneratedNameForNode(node); + } + if (node.kind === 218 /* ExportDeclaration */ && node.moduleSpecifier) { + return getGeneratedNameForNode(node); } } function getExternalModuleNameText(importNode) { @@ -28619,8 +30367,8 @@ var ts; for (var _a = 0; _a < externalImports.length; _a++) { var importNode = externalImports[_a]; // do not create variable declaration for exports and imports that lack import clause - var skipNode = importNode.kind === 216 /* ExportDeclaration */ || - (importNode.kind === 210 /* ImportDeclaration */ && !importNode.importClause); + var skipNode = importNode.kind === 218 /* ExportDeclaration */ || + (importNode.kind === 212 /* ImportDeclaration */ && !importNode.importClause); if (skipNode) { continue; } @@ -28653,7 +30401,7 @@ var ts; var hasExportDeclarationWithExportClause = false; for (var _a = 0; _a < externalImports.length; _a++) { var externalImport = externalImports[_a]; - if (externalImport.kind === 216 /* ExportDeclaration */ && externalImport.exportClause) { + if (externalImport.kind === 218 /* ExportDeclaration */ && externalImport.exportClause) { hasExportDeclarationWithExportClause = true; break; } @@ -28685,7 +30433,7 @@ var ts; } for (var _d = 0; _d < externalImports.length; _d++) { var externalImport = externalImports[_d]; - if (externalImport.kind !== 216 /* ExportDeclaration */) { + if (externalImport.kind !== 218 /* ExportDeclaration */) { continue; } var exportDecl = externalImport; @@ -28769,12 +30517,12 @@ var ts; var seen = {}; for (var i = 0; i < hoistedVars.length; ++i) { var local = hoistedVars[i]; - var name_21 = local.kind === 65 /* Identifier */ + var name_22 = local.kind === 65 /* Identifier */ ? local : local.name; - if (name_21) { + if (name_22) { // do not emit duplicate entries (in case of declaration merging) in the list of hoisted variables - var text = ts.unescapeIdentifier(name_21.text); + var text = ts.unescapeIdentifier(name_22.text); if (ts.hasProperty(seen, text)) { continue; } @@ -28785,7 +30533,7 @@ var ts; if (i !== 0) { write(", "); } - if (local.kind === 202 /* ClassDeclaration */ || local.kind === 206 /* ModuleDeclaration */ || local.kind === 205 /* EnumDeclaration */) { + if (local.kind === 204 /* ClassDeclaration */ || local.kind === 208 /* ModuleDeclaration */ || local.kind === 207 /* EnumDeclaration */) { emitDeclarationName(local); } else { @@ -28819,21 +30567,21 @@ var ts; if (node.flags & 2 /* Ambient */) { return; } - if (node.kind === 201 /* FunctionDeclaration */) { + if (node.kind === 203 /* FunctionDeclaration */) { if (!hoistedFunctionDeclarations) { hoistedFunctionDeclarations = []; } hoistedFunctionDeclarations.push(node); return; } - if (node.kind === 202 /* ClassDeclaration */) { + if (node.kind === 204 /* ClassDeclaration */) { if (!hoistedVars) { hoistedVars = []; } hoistedVars.push(node); return; } - if (node.kind === 205 /* EnumDeclaration */) { + if (node.kind === 207 /* EnumDeclaration */) { if (shouldEmitEnumDeclaration(node)) { if (!hoistedVars) { hoistedVars = []; @@ -28842,7 +30590,7 @@ var ts; } return; } - if (node.kind === 206 /* ModuleDeclaration */) { + if (node.kind === 208 /* ModuleDeclaration */) { if (shouldEmitModuleDeclaration(node)) { if (!hoistedVars) { hoistedVars = []; @@ -28851,17 +30599,17 @@ var ts; } return; } - if (node.kind === 199 /* VariableDeclaration */ || node.kind === 153 /* BindingElement */) { + if (node.kind === 201 /* VariableDeclaration */ || node.kind === 155 /* BindingElement */) { if (shouldHoistVariable(node, false)) { - var name_22 = node.name; - if (name_22.kind === 65 /* Identifier */) { + var name_23 = node.name; + if (name_23.kind === 65 /* Identifier */) { if (!hoistedVars) { hoistedVars = []; } - hoistedVars.push(name_22); + hoistedVars.push(name_23); } else { - ts.forEachChild(name_22, visit); + ts.forEachChild(name_23, visit); } } return; @@ -28885,7 +30633,7 @@ var ts; // if block scoped variables are nested in some another block then // no other functions can use them except ones that are defined at least in the same block return (ts.getCombinedNodeFlags(node) & 12288 /* BlockScoped */) === 0 || - ts.getEnclosingBlockScopeContainer(node).kind === 228 /* SourceFile */; + ts.getEnclosingBlockScopeContainer(node).kind === 230 /* SourceFile */; } function isCurrentFileSystemExternalModule() { return compilerOptions.module === 4 /* System */ && ts.isExternalModule(currentSourceFile); @@ -28938,10 +30686,10 @@ var ts; emitSetters(exportStarFunction); writeLine(); emitExecute(node, startIndex); - emitTempDeclarations(true); decreaseIndent(); writeLine(); write("}"); // return + emitTempDeclarations(true); } function emitSetters(exportStarFunction) { write("setters:["); @@ -28956,21 +30704,21 @@ var ts; var parameterName = "_" + importVariableName; write("function (" + parameterName + ") {"); switch (importNode.kind) { - case 210 /* ImportDeclaration */: + case 212 /* ImportDeclaration */: if (!importNode.importClause) { // 'import "..."' case // module is imported only for side-effects, setter body will be empty break; } // fall-through - case 209 /* ImportEqualsDeclaration */: + case 211 /* ImportEqualsDeclaration */: ts.Debug.assert(importVariableName !== ""); increaseIndent(); writeLine(); // save import into the local write(importVariableName + " = " + parameterName + ";"); writeLine(); - var defaultName = importNode.kind === 210 /* ImportDeclaration */ + var defaultName = importNode.kind === 212 /* ImportDeclaration */ ? importNode.importClause.name : importNode.name; if (defaultName) { @@ -28982,10 +30730,10 @@ var ts; emitExportMemberAssignments(defaultName); writeLine(); } - if (importNode.kind === 210 /* ImportDeclaration */ && + if (importNode.kind === 212 /* ImportDeclaration */ && importNode.importClause.namedBindings) { var namedBindings = importNode.importClause.namedBindings; - if (namedBindings.kind === 212 /* NamespaceImport */) { + if (namedBindings.kind === 214 /* NamespaceImport */) { // emit re-export for namespace // import * as n from 'foo' // export {n} @@ -29005,7 +30753,7 @@ var ts; } decreaseIndent(); break; - case 216 /* ExportDeclaration */: + case 218 /* ExportDeclaration */: ts.Debug.assert(importVariableName !== ""); increaseIndent(); if (importNode.exportClause) { @@ -29048,10 +30796,10 @@ var ts; // - imports/exports are not emitted for system modules // - function declarations are not emitted because they were already hoisted switch (statement.kind) { - case 216 /* ExportDeclaration */: - case 210 /* ImportDeclaration */: - case 209 /* ImportEqualsDeclaration */: - case 201 /* FunctionDeclaration */: + case 218 /* ExportDeclaration */: + case 212 /* ImportDeclaration */: + case 211 /* ImportEqualsDeclaration */: + case 203 /* FunctionDeclaration */: continue; } writeLine(); @@ -29074,7 +30822,11 @@ var ts; ts.Debug.assert(!exportFunctionForFile); // make sure that name of 'exports' function does not conflict with existing identifiers exportFunctionForFile = makeUniqueName("exports"); - write("System.register(["); + write("System.register("); + if (node.moduleName) { + write("\"" + node.moduleName + "\", "); + } + write("["); for (var i = 0; i < externalImports.length; ++i) { var text = getExternalModuleNameText(externalImports[i]); if (i !== 0) { @@ -29154,8 +30906,8 @@ var ts; collectExternalModuleInfo(node); writeLine(); write("define("); - if (node.amdModuleName) { - write("\"" + node.amdModuleName + "\", "); + if (node.moduleName) { + write("\"" + node.moduleName + "\", "); } emitAMDDependencies(node, true); write(") {"); @@ -29265,7 +31017,7 @@ var ts; paramEmitted = true; } } - if (ts.isExternalModule(node) || compilerOptions.separateCompilation) { + if (ts.isExternalModule(node) || compilerOptions.isolatedModules) { if (languageVersion >= 2 /* ES6 */) { emitES6Module(node, startIndex); } @@ -29293,7 +31045,7 @@ var ts; } emitLeadingComments(node.endOfFileToken); } - function emitNodeWithoutSourceMap(node, allowGeneratedIdentifiers) { + function emitNodeWithoutSourceMap(node) { if (!node) { return; } @@ -29304,7 +31056,7 @@ var ts; if (emitComments) { emitLeadingComments(node); } - emitJavaScriptWorker(node, allowGeneratedIdentifiers); + emitJavaScriptWorker(node); if (emitComments) { emitTrailingComments(node); } @@ -29313,18 +31065,20 @@ var ts; switch (node.kind) { // All of these entities are emitted in a specialized fashion. As such, we allow // the specialized methods for each to handle the comments on the nodes. - case 203 /* InterfaceDeclaration */: - case 201 /* FunctionDeclaration */: - case 210 /* ImportDeclaration */: - case 209 /* ImportEqualsDeclaration */: - case 204 /* TypeAliasDeclaration */: - case 215 /* ExportAssignment */: + case 205 /* InterfaceDeclaration */: + case 203 /* FunctionDeclaration */: + case 212 /* ImportDeclaration */: + case 211 /* ImportEqualsDeclaration */: + case 206 /* TypeAliasDeclaration */: + case 217 /* ExportAssignment */: return false; - case 206 /* ModuleDeclaration */: + case 183 /* VariableStatement */: + return shouldEmitLeadingAndTrailingCommentsForVariableStatement(node); + case 208 /* ModuleDeclaration */: // Only emit the leading/trailing comments for a module if we're actually // emitting the module as well. return shouldEmitModuleDeclaration(node); - case 205 /* EnumDeclaration */: + case 207 /* EnumDeclaration */: // Only emit the leading/trailing comments for an enum if we're actually // emitting the module as well. return shouldEmitEnumDeclaration(node); @@ -29333,9 +31087,9 @@ var ts; // then we don't want to emit comments when we emit the body. It will have already // been taken care of when we emitted the 'return' statement for the function // expression body. - if (node.kind !== 180 /* Block */ && + if (node.kind !== 182 /* Block */ && node.parent && - node.parent.kind === 164 /* ArrowFunction */ && + node.parent.kind === 166 /* ArrowFunction */ && node.parent.body === node && compilerOptions.target <= 1 /* ES5 */) { return false; @@ -29343,19 +31097,18 @@ var ts; // Emit comments for everything else. return true; } - function emitJavaScriptWorker(node, allowGeneratedIdentifiers) { - if (allowGeneratedIdentifiers === void 0) { allowGeneratedIdentifiers = true; } + function emitJavaScriptWorker(node) { // Check if the node can be emitted regardless of the ScriptTarget switch (node.kind) { case 65 /* Identifier */: - return emitIdentifier(node, allowGeneratedIdentifiers); - case 130 /* Parameter */: + return emitIdentifier(node); + case 131 /* Parameter */: return emitParameter(node); - case 135 /* MethodDeclaration */: - case 134 /* MethodSignature */: + case 136 /* MethodDeclaration */: + case 135 /* MethodSignature */: return emitMethod(node); - case 137 /* GetAccessor */: - case 138 /* SetAccessor */: + case 138 /* GetAccessor */: + case 139 /* SetAccessor */: return emitAccessor(node); case 93 /* ThisKeyword */: return emitThis(node); @@ -29375,131 +31128,131 @@ var ts; case 12 /* TemplateMiddle */: case 13 /* TemplateTail */: return emitLiteral(node); - case 172 /* TemplateExpression */: + case 174 /* TemplateExpression */: return emitTemplateExpression(node); - case 178 /* TemplateSpan */: + case 180 /* TemplateSpan */: return emitTemplateSpan(node); - case 127 /* QualifiedName */: + case 128 /* QualifiedName */: return emitQualifiedName(node); - case 151 /* ObjectBindingPattern */: + case 153 /* ObjectBindingPattern */: return emitObjectBindingPattern(node); - case 152 /* ArrayBindingPattern */: + case 154 /* ArrayBindingPattern */: return emitArrayBindingPattern(node); - case 153 /* BindingElement */: + case 155 /* BindingElement */: return emitBindingElement(node); - case 154 /* ArrayLiteralExpression */: + case 156 /* ArrayLiteralExpression */: return emitArrayLiteral(node); - case 155 /* ObjectLiteralExpression */: + case 157 /* ObjectLiteralExpression */: return emitObjectLiteral(node); - case 225 /* PropertyAssignment */: + case 227 /* PropertyAssignment */: return emitPropertyAssignment(node); - case 226 /* ShorthandPropertyAssignment */: + case 228 /* ShorthandPropertyAssignment */: return emitShorthandPropertyAssignment(node); - case 128 /* ComputedPropertyName */: + case 129 /* ComputedPropertyName */: return emitComputedPropertyName(node); - case 156 /* PropertyAccessExpression */: + case 158 /* PropertyAccessExpression */: return emitPropertyAccess(node); - case 157 /* ElementAccessExpression */: + case 159 /* ElementAccessExpression */: return emitIndexedAccess(node); - case 158 /* CallExpression */: + case 160 /* CallExpression */: return emitCallExpression(node); - case 159 /* NewExpression */: + case 161 /* NewExpression */: return emitNewExpression(node); - case 160 /* TaggedTemplateExpression */: + case 162 /* TaggedTemplateExpression */: return emitTaggedTemplateExpression(node); - case 161 /* TypeAssertionExpression */: + case 163 /* TypeAssertionExpression */: return emit(node.expression); - case 162 /* ParenthesizedExpression */: + case 164 /* ParenthesizedExpression */: return emitParenExpression(node); - case 201 /* FunctionDeclaration */: - case 163 /* FunctionExpression */: - case 164 /* ArrowFunction */: + case 203 /* FunctionDeclaration */: + case 165 /* FunctionExpression */: + case 166 /* ArrowFunction */: return emitFunctionDeclaration(node); - case 165 /* DeleteExpression */: + case 167 /* DeleteExpression */: return emitDeleteExpression(node); - case 166 /* TypeOfExpression */: + case 168 /* TypeOfExpression */: return emitTypeOfExpression(node); - case 167 /* VoidExpression */: + case 169 /* VoidExpression */: return emitVoidExpression(node); - case 168 /* PrefixUnaryExpression */: + case 170 /* PrefixUnaryExpression */: return emitPrefixUnaryExpression(node); - case 169 /* PostfixUnaryExpression */: + case 171 /* PostfixUnaryExpression */: return emitPostfixUnaryExpression(node); - case 170 /* BinaryExpression */: + case 172 /* BinaryExpression */: return emitBinaryExpression(node); - case 171 /* ConditionalExpression */: + case 173 /* ConditionalExpression */: return emitConditionalExpression(node); - case 174 /* SpreadElementExpression */: + case 176 /* SpreadElementExpression */: return emitSpreadElementExpression(node); - case 173 /* YieldExpression */: + case 175 /* YieldExpression */: return emitYieldExpression(node); - case 176 /* OmittedExpression */: + case 178 /* OmittedExpression */: return; - case 180 /* Block */: - case 207 /* ModuleBlock */: + case 182 /* Block */: + case 209 /* ModuleBlock */: return emitBlock(node); - case 181 /* VariableStatement */: + case 183 /* VariableStatement */: return emitVariableStatement(node); - case 182 /* EmptyStatement */: + case 184 /* EmptyStatement */: return write(";"); - case 183 /* ExpressionStatement */: + case 185 /* ExpressionStatement */: return emitExpressionStatement(node); - case 184 /* IfStatement */: + case 186 /* IfStatement */: return emitIfStatement(node); - case 185 /* DoStatement */: + case 187 /* DoStatement */: return emitDoStatement(node); - case 186 /* WhileStatement */: + case 188 /* WhileStatement */: return emitWhileStatement(node); - case 187 /* ForStatement */: + case 189 /* ForStatement */: return emitForStatement(node); - case 189 /* ForOfStatement */: - case 188 /* ForInStatement */: + case 191 /* ForOfStatement */: + case 190 /* ForInStatement */: return emitForInOrForOfStatement(node); - case 190 /* ContinueStatement */: - case 191 /* BreakStatement */: + case 192 /* ContinueStatement */: + case 193 /* BreakStatement */: return emitBreakOrContinueStatement(node); - case 192 /* ReturnStatement */: + case 194 /* ReturnStatement */: return emitReturnStatement(node); - case 193 /* WithStatement */: + case 195 /* WithStatement */: return emitWithStatement(node); - case 194 /* SwitchStatement */: + case 196 /* SwitchStatement */: return emitSwitchStatement(node); - case 221 /* CaseClause */: - case 222 /* DefaultClause */: + case 223 /* CaseClause */: + case 224 /* DefaultClause */: return emitCaseOrDefaultClause(node); - case 195 /* LabeledStatement */: + case 197 /* LabeledStatement */: return emitLabelledStatement(node); - case 196 /* ThrowStatement */: + case 198 /* ThrowStatement */: return emitThrowStatement(node); - case 197 /* TryStatement */: + case 199 /* TryStatement */: return emitTryStatement(node); - case 224 /* CatchClause */: + case 226 /* CatchClause */: return emitCatchClause(node); - case 198 /* DebuggerStatement */: + case 200 /* DebuggerStatement */: return emitDebuggerStatement(node); - case 199 /* VariableDeclaration */: + case 201 /* VariableDeclaration */: return emitVariableDeclaration(node); - case 175 /* ClassExpression */: + case 177 /* ClassExpression */: return emitClassExpression(node); - case 202 /* ClassDeclaration */: + case 204 /* ClassDeclaration */: return emitClassDeclaration(node); - case 203 /* InterfaceDeclaration */: + case 205 /* InterfaceDeclaration */: return emitInterfaceDeclaration(node); - case 205 /* EnumDeclaration */: + case 207 /* EnumDeclaration */: return emitEnumDeclaration(node); - case 227 /* EnumMember */: + case 229 /* EnumMember */: return emitEnumMember(node); - case 206 /* ModuleDeclaration */: + case 208 /* ModuleDeclaration */: return emitModuleDeclaration(node); - case 210 /* ImportDeclaration */: + case 212 /* ImportDeclaration */: return emitImportDeclaration(node); - case 209 /* ImportEqualsDeclaration */: + case 211 /* ImportEqualsDeclaration */: return emitImportEqualsDeclaration(node); - case 216 /* ExportDeclaration */: + case 218 /* ExportDeclaration */: return emitExportDeclaration(node); - case 215 /* ExportAssignment */: + case 217 /* ExportAssignment */: return emitExportAssignment(node); - case 228 /* SourceFile */: + case 230 /* SourceFile */: return emitSourceFileNode(node); } } @@ -29531,7 +31284,7 @@ var ts; function getLeadingCommentsToEmit(node) { // Emit the leading comments only if the parent's pos doesn't match because parent should take care of emitting these comments if (node.parent) { - if (node.parent.kind === 228 /* SourceFile */ || node.pos !== node.parent.pos) { + if (node.parent.kind === 230 /* SourceFile */ || node.pos !== node.parent.pos) { if (hasDetachedComments(node.pos)) { // get comments without detached comments return getLeadingCommentsWithoutDetachedComments(); @@ -29546,7 +31299,7 @@ var ts; function getTrailingCommentsToEmit(node) { // Emit the trailing comments only if the parent's pos doesn't match because parent should take care of emitting these comments if (node.parent) { - if (node.parent.kind === 228 /* SourceFile */ || node.end !== node.parent.end) { + if (node.parent.kind === 230 /* SourceFile */ || node.end !== node.parent.end) { return ts.getTrailingCommentRanges(currentSourceFile.text, node.end); } } @@ -29656,9 +31409,7 @@ var ts; /* @internal */ ts.ioReadTime = 0; /* @internal */ ts.ioWriteTime = 0; /** The version of the TypeScript compiler release */ - ts.version = "1.5.2"; - var carriageReturnLineFeed = "\r\n"; - var lineFeed = "\n"; + ts.version = "1.5.3"; function findConfigFile(searchPath) { var fileName = "tsconfig.json"; while (true) { @@ -29732,9 +31483,7 @@ var ts; } } } - var newLine = options.newLine === 0 /* CarriageReturnLineFeed */ ? carriageReturnLineFeed : - options.newLine === 1 /* LineFeed */ ? lineFeed : - ts.sys.newLine; + var newLine = ts.getNewLineCharacter(options); return { getSourceFile: getSourceFile, getDefaultLibFileName: function (options) { return ts.combinePaths(ts.getDirectoryPath(ts.normalizePath(ts.sys.getExecutingFilePath())), ts.getDefaultLibFileName(options)); }, @@ -29747,7 +31496,7 @@ var ts; } ts.createCompilerHost = createCompilerHost; function getPreEmitDiagnostics(program, sourceFile) { - var diagnostics = program.getSyntacticDiagnostics(sourceFile).concat(program.getGlobalDiagnostics()).concat(program.getSemanticDiagnostics(sourceFile)); + var diagnostics = program.getOptionsDiagnostics().concat(program.getSyntacticDiagnostics(sourceFile), program.getGlobalDiagnostics(), program.getSemanticDiagnostics(sourceFile)); if (program.getCompilerOptions().declaration) { diagnostics.concat(program.getDeclarationDiagnostics(sourceFile)); } @@ -29780,16 +31529,21 @@ var ts; function createProgram(rootNames, options, host) { var program; var files = []; - var filesByName = {}; var diagnostics = ts.createDiagnosticCollection(); - var seenNoDefaultLib = options.noLib; var commonSourceDirectory; var diagnosticsProducingTypeChecker; var noDiagnosticsTypeChecker; + var classifiableNames; + var skipDefaultLib = options.noLib; var start = new Date().getTime(); host = host || createCompilerHost(options); + var filesByName = ts.createFileMap(function (fileName) { return host.getCanonicalFileName(fileName); }); ts.forEach(rootNames, function (name) { return processRootFile(name, false); }); - if (!seenNoDefaultLib) { + // Do not process the default library if: + // - The '--noLib' flag is used. + // - A 'no-default-lib' reference comment is encountered in + // processing the root files. + if (!skipDefaultLib) { processRootFile(host.getDefaultLibFileName(options), true); } verifyCompilerOptions(); @@ -29799,10 +31553,12 @@ var ts; getSourceFiles: function () { return files; }, getCompilerOptions: function () { return options; }, getSyntacticDiagnostics: getSyntacticDiagnostics, + getOptionsDiagnostics: getOptionsDiagnostics, getGlobalDiagnostics: getGlobalDiagnostics, getSemanticDiagnostics: getSemanticDiagnostics, getDeclarationDiagnostics: getDeclarationDiagnostics, getTypeChecker: getTypeChecker, + getClassifiableNames: getClassifiableNames, getDiagnosticsProducingTypeChecker: getDiagnosticsProducingTypeChecker, getCommonSourceDirectory: function () { return commonSourceDirectory; }, emit: emit, @@ -29813,6 +31569,18 @@ var ts; getTypeCount: function () { return getDiagnosticsProducingTypeChecker().getTypeCount(); } }; return program; + function getClassifiableNames() { + if (!classifiableNames) { + // Initialize a checker so that all our files are bound. + getTypeChecker(); + classifiableNames = {}; + for (var _i = 0; _i < files.length; _i++) { + var sourceFile = files[_i]; + ts.copyMap(sourceFile.classifiableNames, classifiableNames); + } + } + return classifiableNames; + } function getEmitHost(writeFileCallback) { return { getCanonicalFileName: function (fileName) { return host.getCanonicalFileName(fileName); }, @@ -29852,8 +31620,7 @@ var ts; return emitResult; } function getSourceFile(fileName) { - fileName = host.getCanonicalFileName(ts.normalizeSlashes(fileName)); - return ts.hasProperty(filesByName, fileName) ? filesByName[fileName] : undefined; + return filesByName.get(fileName); } function getDiagnosticsHelper(sourceFile, getDiagnostics) { if (sourceFile) { @@ -29893,13 +31660,16 @@ var ts; return ts.getDeclarationDiagnostics(getEmitHost(writeFile), resolver, sourceFile); } } - function getGlobalDiagnostics() { - var typeChecker = getDiagnosticsProducingTypeChecker(); + function getOptionsDiagnostics() { var allDiagnostics = []; - ts.addRange(allDiagnostics, typeChecker.getGlobalDiagnostics()); ts.addRange(allDiagnostics, diagnostics.getGlobalDiagnostics()); return ts.sortAndDeduplicateDiagnostics(allDiagnostics); } + function getGlobalDiagnostics() { + var allDiagnostics = []; + ts.addRange(allDiagnostics, getDiagnosticsProducingTypeChecker().getGlobalDiagnostics()); + return ts.sortAndDeduplicateDiagnostics(allDiagnostics); + } function hasExtension(fileName) { return ts.getBaseFileName(fileName).indexOf(".") >= 0; } @@ -29931,14 +31701,17 @@ var ts; } } else { - if (options.allowNonTsExtensions && !findSourceFile(fileName, isDefaultLib, refFile, refPos, refEnd)) { - diagnostic = ts.Diagnostics.File_0_not_found; - diagnosticArgument = [fileName]; - } - else if (!ts.forEach(ts.supportedExtensions, function (extension) { return findSourceFile(fileName + extension, isDefaultLib, refFile, refPos, refEnd); })) { - diagnostic = ts.Diagnostics.File_0_not_found; - fileName += ".ts"; - diagnosticArgument = [fileName]; + var nonTsFile = options.allowNonTsExtensions && findSourceFile(fileName, isDefaultLib, refFile, refPos, refEnd); + if (!nonTsFile) { + if (options.allowNonTsExtensions) { + diagnostic = ts.Diagnostics.File_0_not_found; + diagnosticArgument = [fileName]; + } + else if (!ts.forEach(ts.supportedExtensions, function (extension) { return findSourceFile(fileName + extension, isDefaultLib, refFile, refPos, refEnd); })) { + diagnostic = ts.Diagnostics.File_0_not_found; + fileName += ".ts"; + diagnosticArgument = [fileName]; + } } } if (diagnostic) { @@ -29953,18 +31726,18 @@ var ts; // Get source file from normalized fileName function findSourceFile(fileName, isDefaultLib, refFile, refStart, refLength) { var canonicalName = host.getCanonicalFileName(ts.normalizeSlashes(fileName)); - if (ts.hasProperty(filesByName, canonicalName)) { + if (filesByName.contains(canonicalName)) { // We've already looked for this file, use cached result return getSourceFileFromCache(fileName, canonicalName, false); } else { var normalizedAbsolutePath = ts.getNormalizedAbsolutePath(fileName, host.getCurrentDirectory()); var canonicalAbsolutePath = host.getCanonicalFileName(normalizedAbsolutePath); - if (ts.hasProperty(filesByName, canonicalAbsolutePath)) { + if (filesByName.contains(canonicalAbsolutePath)) { return getSourceFileFromCache(normalizedAbsolutePath, canonicalAbsolutePath, true); } // We haven't looked for this file, do so now and cache result - var file = filesByName[canonicalName] = host.getSourceFile(fileName, options.target, function (hostErrorMessage) { + var file = host.getSourceFile(fileName, options.target, function (hostErrorMessage) { if (refFile) { diagnostics.add(ts.createFileDiagnostic(refFile, refStart, refLength, ts.Diagnostics.Cannot_read_file_0_Colon_1, fileName, hostErrorMessage)); } @@ -29972,16 +31745,18 @@ var ts; diagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0_Colon_1, fileName, hostErrorMessage)); } }); + filesByName.set(canonicalName, file); if (file) { - seenNoDefaultLib = seenNoDefaultLib || file.hasNoDefaultLib; + skipDefaultLib = skipDefaultLib || file.hasNoDefaultLib; // Set the source file for normalized absolute path - filesByName[canonicalAbsolutePath] = file; + filesByName.set(canonicalAbsolutePath, file); if (!options.noResolve) { var basePath = ts.getDirectoryPath(fileName); processReferencedFiles(file, basePath); processImportedModules(file, basePath); } if (isDefaultLib) { + file.isDefaultLib = true; files.unshift(file); } else { @@ -29991,7 +31766,7 @@ var ts; return file; } function getSourceFileFromCache(fileName, canonicalName, useAbsolutePath) { - var file = filesByName[canonicalName]; + var file = filesByName.get(canonicalName); if (file && host.useCaseSensitiveFileNames()) { var sourceFileName = useAbsolutePath ? ts.getNormalizedAbsolutePath(file.fileName, host.getCurrentDirectory()) : file.fileName; if (canonicalName !== sourceFileName) { @@ -30009,7 +31784,7 @@ var ts; } function processImportedModules(file, basePath) { ts.forEach(file.statements, function (node) { - if (node.kind === 210 /* ImportDeclaration */ || node.kind === 209 /* ImportEqualsDeclaration */ || node.kind === 216 /* ExportDeclaration */) { + if (node.kind === 212 /* ImportDeclaration */ || node.kind === 211 /* ImportEqualsDeclaration */ || node.kind === 218 /* ExportDeclaration */) { var moduleNameExpr = ts.getExternalModuleName(node); if (moduleNameExpr && moduleNameExpr.kind === 8 /* StringLiteral */) { var moduleNameText = moduleNameExpr.text; @@ -30030,7 +31805,7 @@ var ts; } } } - else if (node.kind === 206 /* ModuleDeclaration */ && node.name.kind === 8 /* StringLiteral */ && (node.flags & 2 /* Ambient */ || ts.isDeclarationFile(file))) { + else if (node.kind === 208 /* ModuleDeclaration */ && node.name.kind === 8 /* StringLiteral */ && (node.flags & 2 /* Ambient */ || ts.isDeclarationFile(file))) { // TypeScript 1.0 spec (April 2014): 12.1.6 // An AmbientExternalModuleDeclaration declares an external module. // This type of declaration is permitted only in the global module. @@ -30108,18 +31883,18 @@ var ts; return allFilesBelongToPath; } function verifyCompilerOptions() { - if (options.separateCompilation) { + if (options.isolatedModules) { if (options.sourceMap) { - diagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_sourceMap_cannot_be_specified_with_option_separateCompilation)); + diagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_sourceMap_cannot_be_specified_with_option_isolatedModules)); } if (options.declaration) { - diagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_declaration_cannot_be_specified_with_option_separateCompilation)); + diagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_declaration_cannot_be_specified_with_option_isolatedModules)); } if (options.noEmitOnError) { - diagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_noEmitOnError_cannot_be_specified_with_option_separateCompilation)); + diagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_noEmitOnError_cannot_be_specified_with_option_isolatedModules)); } if (options.out) { - diagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_out_cannot_be_specified_with_option_separateCompilation)); + diagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_out_cannot_be_specified_with_option_isolatedModules)); } } if (options.inlineSourceMap) { @@ -30150,14 +31925,14 @@ var ts; } var languageVersion = options.target || 0 /* ES3 */; var firstExternalModuleSourceFile = ts.forEach(files, function (f) { return ts.isExternalModule(f) ? f : undefined; }); - if (options.separateCompilation) { + if (options.isolatedModules) { if (!options.module && languageVersion < 2 /* ES6 */) { - diagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_separateCompilation_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES6_or_higher)); + diagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES6_or_higher)); } var firstNonExternalModuleSourceFile = ts.forEach(files, function (f) { return !ts.isExternalModule(f) && !ts.isDeclarationFile(f) ? f : undefined; }); if (firstNonExternalModuleSourceFile) { var span = ts.getErrorSpanForNode(firstNonExternalModuleSourceFile, firstNonExternalModuleSourceFile); - diagnostics.add(ts.createFileDiagnostic(firstNonExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_compile_namespaces_when_the_separateCompilation_flag_is_provided)); + diagnostics.add(ts.createFileDiagnostic(firstNonExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided)); } } else if (firstExternalModuleSourceFile && languageVersion < 2 /* ES6 */ && !options.module) { @@ -30198,6 +31973,10 @@ var ts; diagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_noEmit_cannot_be_specified_with_option_declaration)); } } + if (options.emitDecoratorMetadata && + !options.experimentalDecorators) { + diagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_experimentalDecorators_must_also_be_specified_when_option_emitDecoratorMetadata_is_specified)); + } } } ts.createProgram = createProgram; @@ -30307,9 +32086,14 @@ var ts; name: "noResolve", type: "boolean" }, + { + name: "skipDefaultLibCheck", + type: "boolean" + }, { name: "out", type: "string", + isFilePath: true, description: ts.Diagnostics.Concatenate_and_emit_output_to_single_file, paramType: ts.Diagnostics.FILE }, @@ -30346,7 +32130,7 @@ var ts; paramType: ts.Diagnostics.LOCATION }, { - name: "separateCompilation", + name: "isolatedModules", type: "boolean" }, { @@ -30392,10 +32176,16 @@ var ts; type: "boolean", description: ts.Diagnostics.Watch_input_files }, + { + name: "experimentalDecorators", + type: "boolean", + description: ts.Diagnostics.Enables_experimental_support_for_ES7_decorators + }, { name: "emitDecoratorMetadata", type: "boolean", - experimental: true + experimental: true, + description: ts.Diagnostics.Enables_experimental_support_for_emitting_type_metadata_for_decorators } ]; function parseCommandLine(commandLine) { @@ -30540,7 +32330,7 @@ var ts; var errors = []; return { options: getCompilerOptions(), - fileNames: getFiles(), + fileNames: getFileNames(), errors: errors }; function getCompilerOptions() { @@ -30584,23 +32374,24 @@ var ts; } return options; } - function getFiles() { - var files = []; + function getFileNames() { + var fileNames = []; if (ts.hasProperty(json, "files")) { if (json["files"] instanceof Array) { - var files = ts.map(json["files"], function (s) { return ts.combinePaths(basePath, s); }); + fileNames = ts.map(json["files"], function (s) { return ts.combinePaths(basePath, s); }); } } else { - var sysFiles = host.readDirectory(basePath, ".ts"); + var exclude = json["exclude"] instanceof Array ? ts.map(json["exclude"], ts.normalizeSlashes) : undefined; + var sysFiles = host.readDirectory(basePath, ".ts", exclude); for (var i = 0; i < sysFiles.length; i++) { var name = sysFiles[i]; if (!ts.fileExtensionIs(name, ".d.ts") || !ts.contains(sysFiles, name.substr(0, name.length - 5) + ".ts")) { - files.push(name); + fileNames.push(name); } } } - return files; + return fileNames; } } ts.parseConfigFile = parseConfigFile; @@ -30677,7 +32468,7 @@ var ts; } } function autoCollapse(node) { - return ts.isFunctionBlock(node) && node.parent.kind !== 164 /* ArrowFunction */; + return ts.isFunctionBlock(node) && node.parent.kind !== 166 /* ArrowFunction */; } var depth = 0; var maxDepth = 20; @@ -30689,30 +32480,30 @@ var ts; addOutliningForLeadingCommentsForNode(n); } switch (n.kind) { - case 180 /* Block */: + case 182 /* Block */: if (!ts.isFunctionBlock(n)) { - var parent_6 = n.parent; + var parent_8 = n.parent; var openBrace = ts.findChildOfKind(n, 14 /* OpenBraceToken */, sourceFile); var closeBrace = ts.findChildOfKind(n, 15 /* CloseBraceToken */, sourceFile); // Check if the block is standalone, or 'attached' to some parent statement. // If the latter, we want to collaps the block, but consider its hint span // to be the entire span of the parent. - if (parent_6.kind === 185 /* DoStatement */ || - parent_6.kind === 188 /* ForInStatement */ || - parent_6.kind === 189 /* ForOfStatement */ || - parent_6.kind === 187 /* ForStatement */ || - parent_6.kind === 184 /* IfStatement */ || - parent_6.kind === 186 /* WhileStatement */ || - parent_6.kind === 193 /* WithStatement */ || - parent_6.kind === 224 /* CatchClause */) { - addOutliningSpan(parent_6, openBrace, closeBrace, autoCollapse(n)); + if (parent_8.kind === 187 /* DoStatement */ || + parent_8.kind === 190 /* ForInStatement */ || + parent_8.kind === 191 /* ForOfStatement */ || + parent_8.kind === 189 /* ForStatement */ || + parent_8.kind === 186 /* IfStatement */ || + parent_8.kind === 188 /* WhileStatement */ || + parent_8.kind === 195 /* WithStatement */ || + parent_8.kind === 226 /* CatchClause */) { + addOutliningSpan(parent_8, openBrace, closeBrace, autoCollapse(n)); break; } - if (parent_6.kind === 197 /* TryStatement */) { + if (parent_8.kind === 199 /* TryStatement */) { // Could be the try-block, or the finally-block. - var tryStatement = parent_6; + var tryStatement = parent_8; if (tryStatement.tryBlock === n) { - addOutliningSpan(parent_6, openBrace, closeBrace, autoCollapse(n)); + addOutliningSpan(parent_8, openBrace, closeBrace, autoCollapse(n)); break; } else if (tryStatement.finallyBlock === n) { @@ -30735,23 +32526,23 @@ var ts; break; } // Fallthrough. - case 207 /* ModuleBlock */: { + case 209 /* ModuleBlock */: { var openBrace = ts.findChildOfKind(n, 14 /* OpenBraceToken */, sourceFile); var closeBrace = ts.findChildOfKind(n, 15 /* CloseBraceToken */, sourceFile); addOutliningSpan(n.parent, openBrace, closeBrace, autoCollapse(n)); break; } - case 202 /* ClassDeclaration */: - case 203 /* InterfaceDeclaration */: - case 205 /* EnumDeclaration */: - case 155 /* ObjectLiteralExpression */: - case 208 /* CaseBlock */: { + case 204 /* ClassDeclaration */: + case 205 /* InterfaceDeclaration */: + case 207 /* EnumDeclaration */: + case 157 /* ObjectLiteralExpression */: + case 210 /* CaseBlock */: { var openBrace = ts.findChildOfKind(n, 14 /* OpenBraceToken */, sourceFile); var closeBrace = ts.findChildOfKind(n, 15 /* CloseBraceToken */, sourceFile); addOutliningSpan(n, openBrace, closeBrace, autoCollapse(n)); break; } - case 154 /* ArrayLiteralExpression */: + case 156 /* ArrayLiteralExpression */: var openBracket = ts.findChildOfKind(n, 18 /* OpenBracketToken */, sourceFile); var closeBracket = ts.findChildOfKind(n, 19 /* CloseBracketToken */, sourceFile); addOutliningSpan(n, openBracket, closeBracket, autoCollapse(n)); @@ -30779,12 +32570,12 @@ var ts; ts.forEach(program.getSourceFiles(), function (sourceFile) { cancellationToken.throwIfCancellationRequested(); var nameToDeclarations = sourceFile.getNamedDeclarations(); - for (var name_23 in nameToDeclarations) { - var declarations = ts.getProperty(nameToDeclarations, name_23); + for (var name_24 in nameToDeclarations) { + var declarations = ts.getProperty(nameToDeclarations, name_24); if (declarations) { // First do a quick check to see if the name of the declaration matches the // last portion of the (possibly) dotted name they're searching for. - var matches = patternMatcher.getMatchesForLastSegmentOfPattern(name_23); + var matches = patternMatcher.getMatchesForLastSegmentOfPattern(name_24); if (!matches) { continue; } @@ -30797,14 +32588,14 @@ var ts; if (!containers) { return undefined; } - matches = patternMatcher.getMatches(containers, name_23); + matches = patternMatcher.getMatches(containers, name_24); if (!matches) { continue; } } var fileName = sourceFile.fileName; var matchKind = bestMatchKind(matches); - rawItems.push({ name: name_23, fileName: fileName, matchKind: matchKind, isCaseSensitive: allMatchesAreCaseSensitive(matches), declaration: declaration }); + rawItems.push({ name: name_24, fileName: fileName, matchKind: matchKind, isCaseSensitive: allMatchesAreCaseSensitive(matches), declaration: declaration }); } } } @@ -30842,7 +32633,7 @@ var ts; if (text !== undefined) { containers.unshift(text); } - else if (declaration.name.kind === 128 /* ComputedPropertyName */) { + else if (declaration.name.kind === 129 /* ComputedPropertyName */) { return tryAddComputedPropertyName(declaration.name.expression, containers, true); } else { @@ -30863,7 +32654,7 @@ var ts; } return true; } - if (expression.kind === 156 /* PropertyAccessExpression */) { + if (expression.kind === 158 /* PropertyAccessExpression */) { var propertyAccess = expression; if (includeLastPortion) { containers.unshift(propertyAccess.name.text); @@ -30876,7 +32667,7 @@ var ts; var containers = []; // First, if we started with a computed property name, then add all but the last // portion into the container array. - if (declaration.name.kind === 128 /* ComputedPropertyName */) { + if (declaration.name.kind === 129 /* ComputedPropertyName */) { if (!tryAddComputedPropertyName(declaration.name.expression, containers, false)) { return undefined; } @@ -30952,17 +32743,17 @@ var ts; var current = node.parent; while (current) { switch (current.kind) { - case 206 /* ModuleDeclaration */: + case 208 /* ModuleDeclaration */: // If we have a module declared as A.B.C, it is more "intuitive" // to say it only has a single layer of depth do { current = current.parent; - } while (current.kind === 206 /* ModuleDeclaration */); + } while (current.kind === 208 /* ModuleDeclaration */); // fall through - case 202 /* ClassDeclaration */: - case 205 /* EnumDeclaration */: - case 203 /* InterfaceDeclaration */: - case 201 /* FunctionDeclaration */: + case 204 /* ClassDeclaration */: + case 207 /* EnumDeclaration */: + case 205 /* InterfaceDeclaration */: + case 203 /* FunctionDeclaration */: indent++; } current = current.parent; @@ -30973,21 +32764,21 @@ var ts; var childNodes = []; function visit(node) { switch (node.kind) { - case 181 /* VariableStatement */: + case 183 /* VariableStatement */: ts.forEach(node.declarationList.declarations, visit); break; - case 151 /* ObjectBindingPattern */: - case 152 /* ArrayBindingPattern */: + case 153 /* ObjectBindingPattern */: + case 154 /* ArrayBindingPattern */: ts.forEach(node.elements, visit); break; - case 216 /* ExportDeclaration */: + case 218 /* ExportDeclaration */: // Handle named exports case e.g.: // export {a, b as B} from "mod"; if (node.exportClause) { ts.forEach(node.exportClause.elements, visit); } break; - case 210 /* ImportDeclaration */: + case 212 /* ImportDeclaration */: var importClause = node.importClause; if (importClause) { // Handle default import case e.g.: @@ -30999,7 +32790,7 @@ var ts; // import * as NS from "mod"; // import {a, b as B} from "mod"; if (importClause.namedBindings) { - if (importClause.namedBindings.kind === 212 /* NamespaceImport */) { + if (importClause.namedBindings.kind === 214 /* NamespaceImport */) { childNodes.push(importClause.namedBindings); } else { @@ -31008,21 +32799,21 @@ var ts; } } break; - case 153 /* BindingElement */: - case 199 /* VariableDeclaration */: + case 155 /* BindingElement */: + case 201 /* VariableDeclaration */: if (ts.isBindingPattern(node.name)) { visit(node.name); break; } // Fall through - case 202 /* ClassDeclaration */: - case 205 /* EnumDeclaration */: - case 203 /* InterfaceDeclaration */: - case 206 /* ModuleDeclaration */: - case 201 /* FunctionDeclaration */: - case 209 /* ImportEqualsDeclaration */: - case 214 /* ImportSpecifier */: - case 218 /* ExportSpecifier */: + case 204 /* ClassDeclaration */: + case 207 /* EnumDeclaration */: + case 205 /* InterfaceDeclaration */: + case 208 /* ModuleDeclaration */: + case 203 /* FunctionDeclaration */: + case 211 /* ImportEqualsDeclaration */: + case 216 /* ImportSpecifier */: + case 220 /* ExportSpecifier */: childNodes.push(node); break; } @@ -31070,17 +32861,17 @@ var ts; for (var _i = 0; _i < nodes.length; _i++) { var node = nodes[_i]; switch (node.kind) { - case 202 /* ClassDeclaration */: - case 205 /* EnumDeclaration */: - case 203 /* InterfaceDeclaration */: + case 204 /* ClassDeclaration */: + case 207 /* EnumDeclaration */: + case 205 /* InterfaceDeclaration */: topLevelNodes.push(node); break; - case 206 /* ModuleDeclaration */: + case 208 /* ModuleDeclaration */: var moduleDeclaration = node; topLevelNodes.push(node); addTopLevelNodes(getInnermostModule(moduleDeclaration).body.statements, topLevelNodes); break; - case 201 /* FunctionDeclaration */: + case 203 /* FunctionDeclaration */: var functionDeclaration = node; if (isTopLevelFunctionDeclaration(functionDeclaration)) { topLevelNodes.push(node); @@ -31091,12 +32882,12 @@ var ts; } } function isTopLevelFunctionDeclaration(functionDeclaration) { - if (functionDeclaration.kind === 201 /* FunctionDeclaration */) { + if (functionDeclaration.kind === 203 /* FunctionDeclaration */) { // A function declaration is 'top level' if it contains any function declarations // within it. - if (functionDeclaration.body && functionDeclaration.body.kind === 180 /* Block */) { + if (functionDeclaration.body && functionDeclaration.body.kind === 182 /* Block */) { // Proper function declarations can only have identifier names - if (ts.forEach(functionDeclaration.body.statements, function (s) { return s.kind === 201 /* FunctionDeclaration */ && !isEmpty(s.name.text); })) { + if (ts.forEach(functionDeclaration.body.statements, function (s) { return s.kind === 203 /* FunctionDeclaration */ && !isEmpty(s.name.text); })) { return true; } // Or if it is not parented by another function. i.e all functions @@ -31156,7 +32947,7 @@ var ts; } function createChildItem(node) { switch (node.kind) { - case 130 /* Parameter */: + case 131 /* Parameter */: if (ts.isBindingPattern(node.name)) { break; } @@ -31164,36 +32955,36 @@ var ts; return undefined; } return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.memberVariableElement); - case 135 /* MethodDeclaration */: - case 134 /* MethodSignature */: + case 136 /* MethodDeclaration */: + case 135 /* MethodSignature */: return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.memberFunctionElement); - case 137 /* GetAccessor */: + case 138 /* GetAccessor */: return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.memberGetAccessorElement); - case 138 /* SetAccessor */: + case 139 /* SetAccessor */: return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.memberSetAccessorElement); - case 141 /* IndexSignature */: + case 142 /* IndexSignature */: return createItem(node, "[]", ts.ScriptElementKind.indexSignatureElement); - case 227 /* EnumMember */: + case 229 /* EnumMember */: return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.memberVariableElement); - case 139 /* CallSignature */: + case 140 /* CallSignature */: return createItem(node, "()", ts.ScriptElementKind.callSignatureElement); - case 140 /* ConstructSignature */: + case 141 /* ConstructSignature */: return createItem(node, "new()", ts.ScriptElementKind.constructSignatureElement); - case 133 /* PropertyDeclaration */: - case 132 /* PropertySignature */: + case 134 /* PropertyDeclaration */: + case 133 /* PropertySignature */: return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.memberVariableElement); - case 201 /* FunctionDeclaration */: + case 203 /* FunctionDeclaration */: return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.functionElement); - case 199 /* VariableDeclaration */: - case 153 /* BindingElement */: + case 201 /* VariableDeclaration */: + case 155 /* BindingElement */: var variableDeclarationNode; - var name_24; - if (node.kind === 153 /* BindingElement */) { - name_24 = node.name; + var name_25; + if (node.kind === 155 /* BindingElement */) { + name_25 = node.name; variableDeclarationNode = node; // binding elements are added only for variable declarations // bubble up to the containing variable declaration - while (variableDeclarationNode && variableDeclarationNode.kind !== 199 /* VariableDeclaration */) { + while (variableDeclarationNode && variableDeclarationNode.kind !== 201 /* VariableDeclaration */) { variableDeclarationNode = variableDeclarationNode.parent; } ts.Debug.assert(variableDeclarationNode !== undefined); @@ -31201,24 +32992,24 @@ var ts; else { ts.Debug.assert(!ts.isBindingPattern(node.name)); variableDeclarationNode = node; - name_24 = node.name; + name_25 = node.name; } if (ts.isConst(variableDeclarationNode)) { - return createItem(node, getTextOfNode(name_24), ts.ScriptElementKind.constElement); + return createItem(node, getTextOfNode(name_25), ts.ScriptElementKind.constElement); } else if (ts.isLet(variableDeclarationNode)) { - return createItem(node, getTextOfNode(name_24), ts.ScriptElementKind.letElement); + return createItem(node, getTextOfNode(name_25), ts.ScriptElementKind.letElement); } else { - return createItem(node, getTextOfNode(name_24), ts.ScriptElementKind.variableElement); + return createItem(node, getTextOfNode(name_25), ts.ScriptElementKind.variableElement); } - case 136 /* Constructor */: + case 137 /* Constructor */: return createItem(node, "constructor", ts.ScriptElementKind.constructorImplementationElement); - case 218 /* ExportSpecifier */: - case 214 /* ImportSpecifier */: - case 209 /* ImportEqualsDeclaration */: - case 211 /* ImportClause */: - case 212 /* NamespaceImport */: + case 220 /* ExportSpecifier */: + case 216 /* ImportSpecifier */: + case 211 /* ImportEqualsDeclaration */: + case 213 /* ImportClause */: + case 214 /* NamespaceImport */: return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.alias); } return undefined; @@ -31248,17 +33039,17 @@ var ts; } function createTopLevelItem(node) { switch (node.kind) { - case 228 /* SourceFile */: + case 230 /* SourceFile */: return createSourceFileItem(node); - case 202 /* ClassDeclaration */: + case 204 /* ClassDeclaration */: return createClassItem(node); - case 205 /* EnumDeclaration */: + case 207 /* EnumDeclaration */: return createEnumItem(node); - case 203 /* InterfaceDeclaration */: + case 205 /* InterfaceDeclaration */: return createIterfaceItem(node); - case 206 /* ModuleDeclaration */: + case 208 /* ModuleDeclaration */: return createModuleItem(node); - case 201 /* FunctionDeclaration */: + case 203 /* FunctionDeclaration */: return createFunctionItem(node); } return undefined; @@ -31270,7 +33061,7 @@ var ts; // Otherwise, we need to aggregate each identifier to build up the qualified name. var result = []; result.push(moduleDeclaration.name.text); - while (moduleDeclaration.body && moduleDeclaration.body.kind === 206 /* ModuleDeclaration */) { + while (moduleDeclaration.body && moduleDeclaration.body.kind === 208 /* ModuleDeclaration */) { moduleDeclaration = moduleDeclaration.body; result.push(moduleDeclaration.name.text); } @@ -31282,7 +33073,7 @@ var ts; return getNavigationBarItem(moduleName, ts.ScriptElementKind.moduleElement, ts.getNodeModifiers(node), [getNodeSpan(node)], childItems, getIndent(node)); } function createFunctionItem(node) { - if (node.body && node.body.kind === 180 /* Block */) { + if (node.body && node.body.kind === 182 /* Block */) { var childItems = getItemsWorker(sortNodes(node.body.statements), createChildItem); return getNavigationBarItem(!node.name ? "default" : node.name.text, ts.ScriptElementKind.functionElement, ts.getNodeModifiers(node), [getNodeSpan(node)], childItems, getIndent(node)); } @@ -31303,7 +33094,7 @@ var ts; var childItems; if (node.members) { var constructor = ts.forEach(node.members, function (member) { - return member.kind === 136 /* Constructor */ && member; + return member.kind === 137 /* Constructor */ && member; }); // Add the constructor parameters in as children of the class (for property parameters). // Note that *all non-binding pattern named* parameters will be added to the nodes array, but parameters that @@ -31327,7 +33118,7 @@ var ts; } } function removeComputedProperties(node) { - return ts.filter(node.members, function (member) { return member.name === undefined || member.name.kind !== 128 /* ComputedPropertyName */; }); + return ts.filter(node.members, function (member) { return member.name === undefined || member.name.kind !== 129 /* ComputedPropertyName */; }); } /** * Like removeComputedProperties, but retains the properties with well known symbol names @@ -31336,13 +33127,13 @@ var ts; return ts.filter(node.members, function (member) { return !ts.hasDynamicName(member); }); } function getInnermostModule(node) { - while (node.body.kind === 206 /* ModuleDeclaration */) { + while (node.body.kind === 208 /* ModuleDeclaration */) { node = node.body; } return node; } function getNodeSpan(node) { - return node.kind === 228 /* SourceFile */ + return node.kind === 230 /* SourceFile */ ? ts.createTextSpanFromBounds(node.getFullStart(), node.getEnd()) : ts.createTextSpanFromBounds(node.getStart(), node.getEnd()); } @@ -31857,7 +33648,7 @@ var ts; var hasTransitionFromUpperToLower = transitionFromUpperToLower(identifier, word, i, wordStart); if (charIsPunctuation(identifier.charCodeAt(i - 1)) || charIsPunctuation(identifier.charCodeAt(i)) || - lastIsDigit != currentIsDigit || + lastIsDigit !== currentIsDigit || hasTransitionFromLowerToUpper || hasTransitionFromUpperToLower) { if (!isAllPunctuation(identifier, wordStart, i)) { @@ -31918,7 +33709,7 @@ var ts; // 3) HTMLDocument -> HTML, Document // // etc. - if (index != wordStart && + if (index !== wordStart && index + 1 < identifier.length) { var currentIsUpper = isUpperCaseLetter(identifier.charCodeAt(index)); var nextIsLower = isLowerCaseLetter(identifier.charCodeAt(index + 1)); @@ -32137,7 +33928,7 @@ var ts; } return createSignatureHelpItems(candidates, resolvedSignature, argumentInfo); function createJavaScriptSignatureHelpItems(argumentInfo) { - if (argumentInfo.invocation.kind !== 158 /* CallExpression */) { + if (argumentInfo.invocation.kind !== 160 /* CallExpression */) { return undefined; } // See if we can find some symbol with the call expression name that has call signatures. @@ -32145,7 +33936,7 @@ var ts; var expression = callExpression.expression; var name = expression.kind === 65 /* Identifier */ ? expression - : expression.kind === 156 /* PropertyAccessExpression */ + : expression.kind === 158 /* PropertyAccessExpression */ ? expression.name : undefined; if (!name || !name.text) { @@ -32178,7 +33969,7 @@ var ts; * in the argument of an invocation; returns undefined otherwise. */ function getImmediatelyContainingArgumentInfo(node) { - if (node.parent.kind === 158 /* CallExpression */ || node.parent.kind === 159 /* NewExpression */) { + if (node.parent.kind === 160 /* CallExpression */ || node.parent.kind === 161 /* NewExpression */) { var callExpression = node.parent; // There are 3 cases to handle: // 1. The token introduces a list, and should begin a sig help session @@ -32231,25 +34022,25 @@ var ts; }; } } - else if (node.kind === 10 /* NoSubstitutionTemplateLiteral */ && node.parent.kind === 160 /* TaggedTemplateExpression */) { + else if (node.kind === 10 /* NoSubstitutionTemplateLiteral */ && node.parent.kind === 162 /* TaggedTemplateExpression */) { // Check if we're actually inside the template; // otherwise we'll fall out and return undefined. if (ts.isInsideTemplateLiteral(node, position)) { return getArgumentListInfoForTemplate(node.parent, 0); } } - else if (node.kind === 11 /* TemplateHead */ && node.parent.parent.kind === 160 /* TaggedTemplateExpression */) { + else if (node.kind === 11 /* TemplateHead */ && node.parent.parent.kind === 162 /* TaggedTemplateExpression */) { var templateExpression = node.parent; var tagExpression = templateExpression.parent; - ts.Debug.assert(templateExpression.kind === 172 /* TemplateExpression */); + ts.Debug.assert(templateExpression.kind === 174 /* TemplateExpression */); var argumentIndex = ts.isInsideTemplateLiteral(node, position) ? 0 : 1; return getArgumentListInfoForTemplate(tagExpression, argumentIndex); } - else if (node.parent.kind === 178 /* TemplateSpan */ && node.parent.parent.parent.kind === 160 /* TaggedTemplateExpression */) { + else if (node.parent.kind === 180 /* TemplateSpan */ && node.parent.parent.parent.kind === 162 /* TaggedTemplateExpression */) { var templateSpan = node.parent; var templateExpression = templateSpan.parent; var tagExpression = templateExpression.parent; - ts.Debug.assert(templateExpression.kind === 172 /* TemplateExpression */); + ts.Debug.assert(templateExpression.kind === 174 /* TemplateExpression */); // If we're just after a template tail, don't show signature help. if (node.kind === 13 /* TemplateTail */ && !ts.isInsideTemplateLiteral(node, position)) { return undefined; @@ -32367,7 +34158,7 @@ var ts; // // This is because a Missing node has no width. However, what we actually want is to include trivia // leading up to the next token in case the user is about to type in a TemplateMiddle or TemplateTail. - if (template.kind === 172 /* TemplateExpression */) { + if (template.kind === 174 /* TemplateExpression */) { var lastSpan = ts.lastOrUndefined(template.templateSpans); if (lastSpan.literal.getFullWidth() === 0) { applicableSpanEnd = ts.skipTrivia(sourceFile.text, applicableSpanEnd, false); @@ -32376,7 +34167,7 @@ var ts; return ts.createTextSpan(applicableSpanStart, applicableSpanEnd - applicableSpanStart); } function getContainingArgumentInfo(node) { - for (var n = node; n.kind !== 228 /* SourceFile */; n = n.parent) { + for (var n = node; n.kind !== 230 /* SourceFile */; n = n.parent) { if (ts.isFunctionBlock(n)) { return undefined; } @@ -32577,40 +34368,40 @@ var ts; return false; } switch (n.kind) { - case 202 /* ClassDeclaration */: - case 203 /* InterfaceDeclaration */: - case 205 /* EnumDeclaration */: - case 155 /* ObjectLiteralExpression */: - case 151 /* ObjectBindingPattern */: - case 146 /* TypeLiteral */: - case 180 /* Block */: - case 207 /* ModuleBlock */: - case 208 /* CaseBlock */: + case 204 /* ClassDeclaration */: + case 205 /* InterfaceDeclaration */: + case 207 /* EnumDeclaration */: + case 157 /* ObjectLiteralExpression */: + case 153 /* ObjectBindingPattern */: + case 148 /* TypeLiteral */: + case 182 /* Block */: + case 209 /* ModuleBlock */: + case 210 /* CaseBlock */: return nodeEndsWith(n, 15 /* CloseBraceToken */, sourceFile); - case 224 /* CatchClause */: + case 226 /* CatchClause */: return isCompletedNode(n.block, sourceFile); - case 159 /* NewExpression */: + case 161 /* NewExpression */: if (!n.arguments) { return true; } // fall through - case 158 /* CallExpression */: - case 162 /* ParenthesizedExpression */: - case 150 /* ParenthesizedType */: + case 160 /* CallExpression */: + case 164 /* ParenthesizedExpression */: + case 152 /* ParenthesizedType */: return nodeEndsWith(n, 17 /* CloseParenToken */, sourceFile); - case 143 /* FunctionType */: - case 144 /* ConstructorType */: + case 145 /* FunctionType */: + case 146 /* ConstructorType */: return isCompletedNode(n.type, sourceFile); - case 136 /* Constructor */: - case 137 /* GetAccessor */: - case 138 /* SetAccessor */: - case 201 /* FunctionDeclaration */: - case 163 /* FunctionExpression */: - case 135 /* MethodDeclaration */: - case 134 /* MethodSignature */: - case 140 /* ConstructSignature */: - case 139 /* CallSignature */: - case 164 /* ArrowFunction */: + case 137 /* Constructor */: + case 138 /* GetAccessor */: + case 139 /* SetAccessor */: + case 203 /* FunctionDeclaration */: + case 165 /* FunctionExpression */: + case 136 /* MethodDeclaration */: + case 135 /* MethodSignature */: + case 141 /* ConstructSignature */: + case 140 /* CallSignature */: + case 166 /* ArrowFunction */: if (n.body) { return isCompletedNode(n.body, sourceFile); } @@ -32620,63 +34411,63 @@ var ts; // Even though type parameters can be unclosed, we can get away with // having at least a closing paren. return hasChildOfKind(n, 17 /* CloseParenToken */, sourceFile); - case 206 /* ModuleDeclaration */: + case 208 /* ModuleDeclaration */: return n.body && isCompletedNode(n.body, sourceFile); - case 184 /* IfStatement */: + case 186 /* IfStatement */: if (n.elseStatement) { return isCompletedNode(n.elseStatement, sourceFile); } return isCompletedNode(n.thenStatement, sourceFile); - case 183 /* ExpressionStatement */: + case 185 /* ExpressionStatement */: return isCompletedNode(n.expression, sourceFile); - case 154 /* ArrayLiteralExpression */: - case 152 /* ArrayBindingPattern */: - case 157 /* ElementAccessExpression */: - case 128 /* ComputedPropertyName */: - case 148 /* TupleType */: + case 156 /* ArrayLiteralExpression */: + case 154 /* ArrayBindingPattern */: + case 159 /* ElementAccessExpression */: + case 129 /* ComputedPropertyName */: + case 150 /* TupleType */: return nodeEndsWith(n, 19 /* CloseBracketToken */, sourceFile); - case 141 /* IndexSignature */: + case 142 /* IndexSignature */: if (n.type) { return isCompletedNode(n.type, sourceFile); } return hasChildOfKind(n, 19 /* CloseBracketToken */, sourceFile); - case 221 /* CaseClause */: - case 222 /* DefaultClause */: + case 223 /* CaseClause */: + case 224 /* DefaultClause */: // there is no such thing as terminator token for CaseClause/DefaultClause so for simplicitly always consider them non-completed return false; - case 187 /* ForStatement */: - case 188 /* ForInStatement */: - case 189 /* ForOfStatement */: - case 186 /* WhileStatement */: + case 189 /* ForStatement */: + case 190 /* ForInStatement */: + case 191 /* ForOfStatement */: + case 188 /* WhileStatement */: return isCompletedNode(n.statement, sourceFile); - case 185 /* DoStatement */: + case 187 /* DoStatement */: // rough approximation: if DoStatement has While keyword - then if node is completed is checking the presence of ')'; var hasWhileKeyword = findChildOfKind(n, 100 /* WhileKeyword */, sourceFile); if (hasWhileKeyword) { return nodeEndsWith(n, 17 /* CloseParenToken */, sourceFile); } return isCompletedNode(n.statement, sourceFile); - case 145 /* TypeQuery */: + case 147 /* TypeQuery */: return isCompletedNode(n.exprName, sourceFile); - case 166 /* TypeOfExpression */: - case 165 /* DeleteExpression */: - case 167 /* VoidExpression */: - case 173 /* YieldExpression */: - case 174 /* SpreadElementExpression */: + case 168 /* TypeOfExpression */: + case 167 /* DeleteExpression */: + case 169 /* VoidExpression */: + case 175 /* YieldExpression */: + case 176 /* SpreadElementExpression */: var unaryWordExpression = n; return isCompletedNode(unaryWordExpression.expression, sourceFile); - case 160 /* TaggedTemplateExpression */: + case 162 /* TaggedTemplateExpression */: return isCompletedNode(n.template, sourceFile); - case 172 /* TemplateExpression */: + case 174 /* TemplateExpression */: var lastSpan = ts.lastOrUndefined(n.templateSpans); return isCompletedNode(lastSpan, sourceFile); - case 178 /* TemplateSpan */: + case 180 /* TemplateSpan */: return ts.nodeIsPresent(n.literal); - case 168 /* PrefixUnaryExpression */: + case 170 /* PrefixUnaryExpression */: return isCompletedNode(n.operand, sourceFile); - case 170 /* BinaryExpression */: + case 172 /* BinaryExpression */: return isCompletedNode(n.right, sourceFile); - case 171 /* ConditionalExpression */: + case 173 /* ConditionalExpression */: return isCompletedNode(n.whenFalse, sourceFile); default: return true; @@ -32732,7 +34523,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 === 229 /* SyntaxList */ && c.pos <= node.pos && c.end >= node.end) { + if (c.kind === 253 /* SyntaxList */ && c.pos <= node.pos && c.end >= node.end) { return c; } }); @@ -32866,7 +34657,7 @@ var ts; } } } - ts.Debug.assert(startNode !== undefined || n.kind === 228 /* SourceFile */); + ts.Debug.assert(startNode !== undefined || n.kind === 230 /* SourceFile */); // 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. @@ -32910,17 +34701,17 @@ var ts; } ts.getNodeModifiers = getNodeModifiers; function getTypeArgumentOrTypeParameterList(node) { - if (node.kind === 142 /* TypeReference */ || node.kind === 158 /* CallExpression */) { + if (node.kind === 144 /* TypeReference */ || node.kind === 160 /* CallExpression */) { return node.typeArguments; } - if (ts.isFunctionLike(node) || node.kind === 202 /* ClassDeclaration */ || node.kind === 203 /* InterfaceDeclaration */) { + if (ts.isFunctionLike(node) || node.kind === 204 /* ClassDeclaration */ || node.kind === 205 /* InterfaceDeclaration */) { return node.typeParameters; } return undefined; } ts.getTypeArgumentOrTypeParameterList = getTypeArgumentOrTypeParameterList; function isToken(n) { - return n.kind >= 0 /* FirstToken */ && n.kind <= 126 /* LastToken */; + return n.kind >= 0 /* FirstToken */ && n.kind <= 127 /* LastToken */; } ts.isToken = isToken; function isWord(kind) { @@ -32975,7 +34766,7 @@ var ts; var ts; (function (ts) { function isFirstDeclarationOfSymbolParameter(symbol) { - return symbol.declarations && symbol.declarations.length > 0 && symbol.declarations[0].kind === 130 /* Parameter */; + return symbol.declarations && symbol.declarations.length > 0 && symbol.declarations[0].kind === 131 /* Parameter */; } ts.isFirstDeclarationOfSymbolParameter = isFirstDeclarationOfSymbolParameter; var displayPartWriter = getDisplayPartWriter(); @@ -33139,10 +34930,6 @@ var ts; }); } ts.signatureToDisplayParts = signatureToDisplayParts; - function isJavaScript(fileName) { - return ts.fileExtensionIs(fileName, ".js"); - } - ts.isJavaScript = isJavaScript; })(ts || (ts = {})); /// /// @@ -33392,7 +35179,7 @@ var ts; if (this.tokensAreOnSameLine === undefined) { var startLine = this.sourceFile.getLineAndCharacterOfPosition(this.currentTokenSpan.pos).line; var endLine = this.sourceFile.getLineAndCharacterOfPosition(this.nextTokenSpan.pos).line; - this.tokensAreOnSameLine = (startLine == endLine); + this.tokensAreOnSameLine = (startLine === endLine); } return this.tokensAreOnSameLine; }; @@ -33411,7 +35198,7 @@ var ts; FormattingContext.prototype.NodeIsOnOneLine = function (node) { var startLine = this.sourceFile.getLineAndCharacterOfPosition(node.getStart(this.sourceFile)).line; var endLine = this.sourceFile.getLineAndCharacterOfPosition(node.getEnd()).line; - return startLine == endLine; + return startLine === endLine; }; FormattingContext.prototype.BlockIsOnOneLine = function (node) { var openBrace = ts.findChildOfKind(node, 14 /* OpenBraceToken */, this.sourceFile); @@ -33571,7 +35358,7 @@ var ts; this.customContextChecks = funcs; } RuleOperationContext.prototype.IsAny = function () { - return this == RuleOperationContext.Any; + return this === RuleOperationContext.Any; }; RuleOperationContext.prototype.InContext = function (context) { if (this.IsAny()) { @@ -33625,7 +35412,7 @@ var ts; this.NoSpaceBeforeOpenBracket = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 18 /* OpenBracketToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8 /* Delete */)); this.NoSpaceAfterOpenBracket = new formatting.Rule(formatting.RuleDescriptor.create3(18 /* OpenBracketToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8 /* Delete */)); this.NoSpaceBeforeCloseBracket = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 19 /* CloseBracketToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8 /* Delete */)); - this.NoSpaceAfterCloseBracket = new formatting.Rule(formatting.RuleDescriptor.create3(19 /* CloseBracketToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8 /* Delete */)); + this.NoSpaceAfterCloseBracket = new formatting.Rule(formatting.RuleDescriptor.create3(19 /* CloseBracketToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, 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, 14 /* OpenBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext, Rules.IsBeforeBlockContext, Rules.IsNotFormatOnEnter, Rules.IsSameLineTokenOrBeforeMultilineBlockContext), 2 /* Space */), 1 /* CanDeleteNewLines */); @@ -33677,7 +35464,7 @@ var ts; this.SpaceAfterTryFinally = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.FromTokens([96 /* TryKeyword */, 81 /* FinallyKeyword */]), 14 /* OpenBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 2 /* Space */)); // get x() {} // set x(val) {} - this.SpaceAfterGetSetInMember = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.FromTokens([116 /* GetKeyword */, 121 /* SetKeyword */]), 65 /* Identifier */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext), 2 /* Space */)); + this.SpaceAfterGetSetInMember = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.FromTokens([116 /* GetKeyword */, 122 /* SetKeyword */]), 65 /* Identifier */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext), 2 /* Space */)); // Special case for binary operators (that are keywords). For these we have to add a space and shouldn't follow any user options. this.SpaceBeforeBinaryKeywordOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.BinaryKeywordOperators), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsBinaryOpContext), 2 /* Space */)); this.SpaceAfterBinaryKeywordOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.BinaryKeywordOperators, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsBinaryOpContext), 2 /* Space */)); @@ -33685,9 +35472,9 @@ var ts; // Treat constructor as an identifier in a function declaration, and remove spaces between constructor and following left parentheses this.NoSpaceAfterConstructor = new formatting.Rule(formatting.RuleDescriptor.create1(114 /* ConstructorKeyword */, 16 /* OpenParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8 /* Delete */)); // Use of module as a function call. e.g.: import m2 = module("m2"); - this.NoSpaceAfterModuleImport = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.FromTokens([117 /* ModuleKeyword */, 119 /* RequireKeyword */]), 16 /* OpenParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8 /* Delete */)); + this.NoSpaceAfterModuleImport = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.FromTokens([118 /* ModuleKeyword */, 120 /* RequireKeyword */]), 16 /* OpenParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8 /* Delete */)); // Add a space around certain TypeScript keywords - this.SpaceAfterCertainTypeScriptKeywords = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([69 /* ClassKeyword */, 115 /* DeclareKeyword */, 77 /* EnumKeyword */, 78 /* ExportKeyword */, 79 /* ExtendsKeyword */, 116 /* GetKeyword */, 102 /* ImplementsKeyword */, 85 /* ImportKeyword */, 103 /* InterfaceKeyword */, 117 /* ModuleKeyword */, 118 /* NamespaceKeyword */, 106 /* PrivateKeyword */, 108 /* PublicKeyword */, 121 /* SetKeyword */, 109 /* StaticKeyword */]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 2 /* Space */)); + this.SpaceAfterCertainTypeScriptKeywords = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([69 /* ClassKeyword */, 115 /* DeclareKeyword */, 77 /* EnumKeyword */, 78 /* ExportKeyword */, 79 /* ExtendsKeyword */, 116 /* GetKeyword */, 102 /* ImplementsKeyword */, 85 /* ImportKeyword */, 103 /* InterfaceKeyword */, 118 /* ModuleKeyword */, 119 /* NamespaceKeyword */, 106 /* PrivateKeyword */, 108 /* PublicKeyword */, 122 /* SetKeyword */, 109 /* StaticKeyword */]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 2 /* Space */)); this.SpaceBeforeCertainTypeScriptKeywords = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.FromTokens([79 /* ExtendsKeyword */, 102 /* ImplementsKeyword */])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 2 /* Space */)); // Treat string literals in module names as identifiers, and add a space between the literal and the opening Brace braces, e.g.: module "m2" { this.SpaceAfterModuleName = new formatting.Rule(formatting.RuleDescriptor.create1(8 /* StringLiteral */, 14 /* OpenBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsModuleDeclContext), 2 /* Space */)); @@ -33707,7 +35494,11 @@ var ts; // decorators this.SpaceBeforeAt = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 52 /* AtToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 2 /* Space */)); this.NoSpaceAfterAt = new formatting.Rule(formatting.RuleDescriptor.create3(52 /* AtToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8 /* Delete */)); - this.SpaceAfterDecorator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.FromTokens([65 /* Identifier */, 78 /* ExportKeyword */, 73 /* DefaultKeyword */, 69 /* ClassKeyword */, 109 /* StaticKeyword */, 108 /* PublicKeyword */, 106 /* PrivateKeyword */, 107 /* ProtectedKeyword */, 116 /* GetKeyword */, 121 /* SetKeyword */, 18 /* OpenBracketToken */, 35 /* AsteriskToken */])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsEndOfDecoratorContextOnSameLine), 2 /* Space */)); + this.SpaceAfterDecorator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.FromTokens([65 /* Identifier */, 78 /* ExportKeyword */, 73 /* DefaultKeyword */, 69 /* ClassKeyword */, 109 /* StaticKeyword */, 108 /* PublicKeyword */, 106 /* PrivateKeyword */, 107 /* ProtectedKeyword */, 116 /* GetKeyword */, 122 /* SetKeyword */, 18 /* OpenBracketToken */, 35 /* AsteriskToken */])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsEndOfDecoratorContextOnSameLine), 2 /* Space */)); + this.NoSpaceBetweenFunctionKeywordAndStar = new formatting.Rule(formatting.RuleDescriptor.create1(83 /* FunctionKeyword */, 35 /* AsteriskToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclarationOrFunctionExpressionContext), 8 /* Delete */)); + this.SpaceAfterStarInGeneratorDeclaration = new formatting.Rule(formatting.RuleDescriptor.create3(35 /* AsteriskToken */, formatting.Shared.TokenRange.FromTokens([65 /* Identifier */, 16 /* OpenParenToken */])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclarationOrFunctionExpressionContext), 2 /* Space */)); + this.NoSpaceBetweenYieldKeywordAndStar = new formatting.Rule(formatting.RuleDescriptor.create1(110 /* YieldKeyword */, 35 /* AsteriskToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsYieldOrYieldStarWithOperand), 8 /* Delete */)); + this.SpaceBetweenYieldOrYieldStarAndOperand = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([110 /* YieldKeyword */, 35 /* AsteriskToken */]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsYieldOrYieldStarWithOperand), 2 /* Space */)); // These rules are higher in priority than user-configurable rules. this.HighPriorityCommonRules = [ @@ -33725,7 +35516,9 @@ var ts; this.NoSpaceAfterCloseBrace, this.SpaceAfterOpenBrace, this.SpaceBeforeCloseBrace, this.NewLineBeforeCloseBraceInBlockContext, this.SpaceAfterCloseBrace, this.SpaceBetweenCloseBraceAndElse, this.SpaceBetweenCloseBraceAndWhile, this.NoSpaceBetweenEmptyBraceBrackets, + this.NoSpaceBetweenFunctionKeywordAndStar, this.SpaceAfterStarInGeneratorDeclaration, this.SpaceAfterFunctionInFuncDecl, this.NewLineAfterOpenBraceInBlockContext, this.SpaceAfterGetSetInMember, + this.NoSpaceBetweenYieldKeywordAndStar, this.SpaceBetweenYieldOrYieldStarAndOperand, this.NoSpaceBetweenReturnAndSemicolon, this.SpaceAfterCertainKeywords, this.SpaceAfterLetConstInVariableDeclaration, @@ -33797,9 +35590,9 @@ var ts; } Rules.prototype.getRuleName = function (rule) { var o = this; - for (var name_25 in o) { - if (o[name_25] === rule) { - return name_25; + for (var name_26 in o) { + if (o[name_26] === rule) { + return name_26; } } throw new Error("Unknown rule"); @@ -33808,36 +35601,37 @@ var ts; /// Contexts /// Rules.IsForContext = function (context) { - return context.contextNode.kind === 187 /* ForStatement */; + return context.contextNode.kind === 189 /* ForStatement */; }; Rules.IsNotForContext = function (context) { return !Rules.IsForContext(context); }; Rules.IsBinaryOpContext = function (context) { switch (context.contextNode.kind) { - case 170 /* BinaryExpression */: - case 171 /* ConditionalExpression */: + case 172 /* BinaryExpression */: + case 173 /* ConditionalExpression */: + case 143 /* TypePredicate */: return true; // equals in binding elements: function foo([[x, y] = [1, 2]]) - case 153 /* BindingElement */: + case 155 /* BindingElement */: // equals in type X = ... - case 204 /* TypeAliasDeclaration */: + case 206 /* TypeAliasDeclaration */: // equal in import a = module('a'); - case 209 /* ImportEqualsDeclaration */: + case 211 /* ImportEqualsDeclaration */: // equal in let a = 0; - case 199 /* VariableDeclaration */: + case 201 /* VariableDeclaration */: // equal in p = 0; - case 130 /* Parameter */: - case 227 /* EnumMember */: - case 133 /* PropertyDeclaration */: - case 132 /* PropertySignature */: + case 131 /* Parameter */: + case 229 /* EnumMember */: + case 134 /* PropertyDeclaration */: + case 133 /* PropertySignature */: return context.currentTokenSpan.kind === 53 /* EqualsToken */ || context.nextTokenSpan.kind === 53 /* EqualsToken */; // "in" keyword in for (let x in []) { } - case 188 /* ForInStatement */: + case 190 /* ForInStatement */: return context.currentTokenSpan.kind === 86 /* InKeyword */ || context.nextTokenSpan.kind === 86 /* InKeyword */; // Technically, "of" is not a binary operator, but format it the same way as "in" - case 189 /* ForOfStatement */: - return context.currentTokenSpan.kind === 126 /* OfKeyword */ || context.nextTokenSpan.kind === 126 /* OfKeyword */; + case 191 /* ForOfStatement */: + return context.currentTokenSpan.kind === 127 /* OfKeyword */ || context.nextTokenSpan.kind === 127 /* OfKeyword */; } return false; }; @@ -33845,7 +35639,7 @@ var ts; return !Rules.IsBinaryOpContext(context); }; Rules.IsConditionalOperatorContext = function (context) { - return context.contextNode.kind === 171 /* ConditionalExpression */; + return context.contextNode.kind === 173 /* ConditionalExpression */; }; Rules.IsSameLineTokenOrBeforeMultilineBlockContext = function (context) { //// This check is mainly used inside SpaceBeforeOpenBraceInControl and SpaceBeforeOpenBraceInFunction. @@ -33889,89 +35683,92 @@ var ts; return true; } switch (node.kind) { - case 180 /* Block */: - case 208 /* CaseBlock */: - case 155 /* ObjectLiteralExpression */: - case 207 /* ModuleBlock */: + case 182 /* Block */: + case 210 /* CaseBlock */: + case 157 /* ObjectLiteralExpression */: + case 209 /* ModuleBlock */: return true; } return false; }; Rules.IsFunctionDeclContext = function (context) { switch (context.contextNode.kind) { - case 201 /* FunctionDeclaration */: - case 135 /* MethodDeclaration */: - case 134 /* MethodSignature */: + case 203 /* FunctionDeclaration */: + case 136 /* MethodDeclaration */: + case 135 /* MethodSignature */: //case SyntaxKind.MemberFunctionDeclaration: - case 137 /* GetAccessor */: - case 138 /* SetAccessor */: + case 138 /* GetAccessor */: + case 139 /* SetAccessor */: ///case SyntaxKind.MethodSignature: - case 139 /* CallSignature */: - case 163 /* FunctionExpression */: - case 136 /* Constructor */: - case 164 /* ArrowFunction */: + case 140 /* CallSignature */: + case 165 /* FunctionExpression */: + case 137 /* Constructor */: + case 166 /* ArrowFunction */: //case SyntaxKind.ConstructorDeclaration: //case SyntaxKind.SimpleArrowFunctionExpression: //case SyntaxKind.ParenthesizedArrowFunctionExpression: - case 203 /* InterfaceDeclaration */: + case 205 /* InterfaceDeclaration */: return true; } return false; }; + Rules.IsFunctionDeclarationOrFunctionExpressionContext = function (context) { + return context.contextNode.kind === 203 /* FunctionDeclaration */ || context.contextNode.kind === 165 /* FunctionExpression */; + }; Rules.IsTypeScriptDeclWithBlockContext = function (context) { return Rules.NodeIsTypeScriptDeclWithBlockContext(context.contextNode); }; Rules.NodeIsTypeScriptDeclWithBlockContext = function (node) { switch (node.kind) { - case 202 /* ClassDeclaration */: - case 203 /* InterfaceDeclaration */: - case 205 /* EnumDeclaration */: - case 146 /* TypeLiteral */: - case 206 /* ModuleDeclaration */: + case 204 /* ClassDeclaration */: + case 205 /* InterfaceDeclaration */: + case 207 /* EnumDeclaration */: + case 148 /* TypeLiteral */: + case 208 /* ModuleDeclaration */: return true; } return false; }; Rules.IsAfterCodeBlockContext = function (context) { switch (context.currentTokenParent.kind) { - case 202 /* ClassDeclaration */: - case 206 /* ModuleDeclaration */: - case 205 /* EnumDeclaration */: - case 180 /* Block */: - case 224 /* CatchClause */: - case 207 /* ModuleBlock */: - case 194 /* SwitchStatement */: + case 204 /* ClassDeclaration */: + case 208 /* ModuleDeclaration */: + case 207 /* EnumDeclaration */: + case 182 /* Block */: + case 226 /* CatchClause */: + case 209 /* ModuleBlock */: + case 196 /* SwitchStatement */: return true; } return false; }; Rules.IsControlDeclContext = function (context) { switch (context.contextNode.kind) { - case 184 /* IfStatement */: - case 194 /* SwitchStatement */: - case 187 /* ForStatement */: - case 188 /* ForInStatement */: - case 189 /* ForOfStatement */: - case 186 /* WhileStatement */: - case 197 /* TryStatement */: - case 185 /* DoStatement */: - case 193 /* WithStatement */: + case 186 /* IfStatement */: + case 196 /* SwitchStatement */: + case 189 /* ForStatement */: + case 190 /* ForInStatement */: + case 191 /* ForOfStatement */: + case 188 /* WhileStatement */: + case 199 /* TryStatement */: + case 187 /* DoStatement */: + case 195 /* WithStatement */: // TODO // case SyntaxKind.ElseClause: - case 224 /* CatchClause */: + case 226 /* CatchClause */: return true; default: return false; } }; Rules.IsObjectContext = function (context) { - return context.contextNode.kind === 155 /* ObjectLiteralExpression */; + return context.contextNode.kind === 157 /* ObjectLiteralExpression */; }; Rules.IsFunctionCallContext = function (context) { - return context.contextNode.kind === 158 /* CallExpression */; + return context.contextNode.kind === 160 /* CallExpression */; }; Rules.IsNewContext = function (context) { - return context.contextNode.kind === 159 /* NewExpression */; + return context.contextNode.kind === 161 /* NewExpression */; }; Rules.IsFunctionCallOrNewContext = function (context) { return Rules.IsFunctionCallContext(context) || Rules.IsNewContext(context); @@ -33982,6 +35779,9 @@ var ts; Rules.IsSameLineTokenContext = function (context) { return context.TokensAreOnSameLine(); }; + Rules.IsNotBeforeBlockInFunctionDeclarationContext = function (context) { + return !Rules.IsFunctionDeclContext(context) && !Rules.IsBeforeBlockContext(context); + }; Rules.IsEndOfDecoratorContextOnSameLine = function (context) { return context.TokensAreOnSameLine() && context.contextNode.decorators && @@ -33992,38 +35792,38 @@ var ts; while (ts.isExpression(node)) { node = node.parent; } - return node.kind === 131 /* Decorator */; + return node.kind === 132 /* Decorator */; }; Rules.IsStartOfVariableDeclarationList = function (context) { - return context.currentTokenParent.kind === 200 /* VariableDeclarationList */ && + return context.currentTokenParent.kind === 202 /* VariableDeclarationList */ && context.currentTokenParent.getStart(context.sourceFile) === context.currentTokenSpan.pos; }; Rules.IsNotFormatOnEnter = function (context) { - return context.formattingRequestKind != 2 /* FormatOnEnter */; + return context.formattingRequestKind !== 2 /* FormatOnEnter */; }; Rules.IsModuleDeclContext = function (context) { - return context.contextNode.kind === 206 /* ModuleDeclaration */; + return context.contextNode.kind === 208 /* ModuleDeclaration */; }; Rules.IsObjectTypeContext = function (context) { - return context.contextNode.kind === 146 /* TypeLiteral */; // && context.contextNode.parent.kind !== SyntaxKind.InterfaceDeclaration; + return context.contextNode.kind === 148 /* TypeLiteral */; // && context.contextNode.parent.kind !== SyntaxKind.InterfaceDeclaration; }; Rules.IsTypeArgumentOrParameter = function (token, parent) { if (token.kind !== 24 /* LessThanToken */ && token.kind !== 25 /* GreaterThanToken */) { return false; } switch (parent.kind) { - case 142 /* TypeReference */: - case 202 /* ClassDeclaration */: - case 203 /* InterfaceDeclaration */: - case 201 /* FunctionDeclaration */: - case 163 /* FunctionExpression */: - case 164 /* ArrowFunction */: - case 135 /* MethodDeclaration */: - case 134 /* MethodSignature */: - case 139 /* CallSignature */: - case 140 /* ConstructSignature */: - case 158 /* CallExpression */: - case 159 /* NewExpression */: + case 144 /* TypeReference */: + case 204 /* ClassDeclaration */: + case 205 /* InterfaceDeclaration */: + case 203 /* FunctionDeclaration */: + case 165 /* FunctionExpression */: + case 166 /* ArrowFunction */: + case 136 /* MethodDeclaration */: + case 135 /* MethodSignature */: + case 140 /* CallSignature */: + case 141 /* ConstructSignature */: + case 160 /* CallExpression */: + case 161 /* NewExpression */: return true; default: return false; @@ -34034,7 +35834,10 @@ var ts; Rules.IsTypeArgumentOrParameter(context.nextTokenSpan, context.nextTokenParent); }; Rules.IsVoidOpContext = function (context) { - return context.currentTokenSpan.kind === 99 /* VoidKeyword */ && context.currentTokenParent.kind === 167 /* VoidExpression */; + return context.currentTokenSpan.kind === 99 /* VoidKeyword */ && context.currentTokenParent.kind === 169 /* VoidExpression */; + }; + Rules.IsYieldOrYieldStarWithOperand = function (context) { + return context.contextNode.kind === 175 /* YieldExpression */ && context.contextNode.expression !== undefined; }; return Rules; })(); @@ -34058,7 +35861,7 @@ var ts; return result; }; RulesMap.prototype.Initialize = function (rules) { - this.mapRowLength = 126 /* LastToken */ + 1; + this.mapRowLength = 127 /* LastToken */ + 1; this.map = new Array(this.mapRowLength * this.mapRowLength); //new Array(this.mapRowLength * this.mapRowLength); // This array is used only during construction of the rulesbucket in the map var rulesBucketConstructionStateList = new Array(this.map.length); //new Array(this.map.length); @@ -34078,13 +35881,13 @@ var ts; }; RulesMap.prototype.FillRule = function (rule, rulesBucketConstructionStateList) { var _this = this; - var specificRule = rule.Descriptor.LeftTokenRange != formatting.Shared.TokenRange.Any && - rule.Descriptor.RightTokenRange != formatting.Shared.TokenRange.Any; + var specificRule = rule.Descriptor.LeftTokenRange !== formatting.Shared.TokenRange.Any && + rule.Descriptor.RightTokenRange !== formatting.Shared.TokenRange.Any; rule.Descriptor.LeftTokenRange.GetTokens().forEach(function (left) { rule.Descriptor.RightTokenRange.GetTokens().forEach(function (right) { var rulesBucketIndex = _this.GetRuleBucketIndex(left, right); var rulesBucket = _this.map[rulesBucketIndex]; - if (rulesBucket == undefined) { + if (rulesBucket === undefined) { rulesBucket = _this.map[rulesBucketIndex] = new RulesBucket(); } rulesBucket.AddRule(rule, specificRule, rulesBucketConstructionStateList, rulesBucketIndex); @@ -34151,7 +35954,7 @@ var ts; RulesBucketConstructionState.prototype.IncreaseInsertionIndex = function (maskPosition) { var value = (this.rulesInsertionIndexBitmap >> maskPosition) & Mask; value++; - ts.Debug.assert((value & Mask) == value, "Adding more rules into the sub-bucket than allowed. Maximum allowed is 32 rules."); + ts.Debug.assert((value & Mask) === value, "Adding more rules into the sub-bucket than allowed. Maximum allowed is 32 rules."); var temp = this.rulesInsertionIndexBitmap & ~(Mask << maskPosition); temp |= value << maskPosition; this.rulesInsertionIndexBitmap = temp; @@ -34168,7 +35971,7 @@ var ts; }; RulesBucket.prototype.AddRule = function (rule, specificTokens, constructionState, rulesBucketIndex) { var position; - if (rule.Operation.Action == 1 /* Ignore */) { + if (rule.Operation.Action === 1 /* Ignore */) { position = specificTokens ? RulesPosition.IgnoreRulesSpecific : RulesPosition.IgnoreRulesAny; @@ -34243,7 +36046,7 @@ var ts; return [this.token]; }; TokenSingleValueAccess.prototype.Contains = function (tokenValue) { - return tokenValue == this.token; + return tokenValue === this.token; }; return TokenSingleValueAccess; })(); @@ -34253,7 +36056,7 @@ var ts; } TokenAllAccess.prototype.GetTokens = function () { var result = []; - for (var token = 0 /* FirstToken */; token <= 126 /* LastToken */; token++) { + for (var token = 0 /* FirstToken */; token <= 127 /* LastToken */; token++) { result.push(token); } return result; @@ -34295,9 +36098,9 @@ var ts; }; TokenRange.Any = TokenRange.AllTokens(); TokenRange.AnyIncludingMultilineComments = TokenRange.FromTokens(TokenRange.Any.GetTokens().concat([3 /* MultiLineCommentTrivia */])); - TokenRange.Keywords = TokenRange.FromRange(66 /* FirstKeyword */, 126 /* LastKeyword */); + TokenRange.Keywords = TokenRange.FromRange(66 /* FirstKeyword */, 127 /* LastKeyword */); TokenRange.BinaryOperators = TokenRange.FromRange(24 /* FirstBinaryOperator */, 64 /* LastBinaryOperator */); - TokenRange.BinaryKeywordOperators = TokenRange.FromTokens([86 /* InKeyword */, 87 /* InstanceOfKeyword */, 126 /* OfKeyword */]); + TokenRange.BinaryKeywordOperators = TokenRange.FromTokens([86 /* InKeyword */, 87 /* InstanceOfKeyword */, 127 /* OfKeyword */, 117 /* IsKeyword */]); TokenRange.UnaryPrefixOperators = TokenRange.FromTokens([38 /* PlusPlusToken */, 39 /* MinusMinusToken */, 47 /* TildeToken */, 46 /* ExclamationToken */]); TokenRange.UnaryPrefixExpressions = TokenRange.FromTokens([7 /* NumericLiteral */, 65 /* Identifier */, 16 /* OpenParenToken */, 18 /* OpenBracketToken */, 14 /* OpenBraceToken */, 93 /* ThisKeyword */, 88 /* NewKeyword */]); TokenRange.UnaryPreincrementExpressions = TokenRange.FromTokens([65 /* Identifier */, 16 /* OpenParenToken */, 93 /* ThisKeyword */, 88 /* NewKeyword */]); @@ -34305,7 +36108,7 @@ var ts; TokenRange.UnaryPredecrementExpressions = TokenRange.FromTokens([65 /* Identifier */, 16 /* OpenParenToken */, 93 /* ThisKeyword */, 88 /* NewKeyword */]); TokenRange.UnaryPostdecrementExpressions = TokenRange.FromTokens([65 /* Identifier */, 17 /* CloseParenToken */, 19 /* CloseBracketToken */, 88 /* NewKeyword */]); TokenRange.Comments = TokenRange.FromTokens([2 /* SingleLineCommentTrivia */, 3 /* MultiLineCommentTrivia */]); - TokenRange.TypeNames = TokenRange.FromTokens([65 /* Identifier */, 120 /* NumberKeyword */, 122 /* StringKeyword */, 113 /* BooleanKeyword */, 123 /* SymbolKeyword */, 99 /* VoidKeyword */, 112 /* AnyKeyword */]); + TokenRange.TypeNames = TokenRange.FromTokens([65 /* Identifier */, 121 /* NumberKeyword */, 123 /* StringKeyword */, 113 /* BooleanKeyword */, 124 /* SymbolKeyword */, 99 /* VoidKeyword */, 112 /* AnyKeyword */]); return TokenRange; })(); Shared.TokenRange = TokenRange; @@ -34344,6 +36147,7 @@ var ts; return this.rulesMap; }; RulesProvider.prototype.ensureUpToDate = function (options) { + // TODO: Should this be '==='? if (this.options == null || !ts.compareDataObjects(this.options, options)) { var activeRules = this.createActiveRules(options); var rulesMap = formatting.RulesMap.create(activeRules); @@ -34508,17 +36312,17 @@ var ts; // i.e. parent is class declaration with the list of members and node is one of members. function isListElement(parent, node) { switch (parent.kind) { - case 202 /* ClassDeclaration */: - case 203 /* InterfaceDeclaration */: + case 204 /* ClassDeclaration */: + case 205 /* InterfaceDeclaration */: return ts.rangeContainsRange(parent.members, node); - case 206 /* ModuleDeclaration */: + case 208 /* ModuleDeclaration */: var body = parent.body; - return body && body.kind === 180 /* Block */ && ts.rangeContainsRange(body.statements, node); - case 228 /* SourceFile */: - case 180 /* Block */: - case 207 /* ModuleBlock */: + return body && body.kind === 182 /* Block */ && ts.rangeContainsRange(body.statements, node); + case 230 /* SourceFile */: + case 182 /* Block */: + case 209 /* ModuleBlock */: return ts.rangeContainsRange(parent.statements, node); - case 224 /* CatchClause */: + case 226 /* CatchClause */: return ts.rangeContainsRange(parent.block.statements, node); } return false; @@ -34691,9 +36495,9 @@ var ts; // - source file // - switch\default clauses if (isSomeBlock(parent.kind) || - parent.kind === 228 /* SourceFile */ || - parent.kind === 221 /* CaseClause */ || - parent.kind === 222 /* DefaultClause */) { + parent.kind === 230 /* SourceFile */ || + parent.kind === 223 /* CaseClause */ || + parent.kind === 224 /* DefaultClause */) { indentation = parentDynamicIndentation.getIndentation() + parentDynamicIndentation.getDelta(); } else { @@ -34729,19 +36533,19 @@ var ts; return node.modifiers[0].kind; } switch (node.kind) { - case 202 /* ClassDeclaration */: return 69 /* ClassKeyword */; - case 203 /* InterfaceDeclaration */: return 103 /* InterfaceKeyword */; - case 201 /* FunctionDeclaration */: return 83 /* FunctionKeyword */; - case 205 /* EnumDeclaration */: return 205 /* EnumDeclaration */; - case 137 /* GetAccessor */: return 116 /* GetKeyword */; - case 138 /* SetAccessor */: return 121 /* SetKeyword */; - case 135 /* MethodDeclaration */: + case 204 /* ClassDeclaration */: return 69 /* ClassKeyword */; + case 205 /* InterfaceDeclaration */: return 103 /* InterfaceKeyword */; + case 203 /* FunctionDeclaration */: return 83 /* FunctionKeyword */; + case 207 /* EnumDeclaration */: return 207 /* EnumDeclaration */; + case 138 /* GetAccessor */: return 116 /* GetKeyword */; + case 139 /* SetAccessor */: return 122 /* SetKeyword */; + case 136 /* MethodDeclaration */: if (node.asteriskToken) { return 35 /* AsteriskToken */; } // fall-through - case 133 /* PropertyDeclaration */: - case 130 /* Parameter */: + case 134 /* PropertyDeclaration */: + case 131 /* Parameter */: return node.name.kind; } } @@ -34874,7 +36678,7 @@ var ts; consumeTokenAndAdvanceScanner(tokenInfo, node, parentDynamicIndentation); return inheritedIndentation; } - var effectiveParentStartLine = child.kind === 131 /* Decorator */ ? childStartLine : undecoratedParentStartLine; + var effectiveParentStartLine = child.kind === 132 /* Decorator */ ? childStartLine : undecoratedParentStartLine; var childIndentation = computeIndentation(child, childStartLine, childIndentationAmount, node, parentDynamicIndentation, effectiveParentStartLine); processNode(child, childContextNode, childStartLine, undecoratedChildStartLine, childIndentation.indentation, childIndentation.delta); childContextNode = node; @@ -35197,20 +37001,20 @@ var ts; } function isSomeBlock(kind) { switch (kind) { - case 180 /* Block */: - case 207 /* ModuleBlock */: + case 182 /* Block */: + case 209 /* ModuleBlock */: return true; } return false; } function getOpenTokenForList(node, list) { switch (node.kind) { - case 136 /* Constructor */: - case 201 /* FunctionDeclaration */: - case 163 /* FunctionExpression */: - case 135 /* MethodDeclaration */: - case 134 /* MethodSignature */: - case 164 /* ArrowFunction */: + case 137 /* Constructor */: + case 203 /* FunctionDeclaration */: + case 165 /* FunctionExpression */: + case 136 /* MethodDeclaration */: + case 135 /* MethodSignature */: + case 166 /* ArrowFunction */: if (node.typeParameters === list) { return 24 /* LessThanToken */; } @@ -35218,8 +37022,8 @@ var ts; return 16 /* OpenParenToken */; } break; - case 158 /* CallExpression */: - case 159 /* NewExpression */: + case 160 /* CallExpression */: + case 161 /* NewExpression */: if (node.typeArguments === list) { return 24 /* LessThanToken */; } @@ -35227,7 +37031,7 @@ var ts; return 16 /* OpenParenToken */; } break; - case 142 /* TypeReference */: + case 144 /* TypeReference */: if (node.typeArguments === list) { return 24 /* LessThanToken */; } @@ -35326,7 +37130,7 @@ var ts; return 0; } var lineAtPosition = sourceFile.getLineAndCharacterOfPosition(position).line; - if (precedingToken.kind === 23 /* CommaToken */ && precedingToken.parent.kind !== 170 /* BinaryExpression */) { + if (precedingToken.kind === 23 /* CommaToken */ && precedingToken.parent.kind !== 172 /* BinaryExpression */) { // previous token is comma that separates items in list - find the previous item and try to derive indentation from it var actualIndentation = getActualIndentationForListItemBeforeComma(precedingToken, sourceFile, options); if (actualIndentation !== -1 /* Unknown */) { @@ -35437,7 +37241,7 @@ var ts; // - parent is SourceFile - by default immediate children of SourceFile are not indented except when user indents them manually // - parent and child are not on the same line var useActualIndentation = (ts.isDeclaration(current) || ts.isStatement(current)) && - (parent.kind === 228 /* SourceFile */ || !parentAndChildShareLine); + (parent.kind === 230 /* SourceFile */ || !parentAndChildShareLine); if (!useActualIndentation) { return -1 /* Unknown */; } @@ -35470,7 +37274,7 @@ var ts; return sourceFile.getLineAndCharacterOfPosition(n.getStart(sourceFile)); } function childStartsOnTheSameLineWithElseInIfStatement(parent, child, childStartLine, sourceFile) { - if (parent.kind === 184 /* IfStatement */ && parent.elseStatement === child) { + if (parent.kind === 186 /* IfStatement */ && parent.elseStatement === child) { var elseKeyword = ts.findChildOfKind(parent, 76 /* ElseKeyword */, sourceFile); ts.Debug.assert(elseKeyword !== undefined); var elseKeywordStartLine = getStartLineAndCharacterForNode(elseKeyword, sourceFile).line; @@ -35482,23 +37286,23 @@ var ts; function getContainingList(node, sourceFile) { if (node.parent) { switch (node.parent.kind) { - case 142 /* TypeReference */: + case 144 /* TypeReference */: if (node.parent.typeArguments && ts.rangeContainsStartEnd(node.parent.typeArguments, node.getStart(sourceFile), node.getEnd())) { return node.parent.typeArguments; } break; - case 155 /* ObjectLiteralExpression */: + case 157 /* ObjectLiteralExpression */: return node.parent.properties; - case 154 /* ArrayLiteralExpression */: + case 156 /* ArrayLiteralExpression */: return node.parent.elements; - case 201 /* FunctionDeclaration */: - case 163 /* FunctionExpression */: - case 164 /* ArrowFunction */: - case 135 /* MethodDeclaration */: - case 134 /* MethodSignature */: - case 139 /* CallSignature */: - case 140 /* ConstructSignature */: { + case 203 /* FunctionDeclaration */: + case 165 /* FunctionExpression */: + case 166 /* ArrowFunction */: + case 136 /* MethodDeclaration */: + case 135 /* MethodSignature */: + case 140 /* CallSignature */: + case 141 /* ConstructSignature */: { var start = node.getStart(sourceFile); if (node.parent.typeParameters && ts.rangeContainsStartEnd(node.parent.typeParameters, start, node.getEnd())) { @@ -35509,8 +37313,8 @@ var ts; } break; } - case 159 /* NewExpression */: - case 158 /* CallExpression */: { + case 161 /* NewExpression */: + case 160 /* CallExpression */: { var start = node.getStart(sourceFile); if (node.parent.typeArguments && ts.rangeContainsStartEnd(node.parent.typeArguments, start, node.getEnd())) { @@ -35589,28 +37393,28 @@ var ts; SmartIndenter.findFirstNonWhitespaceColumn = findFirstNonWhitespaceColumn; function nodeContentIsAlwaysIndented(kind) { switch (kind) { - case 202 /* ClassDeclaration */: - case 203 /* InterfaceDeclaration */: - case 205 /* EnumDeclaration */: - case 154 /* ArrayLiteralExpression */: - case 180 /* Block */: - case 207 /* ModuleBlock */: - case 155 /* ObjectLiteralExpression */: - case 146 /* TypeLiteral */: - case 148 /* TupleType */: - case 208 /* CaseBlock */: - case 222 /* DefaultClause */: - case 221 /* CaseClause */: - case 162 /* ParenthesizedExpression */: - case 158 /* CallExpression */: - case 159 /* NewExpression */: - case 181 /* VariableStatement */: - case 199 /* VariableDeclaration */: - case 215 /* ExportAssignment */: - case 192 /* ReturnStatement */: - case 171 /* ConditionalExpression */: - case 152 /* ArrayBindingPattern */: - case 151 /* ObjectBindingPattern */: + case 204 /* ClassDeclaration */: + case 205 /* InterfaceDeclaration */: + case 207 /* EnumDeclaration */: + case 156 /* ArrayLiteralExpression */: + case 182 /* Block */: + case 209 /* ModuleBlock */: + case 157 /* ObjectLiteralExpression */: + case 148 /* TypeLiteral */: + case 150 /* TupleType */: + case 210 /* CaseBlock */: + case 224 /* DefaultClause */: + case 223 /* CaseClause */: + case 164 /* ParenthesizedExpression */: + case 160 /* CallExpression */: + case 161 /* NewExpression */: + case 183 /* VariableStatement */: + case 201 /* VariableDeclaration */: + case 217 /* ExportAssignment */: + case 194 /* ReturnStatement */: + case 173 /* ConditionalExpression */: + case 154 /* ArrayBindingPattern */: + case 153 /* ObjectBindingPattern */: return true; } return false; @@ -35620,22 +37424,22 @@ var ts; return true; } switch (parent) { - case 185 /* DoStatement */: - case 186 /* WhileStatement */: - case 188 /* ForInStatement */: - case 189 /* ForOfStatement */: - case 187 /* ForStatement */: - case 184 /* IfStatement */: - case 201 /* FunctionDeclaration */: - case 163 /* FunctionExpression */: - case 135 /* MethodDeclaration */: - case 134 /* MethodSignature */: - case 139 /* CallSignature */: - case 164 /* ArrowFunction */: - case 136 /* Constructor */: - case 137 /* GetAccessor */: - case 138 /* SetAccessor */: - return child !== 180 /* Block */; + case 187 /* DoStatement */: + case 188 /* WhileStatement */: + case 190 /* ForInStatement */: + case 191 /* ForOfStatement */: + case 189 /* ForStatement */: + case 186 /* IfStatement */: + case 203 /* FunctionDeclaration */: + case 165 /* FunctionExpression */: + case 136 /* MethodDeclaration */: + case 135 /* MethodSignature */: + case 140 /* CallSignature */: + case 166 /* ArrowFunction */: + case 137 /* Constructor */: + case 138 /* GetAccessor */: + case 139 /* SetAccessor */: + return child !== 182 /* Block */; default: return false; } @@ -35648,8 +37452,7 @@ var ts; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; /// /// @@ -35718,7 +37521,7 @@ var ts; return this.getEnd() - this.getStart(sourceFile); }; NodeObject.prototype.getFullWidth = function () { - return this.end - this.getFullStart(); + return this.end - this.pos; }; NodeObject.prototype.getLeadingTriviaWidth = function (sourceFile) { return this.getStart(sourceFile) - this.pos; @@ -35740,7 +37543,7 @@ var ts; return pos; }; NodeObject.prototype.createSyntaxList = function (nodes) { - var list = createNode(229 /* SyntaxList */, nodes.pos, nodes.end, 1024 /* Synthetic */, this); + var list = createNode(253 /* SyntaxList */, nodes.pos, nodes.end, 1024 /* Synthetic */, this); list._children = []; var pos = nodes.pos; for (var _i = 0; _i < nodes.length; _i++) { @@ -35759,7 +37562,7 @@ var ts; NodeObject.prototype.createChildren = function (sourceFile) { var _this = this; var children; - if (this.kind >= 127 /* FirstNode */) { + if (this.kind >= 128 /* FirstNode */) { scanner.setText((sourceFile || this.getSourceFile()).text); children = []; var pos = this.pos; @@ -35804,7 +37607,7 @@ var ts; var children = this.getChildren(); for (var _i = 0; _i < children.length; _i++) { var child = children[_i]; - if (child.kind < 127 /* FirstNode */) { + if (child.kind < 128 /* FirstNode */) { return child; } return child.getFirstToken(sourceFile); @@ -35814,7 +37617,7 @@ var ts; var children = this.getChildren(sourceFile); for (var i = children.length - 1; i >= 0; i--) { var child = children[i]; - if (child.kind < 127 /* FirstNode */) { + if (child.kind < 128 /* FirstNode */) { return child; } return child.getLastToken(sourceFile); @@ -35867,7 +37670,7 @@ var ts; if (ts.indexOf(declarations, declaration) === indexOfDeclaration) { var sourceFileOfDeclaration = ts.getSourceFileOfNode(declaration); // If it is parameter - try and get the jsDoc comment with @param tag from function declaration's jsDoc comments - if (canUseParsedParamTagComments && declaration.kind === 130 /* Parameter */) { + if (canUseParsedParamTagComments && declaration.kind === 131 /* Parameter */) { ts.forEach(getJsDocCommentTextRange(declaration.parent, sourceFileOfDeclaration), function (jsDocCommentTextRange) { var cleanedParamJsDocComment = getCleanedParamJsDocComment(jsDocCommentTextRange.pos, jsDocCommentTextRange.end, sourceFileOfDeclaration); if (cleanedParamJsDocComment) { @@ -35876,15 +37679,15 @@ var ts; }); } // If this is left side of dotted module declaration, there is no doc comments associated with this node - if (declaration.kind === 206 /* ModuleDeclaration */ && declaration.body.kind === 206 /* ModuleDeclaration */) { + if (declaration.kind === 208 /* ModuleDeclaration */ && declaration.body.kind === 208 /* ModuleDeclaration */) { return; } // If this is dotted module name, get the doc comments from the parent - while (declaration.kind === 206 /* ModuleDeclaration */ && declaration.parent.kind === 206 /* ModuleDeclaration */) { + while (declaration.kind === 208 /* ModuleDeclaration */ && declaration.parent.kind === 208 /* ModuleDeclaration */) { declaration = declaration.parent; } // Get the cleaned js doc comment text from the declaration - ts.forEach(getJsDocCommentTextRange(declaration.kind === 199 /* VariableDeclaration */ ? declaration.parent.parent : declaration, sourceFileOfDeclaration), function (jsDocCommentTextRange) { + ts.forEach(getJsDocCommentTextRange(declaration.kind === 201 /* VariableDeclaration */ ? declaration.parent.parent : declaration, sourceFileOfDeclaration), function (jsDocCommentTextRange) { var cleanedJsDocComment = getCleanedJsDocComment(jsDocCommentTextRange.pos, jsDocCommentTextRange.end, sourceFileOfDeclaration); if (cleanedJsDocComment) { jsDocCommentParts.push.apply(jsDocCommentParts, cleanedJsDocComment); @@ -36223,9 +38026,9 @@ var ts; if (result_2 !== undefined) { return result_2; } - if (declaration.name.kind === 128 /* ComputedPropertyName */) { + if (declaration.name.kind === 129 /* ComputedPropertyName */) { var expr = declaration.name.expression; - if (expr.kind === 156 /* PropertyAccessExpression */) { + if (expr.kind === 158 /* PropertyAccessExpression */) { return expr.name.text; } return getTextOfIdentifierOrLiteral(expr); @@ -36245,9 +38048,9 @@ var ts; } function visit(node) { switch (node.kind) { - case 201 /* FunctionDeclaration */: - case 135 /* MethodDeclaration */: - case 134 /* MethodSignature */: + case 203 /* FunctionDeclaration */: + case 136 /* MethodDeclaration */: + case 135 /* MethodSignature */: var functionDeclaration = node; var declarationName = getDeclarationName(functionDeclaration); if (declarationName) { @@ -36267,60 +38070,60 @@ var ts; ts.forEachChild(node, visit); } break; - case 202 /* ClassDeclaration */: - case 203 /* InterfaceDeclaration */: - case 204 /* TypeAliasDeclaration */: - case 205 /* EnumDeclaration */: - case 206 /* ModuleDeclaration */: - case 209 /* ImportEqualsDeclaration */: - case 218 /* ExportSpecifier */: - case 214 /* ImportSpecifier */: - case 209 /* ImportEqualsDeclaration */: - case 211 /* ImportClause */: - case 212 /* NamespaceImport */: - case 137 /* GetAccessor */: - case 138 /* SetAccessor */: - case 146 /* TypeLiteral */: + case 204 /* ClassDeclaration */: + case 205 /* InterfaceDeclaration */: + case 206 /* TypeAliasDeclaration */: + case 207 /* EnumDeclaration */: + case 208 /* ModuleDeclaration */: + case 211 /* ImportEqualsDeclaration */: + case 220 /* ExportSpecifier */: + case 216 /* ImportSpecifier */: + case 211 /* ImportEqualsDeclaration */: + case 213 /* ImportClause */: + case 214 /* NamespaceImport */: + case 138 /* GetAccessor */: + case 139 /* SetAccessor */: + case 148 /* TypeLiteral */: addDeclaration(node); // fall through - case 136 /* Constructor */: - case 181 /* VariableStatement */: - case 200 /* VariableDeclarationList */: - case 151 /* ObjectBindingPattern */: - case 152 /* ArrayBindingPattern */: - case 207 /* ModuleBlock */: + case 137 /* Constructor */: + case 183 /* VariableStatement */: + case 202 /* VariableDeclarationList */: + case 153 /* ObjectBindingPattern */: + case 154 /* ArrayBindingPattern */: + case 209 /* ModuleBlock */: ts.forEachChild(node, visit); break; - case 180 /* Block */: + case 182 /* Block */: if (ts.isFunctionBlock(node)) { ts.forEachChild(node, visit); } break; - case 130 /* Parameter */: + case 131 /* Parameter */: // Only consider properties defined as constructor parameters if (!(node.flags & 112 /* AccessibilityModifier */)) { break; } // fall through - case 199 /* VariableDeclaration */: - case 153 /* BindingElement */: + case 201 /* VariableDeclaration */: + case 155 /* BindingElement */: if (ts.isBindingPattern(node.name)) { ts.forEachChild(node.name, visit); break; } - case 227 /* EnumMember */: - case 133 /* PropertyDeclaration */: - case 132 /* PropertySignature */: + case 229 /* EnumMember */: + case 134 /* PropertyDeclaration */: + case 133 /* PropertySignature */: addDeclaration(node); break; - case 216 /* ExportDeclaration */: + case 218 /* ExportDeclaration */: // Handle named exports case e.g.: // export {a, b as B} from "mod"; if (node.exportClause) { ts.forEach(node.exportClause.elements, visit); } break; - case 210 /* ImportDeclaration */: + case 212 /* ImportDeclaration */: var importClause = node.importClause; if (importClause) { // Handle default import case e.g.: @@ -36332,7 +38135,7 @@ var ts; // import * as NS from "mod"; // import {a, b as B} from "mod"; if (importClause.namedBindings) { - if (importClause.namedBindings.kind === 212 /* NamespaceImport */) { + if (importClause.namedBindings.kind === 214 /* NamespaceImport */) { addDeclaration(importClause.namedBindings); } else { @@ -36495,6 +38298,7 @@ var ts; ClassificationTypeNames.typeParameterName = "type parameter name"; ClassificationTypeNames.typeAliasName = "type alias name"; ClassificationTypeNames.parameterName = "parameter name"; + ClassificationTypeNames.docCommentTagName = "doc comment tag name"; return ClassificationTypeNames; })(); ts.ClassificationTypeNames = ClassificationTypeNames; @@ -36516,6 +38320,7 @@ var ts; ClassificationType[ClassificationType["typeParameterName"] = 15] = "typeParameterName"; ClassificationType[ClassificationType["typeAliasName"] = 16] = "typeAliasName"; ClassificationType[ClassificationType["parameterName"] = 17] = "parameterName"; + ClassificationType[ClassificationType["docCommentTagName"] = 18] = "docCommentTagName"; })(ts.ClassificationType || (ts.ClassificationType = {})); var ClassificationType = ts.ClassificationType; function displayPartsToString(displayParts) { @@ -36531,16 +38336,16 @@ var ts; } return ts.forEach(symbol.declarations, function (declaration) { // Function expressions are local - if (declaration.kind === 163 /* FunctionExpression */) { + if (declaration.kind === 165 /* FunctionExpression */) { return true; } - if (declaration.kind !== 199 /* VariableDeclaration */ && declaration.kind !== 201 /* FunctionDeclaration */) { + if (declaration.kind !== 201 /* VariableDeclaration */ && declaration.kind !== 203 /* FunctionDeclaration */) { return false; } // If the parent is not sourceFile or module block it is local variable - for (var parent_7 = declaration.parent; !ts.isFunctionBlock(parent_7); parent_7 = parent_7.parent) { + for (var parent_9 = declaration.parent; !ts.isFunctionBlock(parent_9); parent_9 = parent_9.parent) { // Reached source file or module block - if (parent_7.kind === 228 /* SourceFile */ || parent_7.kind === 207 /* ModuleBlock */) { + if (parent_9.kind === 230 /* SourceFile */ || parent_9.kind === 209 /* ModuleBlock */) { return false; } } @@ -36584,9 +38389,8 @@ var ts; var HostCache = (function () { function HostCache(host, getCanonicalFileName) { this.host = host; - this.getCanonicalFileName = getCanonicalFileName; // script id => script index - this.fileNameToEntry = {}; + this.fileNameToEntry = ts.createFileMap(getCanonicalFileName); // Initialize the list with the root file names var rootFileNames = host.getScriptFileNames(); for (var _i = 0; _i < rootFileNames.length; _i++) { @@ -36599,9 +38403,6 @@ var ts; HostCache.prototype.compilationSettings = function () { return this._compilationSettings; }; - HostCache.prototype.normalizeFileName = function (fileName) { - return this.getCanonicalFileName(ts.normalizeSlashes(fileName)); - }; HostCache.prototype.createEntry = function (fileName) { var entry; var scriptSnapshot = this.host.getScriptSnapshot(fileName); @@ -36612,13 +38413,14 @@ var ts; scriptSnapshot: scriptSnapshot }; } - return this.fileNameToEntry[this.normalizeFileName(fileName)] = entry; + this.fileNameToEntry.set(fileName, entry); + return entry; }; HostCache.prototype.getEntry = function (fileName) { - return ts.lookUp(this.fileNameToEntry, this.normalizeFileName(fileName)); + return this.fileNameToEntry.get(fileName); }; HostCache.prototype.contains = function (fileName) { - return ts.hasProperty(this.fileNameToEntry, this.normalizeFileName(fileName)); + return this.fileNameToEntry.contains(fileName); }; HostCache.prototype.getOrCreateEntry = function (fileName) { if (this.contains(fileName)) { @@ -36627,12 +38429,10 @@ var ts; return this.createEntry(fileName); }; HostCache.prototype.getRootFileNames = function () { - var _this = this; var fileNames = []; - ts.forEachKey(this.fileNameToEntry, function (key) { - var entry = _this.getEntry(key); - if (entry) { - fileNames.push(entry.hostFileName); + this.fileNameToEntry.forEachValue(function (value) { + if (value) { + fileNames.push(value.hostFileName); } }); return fileNames; @@ -36687,21 +38487,29 @@ var ts; * This function will compile source text from 'input' argument using specified compiler options. * If not options are provided - it will use a set of default compiler options. * Extra compiler options that will unconditionally be used bu this function are: - * - separateCompilation = true + * - isolatedModules = true * - allowNonTsExtensions = true + * - noLib = true + * - noResolve = true */ - function transpile(input, compilerOptions, fileName, diagnostics) { + function transpile(input, compilerOptions, fileName, diagnostics, moduleName) { var options = compilerOptions ? ts.clone(compilerOptions) : getDefaultCompilerOptions(); - options.separateCompilation = true; + options.isolatedModules = true; // Filename can be non-ts file. options.allowNonTsExtensions = true; + // We are not returning a sourceFile for lib file when asked by the program, + // so pass --noLib to avoid reporting a file not found error. + options.noLib = true; + // We are not doing a full typecheck, we are not resolving the whole context, + // so pass --noResolve to avoid reporting missing file errors. + options.noResolve = true; // Parse var inputFileName = fileName || "module.ts"; var sourceFile = ts.createSourceFile(inputFileName, input, options.target); - // Store syntactic diagnostics - if (diagnostics && sourceFile.parseDiagnostics) { - diagnostics.push.apply(diagnostics, sourceFile.parseDiagnostics); + if (moduleName) { + sourceFile.moduleName = moduleName; } + var newLine = ts.getNewLineCharacter(options); // Output var outputText; // Create a compilerHost object to allow the compiler to read and write files @@ -36715,12 +38523,11 @@ var ts; useCaseSensitiveFileNames: function () { return false; }, getCanonicalFileName: function (fileName) { return fileName; }, getCurrentDirectory: function () { return ""; }, - getNewLine: function () { return (ts.sys && ts.sys.newLine) || "\r\n"; } + getNewLine: function () { return newLine; } }; var program = ts.createProgram([inputFileName], options, compilerHost); - if (diagnostics) { - diagnostics.push.apply(diagnostics, program.getGlobalDiagnostics()); - } + ts.addRange(diagnostics, program.getSyntacticDiagnostics(sourceFile)); + ts.addRange(diagnostics, program.getOptionsDiagnostics()); // Emit program.emit(); ts.Debug.assert(outputText !== undefined, "Output generation failed"); @@ -36728,7 +38535,8 @@ var ts; } ts.transpile = transpile; function createLanguageServiceSourceFile(fileName, scriptSnapshot, scriptTarget, version, setNodeParents) { - var sourceFile = ts.createSourceFile(fileName, scriptSnapshot.getText(0, scriptSnapshot.getLength()), scriptTarget, setNodeParents); + var text = scriptSnapshot.getText(0, scriptSnapshot.getLength()); + var sourceFile = ts.createSourceFile(fileName, text, scriptTarget, setNodeParents); setSourceFileFields(sourceFile, scriptSnapshot, version); // after full parsing we can use table with interned strings as name table sourceFile.nameTable = sourceFile.identifiers; @@ -36743,7 +38551,30 @@ var ts; if (version !== sourceFile.version) { // Once incremental parsing is ready, then just call into this function. if (!ts.disableIncrementalParsing) { - var newSourceFile = ts.updateSourceFile(sourceFile, scriptSnapshot.getText(0, scriptSnapshot.getLength()), textChangeRange, aggressiveChecks); + var newText; + // grab the fragment from the beginning of the original text to the beginning of the span + var prefix = textChangeRange.span.start !== 0 + ? sourceFile.text.substr(0, textChangeRange.span.start) + : ""; + // grab the fragment from the end of the span till the end of the original text + var suffix = ts.textSpanEnd(textChangeRange.span) !== sourceFile.text.length + ? sourceFile.text.substr(ts.textSpanEnd(textChangeRange.span)) + : ""; + if (textChangeRange.newLength === 0) { + // edit was a deletion - just combine prefix and suffix + newText = prefix && suffix ? prefix + suffix : prefix || suffix; + } + else { + // it was actual edit, fetch the fragment of new text that correspond to new span + var changedText = scriptSnapshot.getText(textChangeRange.span.start, textChangeRange.span.start + textChangeRange.newLength); + // combine prefix, changed text and suffix + newText = prefix && suffix + ? prefix + changedText + suffix + : prefix + ? (prefix + changedText) + : (changedText + suffix); + } + var newSourceFile = ts.updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks); setSourceFileFields(newSourceFile, scriptSnapshot, version); // after incremental parsing nameTable might not be up-to-date // drop it so it can be lazily recreated later @@ -36756,10 +38587,16 @@ var ts; return createLanguageServiceSourceFile(sourceFile.fileName, scriptSnapshot, sourceFile.languageVersion, version, true); } ts.updateLanguageServiceSourceFile = updateLanguageServiceSourceFile; - function createDocumentRegistry() { + function createGetCanonicalFileName(useCaseSensitivefileNames) { + return useCaseSensitivefileNames + ? (function (fileName) { return fileName; }) + : (function (fileName) { return fileName.toLowerCase(); }); + } + function createDocumentRegistry(useCaseSensitiveFileNames) { // Maps from compiler setting target (ES3, ES5, etc.) to all the cached documents we have // for those settings. var buckets = {}; + var getCanonicalFileName = createGetCanonicalFileName(!!useCaseSensitiveFileNames); function getKeyFromCompilationSettings(settings) { return "_" + settings.target; // + "|" + settings.propagateEnumConstantoString() } @@ -36767,7 +38604,7 @@ var ts; var key = getKeyFromCompilationSettings(settings); var bucket = ts.lookUp(buckets, key); if (!bucket && createIfMissing) { - buckets[key] = bucket = {}; + buckets[key] = bucket = ts.createFileMap(getCanonicalFileName); } return bucket; } @@ -36776,7 +38613,7 @@ var ts; var entries = ts.lookUp(buckets, name); var sourceFiles = []; for (var i in entries) { - var entry = entries[i]; + var entry = entries.get(i); sourceFiles.push({ name: i, refCount: entry.languageServiceRefCount, @@ -36799,16 +38636,17 @@ var ts; } function acquireOrUpdateDocument(fileName, compilationSettings, scriptSnapshot, version, acquiring) { var bucket = getBucketForCompilationSettings(compilationSettings, true); - var entry = ts.lookUp(bucket, fileName); + var entry = bucket.get(fileName); if (!entry) { ts.Debug.assert(acquiring, "How could we be trying to update a document that the registry doesn't have?"); // Have never seen this file with these settings. Create a new source file for it. var sourceFile = createLanguageServiceSourceFile(fileName, scriptSnapshot, compilationSettings.target, version, false); - bucket[fileName] = entry = { + entry = { sourceFile: sourceFile, languageServiceRefCount: 0, owners: [] }; + bucket.set(fileName, entry); } else { // We have an entry for this file. However, it may be for a different version of @@ -36831,11 +38669,11 @@ var ts; function releaseDocument(fileName, compilationSettings) { var bucket = getBucketForCompilationSettings(compilationSettings, false); ts.Debug.assert(bucket !== undefined); - var entry = ts.lookUp(bucket, fileName); + var entry = bucket.get(fileName); entry.languageServiceRefCount--; ts.Debug.assert(entry.languageServiceRefCount >= 0); if (entry.languageServiceRefCount === 0) { - delete bucket[fileName]; + bucket.remove(fileName); } } return { @@ -36898,7 +38736,7 @@ var ts; else { if (token === 65 /* Identifier */) { token = scanner.scan(); - if (token === 125 /* FromKeyword */) { + if (token === 126 /* FromKeyword */) { token = scanner.scan(); if (token === 8 /* StringLiteral */) { // import d from "mod"; @@ -36908,7 +38746,7 @@ var ts; } else if (token === 53 /* EqualsToken */) { token = scanner.scan(); - if (token === 119 /* RequireKeyword */) { + if (token === 120 /* RequireKeyword */) { token = scanner.scan(); if (token === 16 /* OpenParenToken */) { token = scanner.scan(); @@ -36937,7 +38775,7 @@ var ts; } if (token === 15 /* CloseBraceToken */) { token = scanner.scan(); - if (token === 125 /* FromKeyword */) { + if (token === 126 /* FromKeyword */) { token = scanner.scan(); if (token === 8 /* StringLiteral */) { // import {a as A} from "mod"; @@ -36953,7 +38791,7 @@ var ts; token = scanner.scan(); if (token === 65 /* Identifier */) { token = scanner.scan(); - if (token === 125 /* FromKeyword */) { + if (token === 126 /* FromKeyword */) { token = scanner.scan(); if (token === 8 /* StringLiteral */) { // import * as NS from "mod" @@ -36976,7 +38814,7 @@ var ts; } if (token === 15 /* CloseBraceToken */) { token = scanner.scan(); - if (token === 125 /* FromKeyword */) { + if (token === 126 /* FromKeyword */) { token = scanner.scan(); if (token === 8 /* StringLiteral */) { // export {a as A} from "mod"; @@ -36988,7 +38826,7 @@ var ts; } else if (token === 35 /* AsteriskToken */) { token = scanner.scan(); - if (token === 125 /* FromKeyword */) { + if (token === 126 /* FromKeyword */) { token = scanner.scan(); if (token === 8 /* StringLiteral */) { // export * from "mod" @@ -37011,7 +38849,7 @@ var ts; /// Helpers function getTargetLabel(referenceNode, labelName) { while (referenceNode) { - if (referenceNode.kind === 195 /* LabeledStatement */ && referenceNode.label.text === labelName) { + if (referenceNode.kind === 197 /* LabeledStatement */ && referenceNode.label.text === labelName) { return referenceNode.label; } referenceNode = referenceNode.parent; @@ -37020,12 +38858,12 @@ var ts; } function isJumpStatementTarget(node) { return node.kind === 65 /* Identifier */ && - (node.parent.kind === 191 /* BreakStatement */ || node.parent.kind === 190 /* ContinueStatement */) && + (node.parent.kind === 193 /* BreakStatement */ || node.parent.kind === 192 /* ContinueStatement */) && node.parent.label === node; } function isLabelOfLabeledStatement(node) { return node.kind === 65 /* Identifier */ && - node.parent.kind === 195 /* LabeledStatement */ && + node.parent.kind === 197 /* LabeledStatement */ && node.parent.label === node; } /** @@ -37033,7 +38871,7 @@ var ts; * Note: 'node' cannot be a SourceFile. */ function isLabeledBy(node, labelName) { - for (var owner = node.parent; owner.kind === 195 /* LabeledStatement */; owner = owner.parent) { + for (var owner = node.parent; owner.kind === 197 /* LabeledStatement */; owner = owner.parent) { if (owner.label.text === labelName) { return true; } @@ -37044,25 +38882,25 @@ var ts; return isLabelOfLabeledStatement(node) || isJumpStatementTarget(node); } function isRightSideOfQualifiedName(node) { - return node.parent.kind === 127 /* QualifiedName */ && node.parent.right === node; + return node.parent.kind === 128 /* QualifiedName */ && node.parent.right === node; } function isRightSideOfPropertyAccess(node) { - return node && node.parent && node.parent.kind === 156 /* PropertyAccessExpression */ && node.parent.name === node; + return node && node.parent && node.parent.kind === 158 /* PropertyAccessExpression */ && node.parent.name === node; } function isCallExpressionTarget(node) { if (isRightSideOfPropertyAccess(node)) { node = node.parent; } - return node && node.parent && node.parent.kind === 158 /* CallExpression */ && node.parent.expression === node; + return node && node.parent && node.parent.kind === 160 /* CallExpression */ && node.parent.expression === node; } function isNewExpressionTarget(node) { if (isRightSideOfPropertyAccess(node)) { node = node.parent; } - return node && node.parent && node.parent.kind === 159 /* NewExpression */ && node.parent.expression === node; + return node && node.parent && node.parent.kind === 161 /* NewExpression */ && node.parent.expression === node; } function isNameOfModuleDeclaration(node) { - return node.parent.kind === 206 /* ModuleDeclaration */ && node.parent.name === node; + return node.parent.kind === 208 /* ModuleDeclaration */ && node.parent.name === node; } function isNameOfFunctionDeclaration(node) { return node.kind === 65 /* Identifier */ && @@ -37071,22 +38909,22 @@ var ts; /** Returns true if node is a name of an object literal property, e.g. "a" in x = { "a": 1 } */ function isNameOfPropertyAssignment(node) { return (node.kind === 65 /* Identifier */ || node.kind === 8 /* StringLiteral */ || node.kind === 7 /* NumericLiteral */) && - (node.parent.kind === 225 /* PropertyAssignment */ || node.parent.kind === 226 /* ShorthandPropertyAssignment */) && node.parent.name === node; + (node.parent.kind === 227 /* PropertyAssignment */ || node.parent.kind === 228 /* ShorthandPropertyAssignment */) && node.parent.name === node; } function isLiteralNameOfPropertyDeclarationOrIndexAccess(node) { if (node.kind === 8 /* StringLiteral */ || node.kind === 7 /* NumericLiteral */) { switch (node.parent.kind) { - case 133 /* PropertyDeclaration */: - case 132 /* PropertySignature */: - case 225 /* PropertyAssignment */: - case 227 /* EnumMember */: - case 135 /* MethodDeclaration */: - case 134 /* MethodSignature */: - case 137 /* GetAccessor */: - case 138 /* SetAccessor */: - case 206 /* ModuleDeclaration */: + case 134 /* PropertyDeclaration */: + case 133 /* PropertySignature */: + case 227 /* PropertyAssignment */: + case 229 /* EnumMember */: + case 136 /* MethodDeclaration */: + case 135 /* MethodSignature */: + case 138 /* GetAccessor */: + case 139 /* SetAccessor */: + case 208 /* ModuleDeclaration */: return node.parent.name === node; - case 157 /* ElementAccessExpression */: + case 159 /* ElementAccessExpression */: return node.parent.argumentExpression === node; } } @@ -37145,7 +38983,7 @@ var ts; })(BreakContinueSearchType || (BreakContinueSearchType = {})); // A cache of completion entries for keywords, these do not change between sessions var keywordCompletions = []; - for (var i = 66 /* FirstKeyword */; i <= 126 /* LastKeyword */; i++) { + for (var i = 66 /* FirstKeyword */; i <= 127 /* LastKeyword */; i++) { keywordCompletions.push({ name: ts.tokenToString(i), kind: ScriptElementKind.keyword, @@ -37160,17 +38998,17 @@ var ts; return undefined; } switch (node.kind) { - case 228 /* SourceFile */: - case 135 /* MethodDeclaration */: - case 134 /* MethodSignature */: - case 201 /* FunctionDeclaration */: - case 163 /* FunctionExpression */: - case 137 /* GetAccessor */: - case 138 /* SetAccessor */: - case 202 /* ClassDeclaration */: - case 203 /* InterfaceDeclaration */: - case 205 /* EnumDeclaration */: - case 206 /* ModuleDeclaration */: + case 230 /* SourceFile */: + case 136 /* MethodDeclaration */: + case 135 /* MethodSignature */: + case 203 /* FunctionDeclaration */: + case 165 /* FunctionExpression */: + case 138 /* GetAccessor */: + case 139 /* SetAccessor */: + case 204 /* ClassDeclaration */: + case 205 /* InterfaceDeclaration */: + case 207 /* EnumDeclaration */: + case 208 /* ModuleDeclaration */: return node; } } @@ -37178,38 +39016,38 @@ var ts; ts.getContainerNode = getContainerNode; /* @internal */ function getNodeKind(node) { switch (node.kind) { - case 206 /* ModuleDeclaration */: return ScriptElementKind.moduleElement; - case 202 /* ClassDeclaration */: return ScriptElementKind.classElement; - case 203 /* InterfaceDeclaration */: return ScriptElementKind.interfaceElement; - case 204 /* TypeAliasDeclaration */: return ScriptElementKind.typeElement; - case 205 /* EnumDeclaration */: return ScriptElementKind.enumElement; - case 199 /* VariableDeclaration */: + case 208 /* ModuleDeclaration */: return ScriptElementKind.moduleElement; + case 204 /* ClassDeclaration */: return ScriptElementKind.classElement; + case 205 /* InterfaceDeclaration */: return ScriptElementKind.interfaceElement; + case 206 /* TypeAliasDeclaration */: return ScriptElementKind.typeElement; + case 207 /* EnumDeclaration */: return ScriptElementKind.enumElement; + case 201 /* VariableDeclaration */: return ts.isConst(node) ? ScriptElementKind.constElement : ts.isLet(node) ? ScriptElementKind.letElement : ScriptElementKind.variableElement; - case 201 /* FunctionDeclaration */: return ScriptElementKind.functionElement; - case 137 /* GetAccessor */: return ScriptElementKind.memberGetAccessorElement; - case 138 /* SetAccessor */: return ScriptElementKind.memberSetAccessorElement; - case 135 /* MethodDeclaration */: - case 134 /* MethodSignature */: + case 203 /* FunctionDeclaration */: return ScriptElementKind.functionElement; + case 138 /* GetAccessor */: return ScriptElementKind.memberGetAccessorElement; + case 139 /* SetAccessor */: return ScriptElementKind.memberSetAccessorElement; + case 136 /* MethodDeclaration */: + case 135 /* MethodSignature */: return ScriptElementKind.memberFunctionElement; - case 133 /* PropertyDeclaration */: - case 132 /* PropertySignature */: + case 134 /* PropertyDeclaration */: + case 133 /* PropertySignature */: return ScriptElementKind.memberVariableElement; - case 141 /* IndexSignature */: return ScriptElementKind.indexSignatureElement; - case 140 /* ConstructSignature */: return ScriptElementKind.constructSignatureElement; - case 139 /* CallSignature */: return ScriptElementKind.callSignatureElement; - case 136 /* Constructor */: return ScriptElementKind.constructorImplementationElement; - case 129 /* TypeParameter */: return ScriptElementKind.typeParameterElement; - case 227 /* EnumMember */: return ScriptElementKind.variableElement; - case 130 /* Parameter */: return (node.flags & 112 /* AccessibilityModifier */) ? ScriptElementKind.memberVariableElement : ScriptElementKind.parameterElement; - case 209 /* ImportEqualsDeclaration */: - case 214 /* ImportSpecifier */: - case 211 /* ImportClause */: - case 218 /* ExportSpecifier */: - case 212 /* NamespaceImport */: + case 142 /* IndexSignature */: return ScriptElementKind.indexSignatureElement; + case 141 /* ConstructSignature */: return ScriptElementKind.constructSignatureElement; + case 140 /* CallSignature */: return ScriptElementKind.callSignatureElement; + case 137 /* Constructor */: return ScriptElementKind.constructorImplementationElement; + case 130 /* TypeParameter */: return ScriptElementKind.typeParameterElement; + case 229 /* EnumMember */: return ScriptElementKind.variableElement; + case 131 /* Parameter */: return (node.flags & 112 /* AccessibilityModifier */) ? ScriptElementKind.memberVariableElement : ScriptElementKind.parameterElement; + case 211 /* ImportEqualsDeclaration */: + case 216 /* ImportSpecifier */: + case 213 /* ImportClause */: + case 220 /* ExportSpecifier */: + case 214 /* NamespaceImport */: return ScriptElementKind.alias; } return ScriptElementKind.unknown; @@ -37232,9 +39070,7 @@ var ts; host.log(message); } } - function getCanonicalFileName(fileName) { - return useCaseSensitivefileNames ? fileName : fileName.toLowerCase(); - } + var getCanonicalFileName = createGetCanonicalFileName(useCaseSensitivefileNames); function getValidSourceFile(fileName) { fileName = ts.normalizeSlashes(fileName); var sourceFile = program.getSourceFile(getCanonicalFileName(fileName)); @@ -37299,12 +39135,16 @@ var ts; } } } + // hostCache is captured in the closure for 'getOrCreateSourceFile' but it should not be used past this point. + // It needs to be cleared to allow all collected snapshots to be released + hostCache = undefined; program = newProgram; // Make sure all the nodes in the program are both bound, and have their parent // pointers set property. program.getTypeChecker(); return; function getOrCreateSourceFile(fileName) { + ts.Debug.assert(hostCache !== undefined); // The program is asking for this file, check first if the host can locate it. // If the host can not locate the file, then it does not exist. return undefined // to the program to allow reporting of errors for missing files. @@ -37421,44 +39261,44 @@ var ts; return false; } switch (node.kind) { - case 209 /* ImportEqualsDeclaration */: + case 211 /* ImportEqualsDeclaration */: diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.import_can_only_be_used_in_a_ts_file)); return true; - case 215 /* ExportAssignment */: + case 217 /* ExportAssignment */: diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.export_can_only_be_used_in_a_ts_file)); return true; - case 202 /* ClassDeclaration */: + case 204 /* ClassDeclaration */: var classDeclaration = node; if (checkModifiers(classDeclaration.modifiers) || checkTypeParameters(classDeclaration.typeParameters)) { return true; } break; - case 223 /* HeritageClause */: + case 225 /* HeritageClause */: var heritageClause = node; if (heritageClause.token === 102 /* ImplementsKeyword */) { diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.implements_clauses_can_only_be_used_in_a_ts_file)); return true; } break; - case 203 /* InterfaceDeclaration */: + case 205 /* InterfaceDeclaration */: diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.interface_declarations_can_only_be_used_in_a_ts_file)); return true; - case 206 /* ModuleDeclaration */: + case 208 /* ModuleDeclaration */: diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.module_declarations_can_only_be_used_in_a_ts_file)); return true; - case 204 /* TypeAliasDeclaration */: + case 206 /* TypeAliasDeclaration */: diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.type_aliases_can_only_be_used_in_a_ts_file)); return true; - case 135 /* MethodDeclaration */: - case 134 /* MethodSignature */: - case 136 /* Constructor */: - case 137 /* GetAccessor */: - case 138 /* SetAccessor */: - case 163 /* FunctionExpression */: - case 201 /* FunctionDeclaration */: - case 164 /* ArrowFunction */: - case 201 /* FunctionDeclaration */: + case 136 /* MethodDeclaration */: + case 135 /* MethodSignature */: + case 137 /* Constructor */: + case 138 /* GetAccessor */: + case 139 /* SetAccessor */: + case 165 /* FunctionExpression */: + case 203 /* FunctionDeclaration */: + case 166 /* ArrowFunction */: + case 203 /* FunctionDeclaration */: var functionDeclaration = node; if (checkModifiers(functionDeclaration.modifiers) || checkTypeParameters(functionDeclaration.typeParameters) || @@ -37466,20 +39306,20 @@ var ts; return true; } break; - case 181 /* VariableStatement */: + case 183 /* VariableStatement */: var variableStatement = node; if (checkModifiers(variableStatement.modifiers)) { return true; } break; - case 199 /* VariableDeclaration */: + case 201 /* VariableDeclaration */: var variableDeclaration = node; if (checkTypeAnnotation(variableDeclaration.type)) { return true; } break; - case 158 /* CallExpression */: - case 159 /* NewExpression */: + case 160 /* CallExpression */: + case 161 /* NewExpression */: var expression = node; if (expression.typeArguments && expression.typeArguments.length > 0) { var start = expression.typeArguments.pos; @@ -37487,7 +39327,7 @@ var ts; return true; } break; - case 130 /* Parameter */: + case 131 /* Parameter */: var parameter = node; if (parameter.modifiers) { var start = parameter.modifiers.pos; @@ -37495,7 +39335,7 @@ var ts; return true; } if (parameter.questionToken) { - diagnostics.push(ts.createDiagnosticForNode(parameter.questionToken, ts.Diagnostics.can_only_be_used_in_a_ts_file)); + diagnostics.push(ts.createDiagnosticForNode(parameter.questionToken, ts.Diagnostics._0_can_only_be_used_in_a_ts_file, '?')); return true; } if (parameter.type) { @@ -37503,17 +39343,17 @@ var ts; return true; } break; - case 133 /* PropertyDeclaration */: + case 134 /* PropertyDeclaration */: diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.property_declarations_can_only_be_used_in_a_ts_file)); return true; - case 205 /* EnumDeclaration */: + case 207 /* EnumDeclaration */: diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.enum_declarations_can_only_be_used_in_a_ts_file)); return true; - case 161 /* TypeAssertionExpression */: + case 163 /* TypeAssertionExpression */: var typeAssertionExpression = node; diagnostics.push(ts.createDiagnosticForNode(typeAssertionExpression.type, ts.Diagnostics.type_assertion_expressions_can_only_be_used_in_a_ts_file)); return true; - case 131 /* Decorator */: + case 132 /* Decorator */: diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.decorators_can_only_be_used_in_a_ts_file)); return true; } @@ -37558,7 +39398,7 @@ var ts; } function getCompilerOptionsDiagnostics() { synchronizeHostData(); - return program.getGlobalDiagnostics(); + return program.getOptionsDiagnostics().concat(program.getGlobalDiagnostics()); } /// Completion function getCompletionEntryDisplayNameForSymbol(symbol, target, performCharacterChecks) { @@ -37612,6 +39452,7 @@ var ts; var typeChecker = program.getTypeChecker(); var syntacticStart = new Date().getTime(); var sourceFile = getValidSourceFile(fileName); + var isJavaScriptFile = ts.isJavaScript(fileName); var start = new Date().getTime(); var currentToken = ts.getTokenAtPosition(sourceFile, position); log("getCompletionData: Get current token: " + (new Date().getTime() - start)); @@ -37646,11 +39487,11 @@ var ts; // visible symbols in the scope, and the node is the current location. var node = currentToken; var isRightOfDot = false; - if (contextToken && contextToken.kind === 20 /* DotToken */ && contextToken.parent.kind === 156 /* PropertyAccessExpression */) { + if (contextToken && contextToken.kind === 20 /* DotToken */ && contextToken.parent.kind === 158 /* PropertyAccessExpression */) { node = contextToken.parent.expression; isRightOfDot = true; } - else if (contextToken && contextToken.kind === 20 /* DotToken */ && contextToken.parent.kind === 127 /* QualifiedName */) { + else if (contextToken && contextToken.kind === 20 /* DotToken */ && contextToken.parent.kind === 128 /* QualifiedName */) { node = contextToken.parent.left; isRightOfDot = true; } @@ -37677,7 +39518,7 @@ var ts; // Right of dot member completion list isMemberCompletion = true; isNewIdentifierLocation = false; - if (node.kind === 65 /* Identifier */ || node.kind === 127 /* QualifiedName */ || node.kind === 156 /* PropertyAccessExpression */) { + if (node.kind === 65 /* Identifier */ || node.kind === 128 /* QualifiedName */ || node.kind === 158 /* PropertyAccessExpression */) { var symbol = typeChecker.getSymbolAtLocation(node); // This is an alias, follow what it aliases if (symbol && symbol.flags & 8388608 /* Alias */) { @@ -37694,13 +39535,29 @@ var ts; } } var type = typeChecker.getTypeAtLocation(node); + addTypeProperties(type); + } + function addTypeProperties(type) { if (type) { // Filter private properties - ts.forEach(type.getApparentProperties(), function (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 & 16384 /* 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); + } + } } } function tryGetGlobalSymbols() { @@ -37719,13 +39576,13 @@ var ts; symbols = filterContextualMembersList(contextualTypeMembers, containingObjectLiteral.properties); } } - else if (ts.getAncestor(contextToken, 211 /* ImportClause */)) { + else if (ts.getAncestor(contextToken, 213 /* ImportClause */)) { // cursor is in import clause // try to show exported member for imported module isMemberCompletion = true; isNewIdentifierLocation = true; if (showCompletionsInImportsClause(contextToken)) { - var importDeclaration = ts.getAncestor(contextToken, 210 /* ImportDeclaration */); + var importDeclaration = ts.getAncestor(contextToken, 212 /* ImportDeclaration */); ts.Debug.assert(importDeclaration !== undefined); var exports; if (importDeclaration.moduleSpecifier) { @@ -37804,7 +39661,7 @@ var ts; // import {| // import {a,| if (node.kind === 14 /* OpenBraceToken */ || node.kind === 23 /* CommaToken */) { - return node.parent.kind === 213 /* NamedImports */; + return node.parent.kind === 215 /* NamedImports */; } } return false; @@ -37814,38 +39671,38 @@ var ts; var containingNodeKind = previousToken.parent.kind; switch (previousToken.kind) { case 23 /* CommaToken */: - return containingNodeKind === 158 /* CallExpression */ // func( a, | - || containingNodeKind === 136 /* Constructor */ // constructor( a, | public, protected, private keywords are allowed here, so show completion - || containingNodeKind === 159 /* NewExpression */ // new C(a, | - || containingNodeKind === 154 /* ArrayLiteralExpression */ // [a, | - || containingNodeKind === 170 /* BinaryExpression */ // let x = (a, | - || containingNodeKind === 143 /* FunctionType */; // var x: (s: string, list| + return containingNodeKind === 160 /* CallExpression */ // func( a, | + || containingNodeKind === 137 /* Constructor */ // constructor( a, | public, protected, private keywords are allowed here, so show completion + || containingNodeKind === 161 /* NewExpression */ // new C(a, | + || containingNodeKind === 156 /* ArrayLiteralExpression */ // [a, | + || containingNodeKind === 172 /* BinaryExpression */ // let x = (a, | + || containingNodeKind === 145 /* FunctionType */; // var x: (s: string, list| case 16 /* OpenParenToken */: - return containingNodeKind === 158 /* CallExpression */ // func( | - || containingNodeKind === 136 /* Constructor */ // constructor( | - || containingNodeKind === 159 /* NewExpression */ // new C(a| - || containingNodeKind === 162 /* ParenthesizedExpression */ // let x = (a| - || containingNodeKind === 150 /* ParenthesizedType */; // function F(pred: (a| this can become an arrow function, where 'a' is the argument + return containingNodeKind === 160 /* CallExpression */ // func( | + || containingNodeKind === 137 /* Constructor */ // constructor( | + || containingNodeKind === 161 /* NewExpression */ // new C(a| + || containingNodeKind === 164 /* ParenthesizedExpression */ // let x = (a| + || containingNodeKind === 152 /* ParenthesizedType */; // function F(pred: (a| this can become an arrow function, where 'a' is the argument case 18 /* OpenBracketToken */: - return containingNodeKind === 154 /* ArrayLiteralExpression */; // [ | - case 117 /* ModuleKeyword */: // module | - case 118 /* NamespaceKeyword */: + return containingNodeKind === 156 /* ArrayLiteralExpression */; // [ | + case 118 /* ModuleKeyword */: // module | + case 119 /* NamespaceKeyword */: return true; case 20 /* DotToken */: - return containingNodeKind === 206 /* ModuleDeclaration */; // module A.| + return containingNodeKind === 208 /* ModuleDeclaration */; // module A.| case 14 /* OpenBraceToken */: - return containingNodeKind === 202 /* ClassDeclaration */; // class A{ | + return containingNodeKind === 204 /* ClassDeclaration */; // class A{ | case 53 /* EqualsToken */: - return containingNodeKind === 199 /* VariableDeclaration */ // let x = a| - || containingNodeKind === 170 /* BinaryExpression */; // x = a| + return containingNodeKind === 201 /* VariableDeclaration */ // let x = a| + || containingNodeKind === 172 /* BinaryExpression */; // x = a| case 11 /* TemplateHead */: - return containingNodeKind === 172 /* TemplateExpression */; // `aa ${| + return containingNodeKind === 174 /* TemplateExpression */; // `aa ${| case 12 /* TemplateMiddle */: - return containingNodeKind === 178 /* TemplateSpan */; // `aa ${10} dd ${| + return containingNodeKind === 180 /* TemplateSpan */; // `aa ${10} dd ${| case 108 /* PublicKeyword */: case 106 /* PrivateKeyword */: case 107 /* ProtectedKeyword */: - return containingNodeKind === 133 /* PropertyDeclaration */; // class A{ public | + return containingNodeKind === 134 /* PropertyDeclaration */; // class A{ public | } // Previous token may have been a keyword that was converted to an identifier. switch (previousToken.getText()) { @@ -37861,15 +39718,18 @@ var ts; if (previousToken.kind === 8 /* StringLiteral */ || previousToken.kind === 9 /* RegularExpressionLiteral */ || ts.isTemplateLiteralKind(previousToken.kind)) { - // The position has to be either: 1. entirely within the token text, or - // 2. at the end position of an unterminated token. var start_3 = previousToken.getStart(); var end = previousToken.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) { return true; } - else if (position === end) { - return !!previousToken.isUnterminated; + if (position === end) { + return !!previousToken.isUnterminated || + previousToken.kind === 9 /* RegularExpressionLiteral */; } } return false; @@ -37877,12 +39737,12 @@ var ts; function getContainingObjectLiteralApplicableForCompletion(previousToken) { // The locations in an object literal expression that are applicable for completion are property name definition locations. if (previousToken) { - var parent_8 = previousToken.parent; + var parent_10 = previousToken.parent; switch (previousToken.kind) { case 14 /* OpenBraceToken */: // let x = { | case 23 /* CommaToken */: - if (parent_8 && parent_8.kind === 155 /* ObjectLiteralExpression */) { - return parent_8; + if (parent_10 && parent_10.kind === 157 /* ObjectLiteralExpression */) { + return parent_10; } break; } @@ -37891,16 +39751,16 @@ var ts; } function isFunction(kind) { switch (kind) { - case 163 /* FunctionExpression */: - case 164 /* ArrowFunction */: - case 201 /* FunctionDeclaration */: - case 135 /* MethodDeclaration */: - case 134 /* MethodSignature */: - case 137 /* GetAccessor */: - case 138 /* SetAccessor */: - case 139 /* CallSignature */: - case 140 /* ConstructSignature */: - case 141 /* IndexSignature */: + case 165 /* FunctionExpression */: + case 166 /* ArrowFunction */: + case 203 /* FunctionDeclaration */: + case 136 /* MethodDeclaration */: + case 135 /* MethodSignature */: + case 138 /* GetAccessor */: + case 139 /* SetAccessor */: + case 140 /* CallSignature */: + case 141 /* ConstructSignature */: + case 142 /* IndexSignature */: return true; } return false; @@ -37910,63 +39770,63 @@ var ts; var containingNodeKind = previousToken.parent.kind; switch (previousToken.kind) { case 23 /* CommaToken */: - return containingNodeKind === 199 /* VariableDeclaration */ || - containingNodeKind === 200 /* VariableDeclarationList */ || - containingNodeKind === 181 /* VariableStatement */ || - containingNodeKind === 205 /* EnumDeclaration */ || + return containingNodeKind === 201 /* VariableDeclaration */ || + containingNodeKind === 202 /* VariableDeclarationList */ || + containingNodeKind === 183 /* VariableStatement */ || + containingNodeKind === 207 /* EnumDeclaration */ || isFunction(containingNodeKind) || - containingNodeKind === 202 /* ClassDeclaration */ || - containingNodeKind === 201 /* FunctionDeclaration */ || - containingNodeKind === 203 /* InterfaceDeclaration */ || - containingNodeKind === 152 /* ArrayBindingPattern */ || - containingNodeKind === 151 /* ObjectBindingPattern */; // function func({ x, y| + containingNodeKind === 204 /* ClassDeclaration */ || + containingNodeKind === 203 /* FunctionDeclaration */ || + containingNodeKind === 205 /* InterfaceDeclaration */ || + containingNodeKind === 154 /* ArrayBindingPattern */ || + containingNodeKind === 153 /* ObjectBindingPattern */; // function func({ x, y| case 20 /* DotToken */: - return containingNodeKind === 152 /* ArrayBindingPattern */; // var [.| + return containingNodeKind === 154 /* ArrayBindingPattern */; // var [.| case 51 /* ColonToken */: - return containingNodeKind === 153 /* BindingElement */; // var {x :html| + return containingNodeKind === 155 /* BindingElement */; // var {x :html| case 18 /* OpenBracketToken */: - return containingNodeKind === 152 /* ArrayBindingPattern */; // var [x| + return containingNodeKind === 154 /* ArrayBindingPattern */; // var [x| case 16 /* OpenParenToken */: - return containingNodeKind === 224 /* CatchClause */ || + return containingNodeKind === 226 /* CatchClause */ || isFunction(containingNodeKind); case 14 /* OpenBraceToken */: - return containingNodeKind === 205 /* EnumDeclaration */ || - containingNodeKind === 203 /* InterfaceDeclaration */ || - containingNodeKind === 146 /* TypeLiteral */ || - containingNodeKind === 151 /* ObjectBindingPattern */; // function func({ x| + return containingNodeKind === 207 /* EnumDeclaration */ || + containingNodeKind === 205 /* InterfaceDeclaration */ || + containingNodeKind === 148 /* TypeLiteral */ || + containingNodeKind === 153 /* ObjectBindingPattern */; // function func({ x| case 22 /* SemicolonToken */: - return containingNodeKind === 132 /* PropertySignature */ && + return containingNodeKind === 133 /* PropertySignature */ && previousToken.parent && previousToken.parent.parent && - (previousToken.parent.parent.kind === 203 /* InterfaceDeclaration */ || - previousToken.parent.parent.kind === 146 /* TypeLiteral */); // let x : { a; | + (previousToken.parent.parent.kind === 205 /* InterfaceDeclaration */ || + previousToken.parent.parent.kind === 148 /* TypeLiteral */); // let x : { a; | case 24 /* LessThanToken */: - return containingNodeKind === 202 /* ClassDeclaration */ || - containingNodeKind === 201 /* FunctionDeclaration */ || - containingNodeKind === 203 /* InterfaceDeclaration */ || + return containingNodeKind === 204 /* ClassDeclaration */ || + containingNodeKind === 203 /* FunctionDeclaration */ || + containingNodeKind === 205 /* InterfaceDeclaration */ || isFunction(containingNodeKind); case 109 /* StaticKeyword */: - return containingNodeKind === 133 /* PropertyDeclaration */; + return containingNodeKind === 134 /* PropertyDeclaration */; case 21 /* DotDotDotToken */: - return containingNodeKind === 130 /* Parameter */ || - containingNodeKind === 136 /* Constructor */ || + return containingNodeKind === 131 /* Parameter */ || + containingNodeKind === 137 /* Constructor */ || (previousToken.parent && previousToken.parent.parent && - previousToken.parent.parent.kind === 152 /* ArrayBindingPattern */); // var [...z| + previousToken.parent.parent.kind === 154 /* ArrayBindingPattern */); // var [...z| case 108 /* PublicKeyword */: case 106 /* PrivateKeyword */: case 107 /* ProtectedKeyword */: - return containingNodeKind === 130 /* Parameter */; + return containingNodeKind === 131 /* Parameter */; case 69 /* ClassKeyword */: case 77 /* EnumKeyword */: case 103 /* InterfaceKeyword */: case 83 /* FunctionKeyword */: case 98 /* VarKeyword */: case 116 /* GetKeyword */: - case 121 /* SetKeyword */: + case 122 /* SetKeyword */: case 85 /* ImportKeyword */: case 104 /* LetKeyword */: case 70 /* ConstKeyword */: case 110 /* YieldKeyword */: - case 124 /* TypeKeyword */: + case 125 /* TypeKeyword */: return true; } // Previous token may have been a keyword that was converted to an identifier. @@ -37998,7 +39858,7 @@ var ts; return exports; } if (importDeclaration.importClause.namedBindings && - importDeclaration.importClause.namedBindings.kind === 213 /* NamedImports */) { + importDeclaration.importClause.namedBindings.kind === 215 /* NamedImports */) { ts.forEach(importDeclaration.importClause.namedBindings.elements, function (el) { var name = el.propertyName || el.name; exisingImports[name.text] = true; @@ -38015,7 +39875,7 @@ var ts; } var existingMemberNames = {}; ts.forEach(existingMembers, function (m) { - if (m.kind !== 225 /* PropertyAssignment */ && m.kind !== 226 /* ShorthandPropertyAssignment */) { + if (m.kind !== 227 /* PropertyAssignment */ && m.kind !== 228 /* ShorthandPropertyAssignment */) { // Ignore omitted expressions for missing members in the object literal return; } @@ -38065,10 +39925,10 @@ var ts; for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { var sourceFile = _a[_i]; var nameTable = getNameTable(sourceFile); - for (var name_26 in nameTable) { - if (!allNames[name_26]) { - allNames[name_26] = name_26; - var displayName = getCompletionEntryDisplayName(name_26, target, true); + for (var name_27 in nameTable) { + if (!allNames[name_27]) { + allNames[name_27] = name_27; + var displayName = getCompletionEntryDisplayName(name_27, target, true); if (displayName) { var entry = { name: displayName, @@ -38267,7 +40127,7 @@ var ts; var signature; type = typeChecker.getTypeOfSymbolAtLocation(symbol, location); if (type) { - if (location.parent && location.parent.kind === 156 /* PropertyAccessExpression */) { + if (location.parent && location.parent.kind === 158 /* PropertyAccessExpression */) { var right = location.parent.name; // Either the location is on the right of a property access, or on the left and the right is missing if (right === location || (right && right.getFullWidth() === 0)) { @@ -38276,7 +40136,7 @@ var ts; } // try get the call/construct signature from the type if it matches var callExpression; - if (location.kind === 158 /* CallExpression */ || location.kind === 159 /* NewExpression */) { + if (location.kind === 160 /* CallExpression */ || location.kind === 161 /* NewExpression */) { callExpression = location; } else if (isCallExpressionTarget(location) || isNewExpressionTarget(location)) { @@ -38289,7 +40149,7 @@ var ts; // Use the first candidate: signature = candidateSignatures[0]; } - var useConstructSignatures = callExpression.kind === 159 /* NewExpression */ || callExpression.expression.kind === 91 /* SuperKeyword */; + var useConstructSignatures = callExpression.kind === 161 /* NewExpression */ || callExpression.expression.kind === 91 /* SuperKeyword */; var allSignatures = useConstructSignatures ? type.getConstructSignatures() : type.getCallSignatures(); if (!ts.contains(allSignatures, signature.target || signature)) { // Get the first signature if there @@ -38341,24 +40201,24 @@ var ts; } } else if ((isNameOfFunctionDeclaration(location) && !(symbol.flags & 98304 /* Accessor */)) || - (location.kind === 114 /* ConstructorKeyword */ && location.parent.kind === 136 /* Constructor */)) { + (location.kind === 114 /* ConstructorKeyword */ && location.parent.kind === 137 /* Constructor */)) { // get the signature from the declaration and write it var functionDeclaration = location.parent; - var allSignatures = functionDeclaration.kind === 136 /* Constructor */ ? type.getConstructSignatures() : type.getCallSignatures(); + var allSignatures = functionDeclaration.kind === 137 /* Constructor */ ? type.getConstructSignatures() : type.getCallSignatures(); if (!typeChecker.isImplementationOfOverload(functionDeclaration)) { signature = typeChecker.getSignatureFromDeclaration(functionDeclaration); } else { signature = allSignatures[0]; } - if (functionDeclaration.kind === 136 /* Constructor */) { + if (functionDeclaration.kind === 137 /* Constructor */) { // show (constructor) Type(...) signature symbolKind = ScriptElementKind.constructorImplementationElement; addPrefixForAnyFunctionOrVar(type.symbol, symbolKind); } else { // (function/method) symbol(..signature) - addPrefixForAnyFunctionOrVar(functionDeclaration.kind === 139 /* CallSignature */ && + addPrefixForAnyFunctionOrVar(functionDeclaration.kind === 140 /* CallSignature */ && !(type.symbol.flags & 2048 /* TypeLiteral */ || type.symbol.flags & 4096 /* ObjectLiteral */) ? type.symbol : symbol, symbolKind); } addSignatureDisplayParts(signature, allSignatures); @@ -38381,7 +40241,7 @@ var ts; } if (symbolFlags & 524288 /* TypeAlias */) { addNewLineIfDisplayPartsExist(); - displayParts.push(ts.keywordPart(124 /* TypeKeyword */)); + displayParts.push(ts.keywordPart(125 /* TypeKeyword */)); displayParts.push(ts.spacePart()); addFullSymbolName(symbol); displayParts.push(ts.spacePart()); @@ -38401,9 +40261,9 @@ var ts; } if (symbolFlags & 1536 /* Module */) { addNewLineIfDisplayPartsExist(); - var declaration = ts.getDeclarationOfKind(symbol, 206 /* ModuleDeclaration */); + var declaration = ts.getDeclarationOfKind(symbol, 208 /* ModuleDeclaration */); var isNamespace = declaration && declaration.name && declaration.name.kind === 65 /* Identifier */; - displayParts.push(ts.keywordPart(isNamespace ? 118 /* NamespaceKeyword */ : 117 /* ModuleKeyword */)); + displayParts.push(ts.keywordPart(isNamespace ? 119 /* NamespaceKeyword */ : 118 /* ModuleKeyword */)); displayParts.push(ts.spacePart()); addFullSymbolName(symbol); } @@ -38424,13 +40284,13 @@ var ts; } else { // Method/function type parameter - var signatureDeclaration = ts.getDeclarationOfKind(symbol, 129 /* TypeParameter */).parent; + var signatureDeclaration = ts.getDeclarationOfKind(symbol, 130 /* TypeParameter */).parent; var signature = typeChecker.getSignatureFromDeclaration(signatureDeclaration); - if (signatureDeclaration.kind === 140 /* ConstructSignature */) { + if (signatureDeclaration.kind === 141 /* ConstructSignature */) { displayParts.push(ts.keywordPart(88 /* NewKeyword */)); displayParts.push(ts.spacePart()); } - else if (signatureDeclaration.kind !== 139 /* CallSignature */ && signatureDeclaration.name) { + else if (signatureDeclaration.kind !== 140 /* CallSignature */ && signatureDeclaration.name) { addFullSymbolName(signatureDeclaration.symbol); } displayParts.push.apply(displayParts, ts.signatureToDisplayParts(typeChecker, signature, sourceFile, 32 /* WriteTypeArgumentsOfSignature */)); @@ -38439,7 +40299,7 @@ var ts; if (symbolFlags & 8 /* EnumMember */) { addPrefixForAnyFunctionOrVar(symbol, "enum member"); var declaration = symbol.declarations[0]; - if (declaration.kind === 227 /* EnumMember */) { + if (declaration.kind === 229 /* EnumMember */) { var constantValue = typeChecker.getConstantValue(declaration); if (constantValue !== undefined) { displayParts.push(ts.spacePart()); @@ -38455,13 +40315,13 @@ var ts; displayParts.push(ts.spacePart()); addFullSymbolName(symbol); ts.forEach(symbol.declarations, function (declaration) { - if (declaration.kind === 209 /* ImportEqualsDeclaration */) { + if (declaration.kind === 211 /* ImportEqualsDeclaration */) { var importEqualsDeclaration = declaration; if (ts.isExternalModuleImportEqualsDeclaration(importEqualsDeclaration)) { displayParts.push(ts.spacePart()); displayParts.push(ts.operatorPart(53 /* EqualsToken */)); displayParts.push(ts.spacePart()); - displayParts.push(ts.keywordPart(119 /* RequireKeyword */)); + displayParts.push(ts.keywordPart(120 /* RequireKeyword */)); displayParts.push(ts.punctuationPart(16 /* OpenParenToken */)); displayParts.push(ts.displayPart(ts.getTextOfNode(ts.getExternalModuleImportEqualsDeclarationExpression(importEqualsDeclaration)), SymbolDisplayPartKind.stringLiteral)); displayParts.push(ts.punctuationPart(17 /* CloseParenToken */)); @@ -38588,8 +40448,8 @@ var ts; // Try getting just type at this position and show switch (node.kind) { case 65 /* Identifier */: - case 156 /* PropertyAccessExpression */: - case 127 /* QualifiedName */: + case 158 /* PropertyAccessExpression */: + case 128 /* QualifiedName */: case 93 /* ThisKeyword */: case 91 /* SuperKeyword */: // For the identifiers/this/super etc get the type at position @@ -38647,7 +40507,7 @@ var ts; if (isNewExpressionTarget(location) || location.kind === 114 /* ConstructorKeyword */) { if (symbol.flags & 32 /* Class */) { var classDeclaration = symbol.getDeclarations()[0]; - ts.Debug.assert(classDeclaration && classDeclaration.kind === 202 /* ClassDeclaration */); + ts.Debug.assert(classDeclaration && classDeclaration.kind === 204 /* ClassDeclaration */); return tryAddSignature(classDeclaration.members, true, symbolKind, symbolName, containerName, result); } } @@ -38663,8 +40523,8 @@ var ts; var declarations = []; var definition; ts.forEach(signatureDeclarations, function (d) { - if ((selectConstructors && d.kind === 136 /* Constructor */) || - (!selectConstructors && (d.kind === 201 /* FunctionDeclaration */ || d.kind === 135 /* MethodDeclaration */ || d.kind === 134 /* MethodSignature */))) { + if ((selectConstructors && d.kind === 137 /* Constructor */) || + (!selectConstructors && (d.kind === 203 /* FunctionDeclaration */ || d.kind === 136 /* MethodDeclaration */ || d.kind === 135 /* MethodSignature */))) { declarations.push(d); if (d.body) definition = d; @@ -38733,7 +40593,7 @@ var ts; // go to the declaration of the property name (in this case stay at the same position). However, if go-to-definition // is performed at the location of property access, we would like to go to definition of the property in the short-hand // assignment. This case and others are handled by the following code. - if (node.parent.kind === 226 /* ShorthandPropertyAssignment */) { + if (node.parent.kind === 228 /* ShorthandPropertyAssignment */) { var shorthandSymbol = typeChecker.getShorthandAssignmentValueSymbol(symbol.valueDeclaration); if (!shorthandSymbol) { return []; @@ -38767,7 +40627,7 @@ var ts; var result = []; ts.forEach(type.types, function (t) { if (t.symbol) { - result.push.apply(result, getDefinitionFromSymbol(t.symbol, node)); + ts.addRange(result, getDefinitionFromSymbol(t.symbol, node)); } }); return result; @@ -38862,74 +40722,74 @@ var ts; switch (node.kind) { case 84 /* IfKeyword */: case 76 /* ElseKeyword */: - if (hasKind(node.parent, 184 /* IfStatement */)) { + if (hasKind(node.parent, 186 /* IfStatement */)) { return getIfElseOccurrences(node.parent); } break; case 90 /* ReturnKeyword */: - if (hasKind(node.parent, 192 /* ReturnStatement */)) { + if (hasKind(node.parent, 194 /* ReturnStatement */)) { return getReturnOccurrences(node.parent); } break; case 94 /* ThrowKeyword */: - if (hasKind(node.parent, 196 /* ThrowStatement */)) { + if (hasKind(node.parent, 198 /* ThrowStatement */)) { return getThrowOccurrences(node.parent); } break; case 68 /* CatchKeyword */: - if (hasKind(parent(parent(node)), 197 /* TryStatement */)) { + if (hasKind(parent(parent(node)), 199 /* TryStatement */)) { return getTryCatchFinallyOccurrences(node.parent.parent); } break; case 96 /* TryKeyword */: case 81 /* FinallyKeyword */: - if (hasKind(parent(node), 197 /* TryStatement */)) { + if (hasKind(parent(node), 199 /* TryStatement */)) { return getTryCatchFinallyOccurrences(node.parent); } break; case 92 /* SwitchKeyword */: - if (hasKind(node.parent, 194 /* SwitchStatement */)) { + if (hasKind(node.parent, 196 /* SwitchStatement */)) { return getSwitchCaseDefaultOccurrences(node.parent); } break; case 67 /* CaseKeyword */: case 73 /* DefaultKeyword */: - if (hasKind(parent(parent(parent(node))), 194 /* SwitchStatement */)) { + if (hasKind(parent(parent(parent(node))), 196 /* SwitchStatement */)) { return getSwitchCaseDefaultOccurrences(node.parent.parent.parent); } break; case 66 /* BreakKeyword */: case 71 /* ContinueKeyword */: - if (hasKind(node.parent, 191 /* BreakStatement */) || hasKind(node.parent, 190 /* ContinueStatement */)) { + if (hasKind(node.parent, 193 /* BreakStatement */) || hasKind(node.parent, 192 /* ContinueStatement */)) { return getBreakOrContinueStatementOccurences(node.parent); } break; case 82 /* ForKeyword */: - if (hasKind(node.parent, 187 /* ForStatement */) || - hasKind(node.parent, 188 /* ForInStatement */) || - hasKind(node.parent, 189 /* ForOfStatement */)) { + if (hasKind(node.parent, 189 /* ForStatement */) || + hasKind(node.parent, 190 /* ForInStatement */) || + hasKind(node.parent, 191 /* ForOfStatement */)) { return getLoopBreakContinueOccurrences(node.parent); } break; case 100 /* WhileKeyword */: case 75 /* DoKeyword */: - if (hasKind(node.parent, 186 /* WhileStatement */) || hasKind(node.parent, 185 /* DoStatement */)) { + if (hasKind(node.parent, 188 /* WhileStatement */) || hasKind(node.parent, 187 /* DoStatement */)) { return getLoopBreakContinueOccurrences(node.parent); } break; case 114 /* ConstructorKeyword */: - if (hasKind(node.parent, 136 /* Constructor */)) { + if (hasKind(node.parent, 137 /* Constructor */)) { return getConstructorOccurrences(node.parent); } break; case 116 /* GetKeyword */: - case 121 /* SetKeyword */: - if (hasKind(node.parent, 137 /* GetAccessor */) || hasKind(node.parent, 138 /* SetAccessor */)) { + case 122 /* SetKeyword */: + if (hasKind(node.parent, 138 /* GetAccessor */) || hasKind(node.parent, 139 /* SetAccessor */)) { return getGetAndSetOccurrences(node.parent); } default: if (ts.isModifier(node.kind) && node.parent && - (ts.isDeclaration(node.parent) || node.parent.kind === 181 /* VariableStatement */)) { + (ts.isDeclaration(node.parent) || node.parent.kind === 183 /* VariableStatement */)) { return getModifierOccurrences(node.kind, node.parent); } } @@ -38945,10 +40805,10 @@ var ts; aggregate(node); return statementAccumulator; function aggregate(node) { - if (node.kind === 196 /* ThrowStatement */) { + if (node.kind === 198 /* ThrowStatement */) { statementAccumulator.push(node); } - else if (node.kind === 197 /* TryStatement */) { + else if (node.kind === 199 /* TryStatement */) { var tryStatement = node; if (tryStatement.catchClause) { aggregate(tryStatement.catchClause); @@ -38976,19 +40836,19 @@ var ts; function getThrowStatementOwner(throwStatement) { var child = throwStatement; while (child.parent) { - var parent_9 = child.parent; - if (ts.isFunctionBlock(parent_9) || parent_9.kind === 228 /* SourceFile */) { - return parent_9; + var parent_11 = child.parent; + if (ts.isFunctionBlock(parent_11) || parent_11.kind === 230 /* SourceFile */) { + return parent_11; } // A throw-statement is only owned by a try-statement if the try-statement has // a catch clause, and if the throw-statement occurs within the try block. - if (parent_9.kind === 197 /* TryStatement */) { - var tryStatement = parent_9; + if (parent_11.kind === 199 /* TryStatement */) { + var tryStatement = parent_11; if (tryStatement.tryBlock === child && tryStatement.catchClause) { return child; } } - child = parent_9; + child = parent_11; } return undefined; } @@ -38997,7 +40857,7 @@ var ts; aggregate(node); return statementAccumulator; function aggregate(node) { - if (node.kind === 191 /* BreakStatement */ || node.kind === 190 /* ContinueStatement */) { + if (node.kind === 193 /* BreakStatement */ || node.kind === 192 /* ContinueStatement */) { statementAccumulator.push(node); } else if (!ts.isFunctionLike(node)) { @@ -39011,25 +40871,25 @@ var ts; return actualOwner && actualOwner === owner; } function getBreakOrContinueOwner(statement) { - for (var node_1 = statement.parent; node_1; node_1 = node_1.parent) { - switch (node_1.kind) { - case 194 /* SwitchStatement */: - if (statement.kind === 190 /* ContinueStatement */) { + for (var node_2 = statement.parent; node_2; node_2 = node_2.parent) { + switch (node_2.kind) { + case 196 /* SwitchStatement */: + if (statement.kind === 192 /* ContinueStatement */) { continue; } // Fall through. - case 187 /* ForStatement */: - case 188 /* ForInStatement */: - case 189 /* ForOfStatement */: - case 186 /* WhileStatement */: - case 185 /* DoStatement */: - if (!statement.label || isLabeledBy(node_1, statement.label.text)) { - return node_1; + case 189 /* ForStatement */: + case 190 /* ForInStatement */: + case 191 /* ForOfStatement */: + case 188 /* WhileStatement */: + case 187 /* DoStatement */: + if (!statement.label || isLabeledBy(node_2, statement.label.text)) { + return node_2; } break; default: // Don't cross function boundaries. - if (ts.isFunctionLike(node_1)) { + if (ts.isFunctionLike(node_2)) { return undefined; } break; @@ -39041,18 +40901,18 @@ var ts; var container = declaration.parent; // Make sure we only highlight the keyword when it makes sense to do so. if (ts.isAccessibilityModifier(modifier)) { - if (!(container.kind === 202 /* ClassDeclaration */ || - (declaration.kind === 130 /* Parameter */ && hasKind(container, 136 /* Constructor */)))) { + if (!(container.kind === 204 /* ClassDeclaration */ || + (declaration.kind === 131 /* Parameter */ && hasKind(container, 137 /* Constructor */)))) { return undefined; } } else if (modifier === 109 /* StaticKeyword */) { - if (container.kind !== 202 /* ClassDeclaration */) { + if (container.kind !== 204 /* ClassDeclaration */) { return undefined; } } else if (modifier === 78 /* ExportKeyword */ || modifier === 115 /* DeclareKeyword */) { - if (!(container.kind === 207 /* ModuleBlock */ || container.kind === 228 /* SourceFile */)) { + if (!(container.kind === 209 /* ModuleBlock */ || container.kind === 230 /* SourceFile */)) { return undefined; } } @@ -39064,20 +40924,20 @@ var ts; var modifierFlag = getFlagFromModifier(modifier); var nodes; switch (container.kind) { - case 207 /* ModuleBlock */: - case 228 /* SourceFile */: + case 209 /* ModuleBlock */: + case 230 /* SourceFile */: nodes = container.statements; break; - case 136 /* Constructor */: + case 137 /* Constructor */: nodes = container.parameters.concat(container.parent.members); break; - case 202 /* ClassDeclaration */: + case 204 /* ClassDeclaration */: nodes = container.members; // If we're an accessibility modifier, we're in an instance member and should search // the constructor's parameter list for instance members as well. if (modifierFlag & 112 /* AccessibilityModifier */) { var constructor = ts.forEach(container.members, function (member) { - return member.kind === 136 /* Constructor */ && member; + return member.kind === 137 /* Constructor */ && member; }); if (constructor) { nodes = nodes.concat(constructor.parameters); @@ -39125,13 +40985,13 @@ var ts; } function getGetAndSetOccurrences(accessorDeclaration) { var keywords = []; - tryPushAccessorKeyword(accessorDeclaration.symbol, 137 /* GetAccessor */); - tryPushAccessorKeyword(accessorDeclaration.symbol, 138 /* SetAccessor */); + tryPushAccessorKeyword(accessorDeclaration.symbol, 138 /* GetAccessor */); + tryPushAccessorKeyword(accessorDeclaration.symbol, 139 /* SetAccessor */); return ts.map(keywords, getHighlightSpanForNode); function tryPushAccessorKeyword(accessorSymbol, accessorKind) { var accessor = ts.getDeclarationOfKind(accessorSymbol, accessorKind); if (accessor) { - ts.forEach(accessor.getChildren(), function (child) { return pushKeywordIf(keywords, child, 116 /* GetKeyword */, 121 /* SetKeyword */); }); + ts.forEach(accessor.getChildren(), function (child) { return pushKeywordIf(keywords, child, 116 /* GetKeyword */, 122 /* SetKeyword */); }); } } } @@ -39149,7 +41009,7 @@ var ts; var keywords = []; if (pushKeywordIf(keywords, loopNode.getFirstToken(), 82 /* ForKeyword */, 100 /* WhileKeyword */, 75 /* DoKeyword */)) { // If we succeeded and got a do-while loop, then start looking for a 'while' keyword. - if (loopNode.kind === 185 /* DoStatement */) { + if (loopNode.kind === 187 /* DoStatement */) { var loopTokens = loopNode.getChildren(); for (var i = loopTokens.length - 1; i >= 0; i--) { if (pushKeywordIf(keywords, loopTokens[i], 100 /* WhileKeyword */)) { @@ -39170,13 +41030,13 @@ var ts; var owner = getBreakOrContinueOwner(breakOrContinueStatement); if (owner) { switch (owner.kind) { - case 187 /* ForStatement */: - case 188 /* ForInStatement */: - case 189 /* ForOfStatement */: - case 185 /* DoStatement */: - case 186 /* WhileStatement */: + case 189 /* ForStatement */: + case 190 /* ForInStatement */: + case 191 /* ForOfStatement */: + case 187 /* DoStatement */: + case 188 /* WhileStatement */: return getLoopBreakContinueOccurrences(owner); - case 194 /* SwitchStatement */: + case 196 /* SwitchStatement */: return getSwitchCaseDefaultOccurrences(owner); } } @@ -39230,7 +41090,7 @@ var ts; function getReturnOccurrences(returnStatement) { var func = ts.getContainingFunction(returnStatement); // If we didn't find a containing function with a block body, bail out. - if (!(func && hasKind(func.body, 180 /* Block */))) { + if (!(func && hasKind(func.body, 182 /* Block */))) { return undefined; } var keywords = []; @@ -39246,7 +41106,7 @@ var ts; function getIfElseOccurrences(ifStatement) { var keywords = []; // Traverse upwards through all parent if-statements linked by their else-branches. - while (hasKind(ifStatement.parent, 184 /* IfStatement */) && ifStatement.parent.elseStatement === ifStatement) { + while (hasKind(ifStatement.parent, 186 /* IfStatement */) && ifStatement.parent.elseStatement === ifStatement) { ifStatement = ifStatement.parent; } // Now traverse back down through the else branches, aggregating if/else keywords of if-statements. @@ -39259,7 +41119,7 @@ var ts; break; } } - if (!hasKind(ifStatement.elseStatement, 184 /* IfStatement */)) { + if (!hasKind(ifStatement.elseStatement, 186 /* IfStatement */)) { break; } ifStatement = ifStatement.elseStatement; @@ -39438,17 +41298,17 @@ var ts; } function isImportOrExportSpecifierName(location) { return location.parent && - (location.parent.kind === 214 /* ImportSpecifier */ || location.parent.kind === 218 /* ExportSpecifier */) && + (location.parent.kind === 216 /* ImportSpecifier */ || location.parent.kind === 220 /* ExportSpecifier */) && location.parent.propertyName === location; } function isImportOrExportSpecifierImportSymbol(symbol) { return (symbol.flags & 8388608 /* Alias */) && ts.forEach(symbol.declarations, function (declaration) { - return declaration.kind === 214 /* ImportSpecifier */ || declaration.kind === 218 /* ExportSpecifier */; + return declaration.kind === 216 /* ImportSpecifier */ || declaration.kind === 220 /* ExportSpecifier */; }); } function getDeclaredName(symbol, location) { // Special case for function expressions, whose names are solely local to their bodies. - var functionExpression = ts.forEach(symbol.declarations, function (d) { return d.kind === 163 /* FunctionExpression */ ? d : undefined; }); + var functionExpression = ts.forEach(symbol.declarations, function (d) { return d.kind === 165 /* FunctionExpression */ ? d : undefined; }); // When a name gets interned into a SourceFile's 'identifiers' Map, // its name is escaped and stored in the same way its symbol name/identifier // name should be stored. Function expressions, however, are a special case, @@ -39475,7 +41335,7 @@ var ts; return location.getText(); } // Special case for function expressions, whose names are solely local to their bodies. - var functionExpression = ts.forEach(declarations, function (d) { return d.kind === 163 /* FunctionExpression */ ? d : undefined; }); + var functionExpression = ts.forEach(declarations, function (d) { return d.kind === 165 /* FunctionExpression */ ? d : undefined; }); // When a name gets interned into a SourceFile's 'identifiers' Map, // its name is escaped and stored in the same way its symbol name/identifier // name should be stored. Function expressions, however, are a special case, @@ -39499,7 +41359,7 @@ var ts; if (symbol.flags & (4 /* Property */ | 8192 /* Method */)) { var privateDeclaration = ts.forEach(symbol.getDeclarations(), function (d) { return (d.flags & 32 /* Private */) ? d : undefined; }); if (privateDeclaration) { - return ts.getAncestor(privateDeclaration, 202 /* ClassDeclaration */); + return ts.getAncestor(privateDeclaration, 204 /* ClassDeclaration */); } } // If the symbol is an import we would like to find it if we are looking for what it imports. @@ -39525,7 +41385,7 @@ var ts; // Different declarations have different containers, bail out return undefined; } - if (container.kind === 228 /* SourceFile */ && !ts.isExternalModule(container)) { + if (container.kind === 230 /* SourceFile */ && !ts.isExternalModule(container)) { // This is a global variable and not an external module, any declaration defined // within this scope is visible outside the file return undefined; @@ -39713,13 +41573,13 @@ var ts; // Whether 'super' occurs in a static context within a class. var staticFlag = 128 /* Static */; switch (searchSpaceNode.kind) { - case 133 /* PropertyDeclaration */: - case 132 /* PropertySignature */: - case 135 /* MethodDeclaration */: - case 134 /* MethodSignature */: - case 136 /* Constructor */: - case 137 /* GetAccessor */: - case 138 /* SetAccessor */: + case 134 /* PropertyDeclaration */: + case 133 /* PropertySignature */: + case 136 /* MethodDeclaration */: + case 135 /* MethodSignature */: + case 137 /* Constructor */: + case 138 /* GetAccessor */: + case 139 /* SetAccessor */: staticFlag &= searchSpaceNode.flags; searchSpaceNode = searchSpaceNode.parent; // re-assign to be the owning class break; @@ -39751,27 +41611,27 @@ var ts; // Whether 'this' occurs in a static context within a class. var staticFlag = 128 /* Static */; switch (searchSpaceNode.kind) { - case 135 /* MethodDeclaration */: - case 134 /* MethodSignature */: + case 136 /* MethodDeclaration */: + case 135 /* MethodSignature */: if (ts.isObjectLiteralMethod(searchSpaceNode)) { break; } // fall through - case 133 /* PropertyDeclaration */: - case 132 /* PropertySignature */: - case 136 /* Constructor */: - case 137 /* GetAccessor */: - case 138 /* SetAccessor */: + case 134 /* PropertyDeclaration */: + case 133 /* PropertySignature */: + case 137 /* Constructor */: + case 138 /* GetAccessor */: + case 139 /* SetAccessor */: staticFlag &= searchSpaceNode.flags; searchSpaceNode = searchSpaceNode.parent; // re-assign to be the owning class break; - case 228 /* SourceFile */: + case 230 /* SourceFile */: if (ts.isExternalModule(searchSpaceNode)) { return undefined; } // Fall through - case 201 /* FunctionDeclaration */: - case 163 /* FunctionExpression */: + case 203 /* FunctionDeclaration */: + case 165 /* FunctionExpression */: break; // Computed properties in classes are not handled here because references to this are illegal, // so there is no point finding references to them. @@ -39780,7 +41640,7 @@ var ts; } var references = []; var possiblePositions; - if (searchSpaceNode.kind === 228 /* SourceFile */) { + if (searchSpaceNode.kind === 230 /* SourceFile */) { ts.forEach(sourceFiles, function (sourceFile) { possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "this", sourceFile.getStart(), sourceFile.getEnd()); getThisReferencesInFile(sourceFile, sourceFile, possiblePositions, references); @@ -39811,27 +41671,27 @@ var ts; } var container = ts.getThisContainer(node, false); switch (searchSpaceNode.kind) { - case 163 /* FunctionExpression */: - case 201 /* FunctionDeclaration */: + case 165 /* FunctionExpression */: + case 203 /* FunctionDeclaration */: if (searchSpaceNode.symbol === container.symbol) { result.push(getReferenceEntryFromNode(node)); } break; - case 135 /* MethodDeclaration */: - case 134 /* MethodSignature */: + case 136 /* MethodDeclaration */: + case 135 /* MethodSignature */: if (ts.isObjectLiteralMethod(searchSpaceNode) && searchSpaceNode.symbol === container.symbol) { result.push(getReferenceEntryFromNode(node)); } break; - case 202 /* ClassDeclaration */: + case 204 /* ClassDeclaration */: // Make sure the container belongs to the same class // and has the appropriate static modifier from the original container. if (container.parent && searchSpaceNode.symbol === container.parent.symbol && (container.flags & 128 /* Static */) === staticFlag) { result.push(getReferenceEntryFromNode(node)); } break; - case 228 /* SourceFile */: - if (container.kind === 228 /* SourceFile */ && !ts.isExternalModule(container)) { + case 230 /* SourceFile */: + if (container.kind === 230 /* SourceFile */ && !ts.isExternalModule(container)) { result.push(getReferenceEntryFromNode(node)); } break; @@ -39885,11 +41745,11 @@ var ts; function getPropertySymbolsFromBaseTypes(symbol, propertyName, result) { if (symbol && symbol.flags & (32 /* Class */ | 64 /* Interface */)) { ts.forEach(symbol.getDeclarations(), function (declaration) { - if (declaration.kind === 202 /* ClassDeclaration */) { + if (declaration.kind === 204 /* ClassDeclaration */) { getPropertySymbolFromTypeReference(ts.getClassExtendsHeritageClauseElement(declaration)); ts.forEach(ts.getClassImplementsHeritageClauseElements(declaration), getPropertySymbolFromTypeReference); } - else if (declaration.kind === 203 /* InterfaceDeclaration */) { + else if (declaration.kind === 205 /* InterfaceDeclaration */) { ts.forEach(ts.getInterfaceBaseTypeNodes(declaration), getPropertySymbolFromTypeReference); } }); @@ -39950,19 +41810,19 @@ var ts; if (isNameOfPropertyAssignment(node)) { var objectLiteral = node.parent.parent; var contextualType = typeChecker.getContextualType(objectLiteral); - var name_27 = node.text; + var name_28 = node.text; if (contextualType) { if (contextualType.flags & 16384 /* Union */) { // This is a union type, first see if the property we are looking for is a union property (i.e. exists in all types) // if not, search the constituent types for the property - var unionProperty = contextualType.getProperty(name_27); + var unionProperty = contextualType.getProperty(name_28); if (unionProperty) { return [unionProperty]; } else { var result_4 = []; ts.forEach(contextualType.types, function (t) { - var symbol = t.getProperty(name_27); + var symbol = t.getProperty(name_28); if (symbol) { result_4.push(symbol); } @@ -39971,7 +41831,7 @@ var ts; } } else { - var symbol_1 = contextualType.getProperty(name_27); + var symbol_1 = contextualType.getProperty(name_28); if (symbol_1) { return [symbol_1]; } @@ -40029,10 +41889,10 @@ var ts; } var parent = node.parent; if (parent) { - if (parent.kind === 169 /* PostfixUnaryExpression */ || parent.kind === 168 /* PrefixUnaryExpression */) { + if (parent.kind === 171 /* PostfixUnaryExpression */ || parent.kind === 170 /* PrefixUnaryExpression */) { return true; } - else if (parent.kind === 170 /* BinaryExpression */ && parent.left === node) { + else if (parent.kind === 172 /* BinaryExpression */ && parent.left === node) { var operator = parent.operatorToken.kind; return 53 /* FirstAssignment */ <= operator && operator <= 64 /* LastAssignment */; } @@ -40066,33 +41926,33 @@ var ts; } function getMeaningFromDeclaration(node) { switch (node.kind) { - case 130 /* Parameter */: - case 199 /* VariableDeclaration */: - case 153 /* BindingElement */: - case 133 /* PropertyDeclaration */: - case 132 /* PropertySignature */: - case 225 /* PropertyAssignment */: - case 226 /* ShorthandPropertyAssignment */: - case 227 /* EnumMember */: - case 135 /* MethodDeclaration */: - case 134 /* MethodSignature */: - case 136 /* Constructor */: - case 137 /* GetAccessor */: - case 138 /* SetAccessor */: - case 201 /* FunctionDeclaration */: - case 163 /* FunctionExpression */: - case 164 /* ArrowFunction */: - case 224 /* CatchClause */: + case 131 /* Parameter */: + case 201 /* VariableDeclaration */: + case 155 /* BindingElement */: + case 134 /* PropertyDeclaration */: + case 133 /* PropertySignature */: + case 227 /* PropertyAssignment */: + case 228 /* ShorthandPropertyAssignment */: + case 229 /* EnumMember */: + case 136 /* MethodDeclaration */: + case 135 /* MethodSignature */: + case 137 /* Constructor */: + case 138 /* GetAccessor */: + case 139 /* SetAccessor */: + case 203 /* FunctionDeclaration */: + case 165 /* FunctionExpression */: + case 166 /* ArrowFunction */: + case 226 /* CatchClause */: return 1 /* Value */; - case 129 /* TypeParameter */: - case 203 /* InterfaceDeclaration */: - case 204 /* TypeAliasDeclaration */: - case 146 /* TypeLiteral */: + case 130 /* TypeParameter */: + case 205 /* InterfaceDeclaration */: + case 206 /* TypeAliasDeclaration */: + case 148 /* TypeLiteral */: return 2 /* Type */; - case 202 /* ClassDeclaration */: - case 205 /* EnumDeclaration */: + case 204 /* ClassDeclaration */: + case 207 /* EnumDeclaration */: return 1 /* Value */ | 2 /* Type */; - case 206 /* ModuleDeclaration */: + case 208 /* ModuleDeclaration */: if (node.name.kind === 8 /* StringLiteral */) { return 4 /* Namespace */ | 1 /* Value */; } @@ -40102,15 +41962,15 @@ var ts; else { return 4 /* Namespace */; } - case 213 /* NamedImports */: - case 214 /* ImportSpecifier */: - case 209 /* ImportEqualsDeclaration */: - case 210 /* ImportDeclaration */: - case 215 /* ExportAssignment */: - case 216 /* ExportDeclaration */: + case 215 /* NamedImports */: + case 216 /* ImportSpecifier */: + case 211 /* ImportEqualsDeclaration */: + case 212 /* ImportDeclaration */: + case 217 /* ExportAssignment */: + case 218 /* ExportDeclaration */: return 1 /* Value */ | 2 /* Type */ | 4 /* Namespace */; // An external module can be a Value - case 228 /* SourceFile */: + case 230 /* SourceFile */: return 4 /* Namespace */ | 1 /* Value */; } return 1 /* Value */ | 2 /* Type */ | 4 /* Namespace */; @@ -40120,7 +41980,8 @@ var ts; if (ts.isRightSideOfQualifiedNameOrPropertyAccess(node)) { node = node.parent; } - return node.parent.kind === 142 /* TypeReference */ || node.parent.kind === 177 /* ExpressionWithTypeArguments */; + return node.parent.kind === 144 /* TypeReference */ || + (node.parent.kind === 179 /* ExpressionWithTypeArguments */ && !ts.isExpressionWithTypeArgumentsInClassExtendsClause(node.parent)); } function isNamespaceReference(node) { return isQualifiedNameNamespaceReference(node) || isPropertyAccessNamespaceReference(node); @@ -40128,32 +41989,32 @@ var ts; function isPropertyAccessNamespaceReference(node) { var root = node; var isLastClause = true; - if (root.parent.kind === 156 /* PropertyAccessExpression */) { - while (root.parent && root.parent.kind === 156 /* PropertyAccessExpression */) { + if (root.parent.kind === 158 /* PropertyAccessExpression */) { + while (root.parent && root.parent.kind === 158 /* PropertyAccessExpression */) { root = root.parent; } isLastClause = root.name === node; } - if (!isLastClause && root.parent.kind === 177 /* ExpressionWithTypeArguments */ && root.parent.parent.kind === 223 /* HeritageClause */) { + if (!isLastClause && root.parent.kind === 179 /* ExpressionWithTypeArguments */ && root.parent.parent.kind === 225 /* HeritageClause */) { var decl = root.parent.parent.parent; - return (decl.kind === 202 /* ClassDeclaration */ && root.parent.parent.token === 102 /* ImplementsKeyword */) || - (decl.kind === 203 /* InterfaceDeclaration */ && root.parent.parent.token === 79 /* ExtendsKeyword */); + return (decl.kind === 204 /* ClassDeclaration */ && root.parent.parent.token === 102 /* ImplementsKeyword */) || + (decl.kind === 205 /* InterfaceDeclaration */ && root.parent.parent.token === 79 /* ExtendsKeyword */); } return false; } function isQualifiedNameNamespaceReference(node) { var root = node; var isLastClause = true; - if (root.parent.kind === 127 /* QualifiedName */) { - while (root.parent && root.parent.kind === 127 /* QualifiedName */) { + if (root.parent.kind === 128 /* QualifiedName */) { + while (root.parent && root.parent.kind === 128 /* QualifiedName */) { root = root.parent; } isLastClause = root.right === node; } - return root.parent.kind === 142 /* TypeReference */ && !isLastClause; + return root.parent.kind === 144 /* TypeReference */ && !isLastClause; } function isInRightSideOfImport(node) { - while (node.parent.kind === 127 /* QualifiedName */) { + while (node.parent.kind === 128 /* QualifiedName */) { node = node.parent; } return ts.isInternalModuleImportEqualsDeclaration(node.parent) && node.parent.moduleReference === node; @@ -40163,15 +42024,15 @@ var ts; // import a = |b|; // Namespace // import a = |b.c|; // Value, type, namespace // import a = |b.c|.d; // Namespace - if (node.parent.kind === 127 /* QualifiedName */ && + if (node.parent.kind === 128 /* QualifiedName */ && node.parent.right === node && - node.parent.parent.kind === 209 /* ImportEqualsDeclaration */) { + node.parent.parent.kind === 211 /* ImportEqualsDeclaration */) { return 1 /* Value */ | 2 /* Type */ | 4 /* Namespace */; } return 4 /* Namespace */; } function getMeaningFromLocation(node) { - if (node.parent.kind === 215 /* ExportAssignment */) { + if (node.parent.kind === 217 /* ExportAssignment */) { return 1 /* Value */ | 2 /* Type */ | 4 /* Namespace */; } else if (isInRightSideOfImport(node)) { @@ -40211,8 +42072,8 @@ var ts; return; } switch (node.kind) { - case 156 /* PropertyAccessExpression */: - case 127 /* QualifiedName */: + case 158 /* PropertyAccessExpression */: + case 128 /* QualifiedName */: case 8 /* StringLiteral */: case 80 /* FalseKeyword */: case 95 /* TrueKeyword */: @@ -40235,7 +42096,7 @@ var ts; // If this is name of a module declarations, check if this is right side of dotted module name // If parent of the module declaration which is parent of this node is module declaration and its body is the module declaration that this node is name of // Then this name is name from dotted module - if (nodeForStartPos.parent.parent.kind === 206 /* ModuleDeclaration */ && + if (nodeForStartPos.parent.parent.kind === 208 /* ModuleDeclaration */ && nodeForStartPos.parent.parent.body === nodeForStartPos.parent) { // Use parent module declarations name for start pos nodeForStartPos = nodeForStartPos.parent.parent.name; @@ -40269,6 +42130,7 @@ var ts; var sourceFile = getValidSourceFile(fileName); var typeChecker = program.getTypeChecker(); var result = []; + var classifiableNames = program.getClassifiableNames(); processNode(sourceFile); return { spans: result, endOfLineState: 0 /* None */ }; function pushClassification(start, length, type) { @@ -40278,6 +42140,9 @@ var ts; } function classifySymbol(symbol, meaningAtPosition) { var flags = symbol.getFlags(); + if ((flags & 788448 /* Classifiable */) === 0 /* None */) { + return; + } if (flags & 32 /* Class */) { return 11 /* className */; } @@ -40310,19 +42175,26 @@ var ts; */ function hasValueSideModule(symbol) { return ts.forEach(symbol.declarations, function (declaration) { - return declaration.kind === 206 /* ModuleDeclaration */ && ts.getModuleInstanceState(declaration) == 1 /* Instantiated */; + return declaration.kind === 208 /* ModuleDeclaration */ && + ts.getModuleInstanceState(declaration) === 1 /* Instantiated */; }); } } function processNode(node) { // Only walk into nodes that intersect the requested span. - if (node && ts.textSpanIntersectsWith(span, node.getStart(), node.getWidth())) { - if (node.kind === 65 /* Identifier */ && node.getWidth() > 0) { - var symbol = typeChecker.getSymbolAtLocation(node); - if (symbol) { - var type = classifySymbol(symbol, getMeaningFromLocation(node)); - if (type) { - pushClassification(node.getStart(), node.getWidth(), type); + if (node && ts.textSpanIntersectsWith(span, node.getFullStart(), node.getFullWidth())) { + if (node.kind === 65 /* Identifier */ && !ts.nodeIsMissing(node)) { + var identifier = node; + // 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[identifier.text]) { + var symbol = typeChecker.getSymbolAtLocation(node); + if (symbol) { + var type = classifySymbol(symbol, getMeaningFromLocation(node)); + if (type) { + pushClassification(node.getStart(), node.getWidth(), type); + } } } } @@ -40348,6 +42220,7 @@ var ts; case 15 /* typeParameterName */: return ClassificationTypeNames.typeParameterName; case 16 /* typeAliasName */: return ClassificationTypeNames.typeAliasName; case 17 /* parameterName */: return ClassificationTypeNames.parameterName; + case 18 /* docCommentTagName */: return ClassificationTypeNames.docCommentTagName; } } function convertClassifications(classifications) { @@ -40368,6 +42241,8 @@ var ts; function getEncodedSyntacticClassifications(fileName, span) { // doesn't use compiler - no need to synchronize with host var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); + var spanStart = span.start; + var spanLength = span.length; // Make a scanner we can get trivia from. var triviaScanner = ts.createScanner(2 /* Latest */, false, sourceFile.text); var mergeConflictScanner = ts.createScanner(2 /* Latest */, false, sourceFile.text); @@ -40379,46 +42254,123 @@ var ts; result.push(length); result.push(type); } - function classifyLeadingTrivia(token) { - var tokenStart = ts.skipTrivia(sourceFile.text, token.pos, false); - if (tokenStart === token.pos) { - return; - } - // token has trivia. Classify them appropriately. + function classifyLeadingTriviaAndGetTokenStart(token) { triviaScanner.setTextPos(token.pos); while (true) { var start = triviaScanner.getTextPos(); + // only bother scanning if we have something that could be trivia. + if (!ts.couldStartTrivia(sourceFile.text, start)) { + return start; + } var kind = triviaScanner.scan(); var end = triviaScanner.getTextPos(); var width = end - start; // The moment we get something that isn't trivia, then stop processing. if (!ts.isTrivia(kind)) { - return; + return start; + } + // Don't bother with newlines/whitespace. + if (kind === 4 /* NewLineTrivia */ || kind === 5 /* WhitespaceTrivia */) { + continue; } // Only bother with the trivia if it at least intersects the span of interest. - if (ts.textSpanIntersectsWith(span, start, width)) { - if (ts.isComment(kind)) { - // Simple comment. Just add as is. + if (ts.isComment(kind)) { + classifyComment(token, kind, start, width); + // Classifying a comment might cause us to reuse the trivia scanner + // (because of jsdoc comments). So after we classify the comment make + // sure we set the scanner position back to where it needs to be. + triviaScanner.setTextPos(end); + continue; + } + if (kind === 6 /* ConflictMarkerTrivia */) { + var text = sourceFile.text; + var ch = text.charCodeAt(start); + // for the <<<<<<< and >>>>>>> markers, we just add them in as comments + // in the classification stream. + if (ch === 60 /* lessThan */ || ch === 62 /* greaterThan */) { pushClassification(start, width, 1 /* comment */); continue; } - if (kind === 6 /* ConflictMarkerTrivia */) { - var text = sourceFile.text; - var ch = text.charCodeAt(start); - // for the <<<<<<< and >>>>>>> markers, we just add them in as comments - // in the classification stream. - if (ch === 60 /* lessThan */ || ch === 62 /* greaterThan */) { - 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 */); - classifyDisabledMergeCode(text, start, end); - } + // 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 */); + classifyDisabledMergeCode(text, start, end); } } } + function classifyComment(token, kind, start, width) { + if (kind === 3 /* MultiLineCommentTrivia */) { + // See if this is a doc comment. If so, we'll classify certain portions of it + // specially. + var docCommentAndDiagnostics = ts.parseIsolatedJSDocComment(sourceFile.text, start, width); + if (docCommentAndDiagnostics && docCommentAndDiagnostics.jsDocComment) { + docCommentAndDiagnostics.jsDocComment.parent = token; + classifyJSDocComment(docCommentAndDiagnostics.jsDocComment); + return; + } + } + // Simple comment. Just add as is. + pushCommentRange(start, width); + } + function pushCommentRange(start, width) { + pushClassification(start, width, 1 /* comment */); + } + function classifyJSDocComment(docComment) { + var pos = docComment.pos; + for (var _i = 0, _a = docComment.tags; _i < _a.length; _i++) { + var tag = _a[_i]; + // As we walk through each tag, classify the portion of text from the end of + // the last tag (or the start of the entire doc comment) as 'comment'. + 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 */); + pos = tag.tagName.end; + switch (tag.kind) { + case 249 /* JSDocParameterTag */: + processJSDocParameterTag(tag); + break; + case 252 /* JSDocTemplateTag */: + processJSDocTemplateTag(tag); + break; + case 251 /* JSDocTypeTag */: + processElement(tag.typeExpression); + break; + case 250 /* JSDocReturnTag */: + processElement(tag.typeExpression); + break; + } + pos = tag.end; + } + if (pos !== docComment.end) { + pushCommentRange(pos, docComment.end - pos); + } + 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.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; + } + } + } + function processJSDocTemplateTag(tag) { + for (var _i = 0, _a = tag.getChildren(); _i < _a.length; _i++) { + var child = _a[_i]; + processElement(child); + } + } 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. @@ -40443,11 +42395,16 @@ var ts; } } function classifyToken(token) { - classifyLeadingTrivia(token); - if (token.getWidth() > 0) { + if (ts.nodeIsMissing(token)) { + return; + } + var tokenStart = classifyLeadingTriviaAndGetTokenStart(token); + var tokenWidth = token.end - tokenStart; + ts.Debug.assert(tokenWidth >= 0); + if (tokenWidth > 0) { var type = classifyTokenType(token.kind, token); if (type) { - pushClassification(token.getStart(), token.getWidth(), type); + pushClassification(tokenStart, tokenWidth, type); } } } @@ -40471,16 +42428,16 @@ var ts; if (token) { if (tokenKind === 53 /* EqualsToken */) { // the '=' in a variable declaration is special cased here. - if (token.parent.kind === 199 /* VariableDeclaration */ || - token.parent.kind === 133 /* PropertyDeclaration */ || - token.parent.kind === 130 /* Parameter */) { + if (token.parent.kind === 201 /* VariableDeclaration */ || + token.parent.kind === 134 /* PropertyDeclaration */ || + token.parent.kind === 131 /* Parameter */) { return 5 /* operator */; } } - if (token.parent.kind === 170 /* BinaryExpression */ || - token.parent.kind === 168 /* PrefixUnaryExpression */ || - token.parent.kind === 169 /* PostfixUnaryExpression */ || - token.parent.kind === 171 /* ConditionalExpression */) { + if (token.parent.kind === 172 /* BinaryExpression */ || + token.parent.kind === 170 /* PrefixUnaryExpression */ || + token.parent.kind === 171 /* PostfixUnaryExpression */ || + token.parent.kind === 173 /* ConditionalExpression */) { return 5 /* operator */; } } @@ -40503,32 +42460,32 @@ var ts; else if (tokenKind === 65 /* Identifier */) { if (token) { switch (token.parent.kind) { - case 202 /* ClassDeclaration */: + case 204 /* ClassDeclaration */: if (token.parent.name === token) { return 11 /* className */; } return; - case 129 /* TypeParameter */: + case 130 /* TypeParameter */: if (token.parent.name === token) { return 15 /* typeParameterName */; } return; - case 203 /* InterfaceDeclaration */: + case 205 /* InterfaceDeclaration */: if (token.parent.name === token) { return 13 /* interfaceName */; } return; - case 205 /* EnumDeclaration */: + case 207 /* EnumDeclaration */: if (token.parent.name === token) { return 12 /* enumName */; } return; - case 206 /* ModuleDeclaration */: + case 208 /* ModuleDeclaration */: if (token.parent.name === token) { return 14 /* moduleName */; } return; - case 130 /* Parameter */: + case 131 /* Parameter */: if (token.parent.name === token) { return 17 /* parameterName */; } @@ -40539,11 +42496,14 @@ var ts; } } function processElement(element) { + if (!element) { + return; + } // Ignore nodes that don't intersect the original span to classify. - if (ts.textSpanIntersectsWith(span, element.getFullStart(), element.getFullWidth())) { - var children = element.getChildren(); - for (var _i = 0; _i < children.length; _i++) { - var child = children[_i]; + if (ts.decodedTextSpanIntersectsWith(spanStart, spanLength, element.pos, element.getFullWidth())) { + var children = element.getChildren(sourceFile); + for (var i = 0, n = children.length; i < n; i++) { + var child = children[i]; if (ts.isToken(child)) { classifyToken(child); } @@ -40870,7 +42830,7 @@ var ts; // 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 === 220 /* ExternalModuleReference */ || + node.parent.kind === 222 /* ExternalModuleReference */ || isArgumentOfElementAccessExpression(node)) { nameTable[node.text] = node.text; } @@ -40883,7 +42843,7 @@ var ts; function isArgumentOfElementAccessExpression(node) { return node && node.parent && - node.parent.kind === 157 /* ElementAccessExpression */ && + node.parent.kind === 159 /* ElementAccessExpression */ && node.parent.argumentExpression === node; } /// Classifier @@ -40931,7 +42891,7 @@ var ts; function canFollow(keyword1, keyword2) { if (ts.isAccessibilityModifier(keyword1)) { if (keyword2 === 116 /* GetKeyword */ || - keyword2 === 121 /* SetKeyword */ || + keyword2 === 122 /* SetKeyword */ || keyword2 === 114 /* ConstructorKeyword */ || keyword2 === 109 /* StaticKeyword */) { // Allow things like "public get", "public constructor" and "public static". @@ -40952,7 +42912,7 @@ var ts; var lastEnd = 0; for (var i = 0, n = dense.length; i < n; i += 3) { var start = dense[i]; - var length_1 = dense[i + 1]; + var length_2 = dense[i + 1]; var type = dense[i + 2]; // Make a whitespace entry between the last item and this one. if (lastEnd >= 0) { @@ -40961,8 +42921,8 @@ var ts; entries.push({ length: whitespaceLength_1, classification: TokenClass.Whitespace }); } } - entries.push({ length: length_1, classification: convertClassification(type) }); - lastEnd = start + length_1; + entries.push({ length: length_2, classification: convertClassification(type) }); + lastEnd = start + length_2; } var whitespaceLength = text.length - lastEnd; if (whitespaceLength > 0) { @@ -41090,10 +43050,10 @@ var ts; angleBracketStack--; } else if (token === 112 /* AnyKeyword */ || - token === 122 /* StringKeyword */ || - token === 120 /* NumberKeyword */ || + token === 123 /* StringKeyword */ || + token === 121 /* NumberKeyword */ || token === 113 /* BooleanKeyword */ || - token === 123 /* SymbolKeyword */) { + token === 124 /* SymbolKeyword */) { if (angleBracketStack > 0 && !syntacticClassifierAbsent) { // If it looks like we're could be in something generic, don't classify this // as a keyword. We may just get overwritten by the syntactic classifier, @@ -41264,7 +43224,7 @@ var ts; } } function isKeyword(token) { - return token >= 66 /* FirstKeyword */ && token <= 126 /* LastKeyword */; + return token >= 66 /* FirstKeyword */ && token <= 127 /* LastKeyword */; } function classFromKind(token) { if (isKeyword(token)) { @@ -41322,7 +43282,7 @@ var ts; getNodeConstructor: function (kind) { function Node() { } - var proto = kind === 228 /* SourceFile */ ? new SourceFileObject() : new NodeObject(); + var proto = kind === 230 /* SourceFile */ ? new SourceFileObject() : new NodeObject(); proto.kind = kind; proto.pos = 0; proto.end = 0; @@ -41392,125 +43352,125 @@ var ts; function spanInNode(node) { if (node) { if (ts.isExpression(node)) { - if (node.parent.kind === 185 /* DoStatement */) { + if (node.parent.kind === 187 /* DoStatement */) { // Set span as if on while keyword return spanInPreviousNode(node); } - if (node.parent.kind === 187 /* ForStatement */) { + if (node.parent.kind === 189 /* ForStatement */) { // For now lets set the span on this expression, fix it later return textSpan(node); } - if (node.parent.kind === 170 /* BinaryExpression */ && node.parent.operatorToken.kind === 23 /* CommaToken */) { + if (node.parent.kind === 172 /* BinaryExpression */ && node.parent.operatorToken.kind === 23 /* CommaToken */) { // if this is comma expression, the breakpoint is possible in this expression return textSpan(node); } - if (node.parent.kind == 164 /* ArrowFunction */ && node.parent.body == node) { + if (node.parent.kind === 166 /* ArrowFunction */ && node.parent.body === node) { // If this is body of arrow function, it is allowed to have the breakpoint return textSpan(node); } } switch (node.kind) { - case 181 /* VariableStatement */: + case 183 /* VariableStatement */: // Span on first variable declaration return spanInVariableDeclaration(node.declarationList.declarations[0]); - case 199 /* VariableDeclaration */: - case 133 /* PropertyDeclaration */: - case 132 /* PropertySignature */: + case 201 /* VariableDeclaration */: + case 134 /* PropertyDeclaration */: + case 133 /* PropertySignature */: return spanInVariableDeclaration(node); - case 130 /* Parameter */: + case 131 /* Parameter */: return spanInParameterDeclaration(node); - case 201 /* FunctionDeclaration */: - case 135 /* MethodDeclaration */: - case 134 /* MethodSignature */: - case 137 /* GetAccessor */: - case 138 /* SetAccessor */: - case 136 /* Constructor */: - case 163 /* FunctionExpression */: - case 164 /* ArrowFunction */: + case 203 /* FunctionDeclaration */: + case 136 /* MethodDeclaration */: + case 135 /* MethodSignature */: + case 138 /* GetAccessor */: + case 139 /* SetAccessor */: + case 137 /* Constructor */: + case 165 /* FunctionExpression */: + case 166 /* ArrowFunction */: return spanInFunctionDeclaration(node); - case 180 /* Block */: + case 182 /* Block */: if (ts.isFunctionBlock(node)) { return spanInFunctionBlock(node); } // Fall through - case 207 /* ModuleBlock */: + case 209 /* ModuleBlock */: return spanInBlock(node); - case 224 /* CatchClause */: + case 226 /* CatchClause */: return spanInBlock(node.block); - case 183 /* ExpressionStatement */: + case 185 /* ExpressionStatement */: // span on the expression return textSpan(node.expression); - case 192 /* ReturnStatement */: + case 194 /* ReturnStatement */: // span on return keyword and expression if present return textSpan(node.getChildAt(0), node.expression); - case 186 /* WhileStatement */: + case 188 /* WhileStatement */: // Span on while(...) return textSpan(node, ts.findNextToken(node.expression, node)); - case 185 /* DoStatement */: + case 187 /* DoStatement */: // span in statement of the do statement return spanInNode(node.statement); - case 198 /* DebuggerStatement */: + case 200 /* DebuggerStatement */: // span on debugger keyword return textSpan(node.getChildAt(0)); - case 184 /* IfStatement */: + case 186 /* IfStatement */: // set on if(..) span return textSpan(node, ts.findNextToken(node.expression, node)); - case 195 /* LabeledStatement */: + case 197 /* LabeledStatement */: // span in statement return spanInNode(node.statement); - case 191 /* BreakStatement */: - case 190 /* ContinueStatement */: + case 193 /* BreakStatement */: + case 192 /* ContinueStatement */: // On break or continue keyword and label if present return textSpan(node.getChildAt(0), node.label); - case 187 /* ForStatement */: + case 189 /* ForStatement */: return spanInForStatement(node); - case 188 /* ForInStatement */: - case 189 /* ForOfStatement */: + case 190 /* ForInStatement */: + case 191 /* ForOfStatement */: // span on for (a in ...) return textSpan(node, ts.findNextToken(node.expression, node)); - case 194 /* SwitchStatement */: + case 196 /* SwitchStatement */: // span on switch(...) return textSpan(node, ts.findNextToken(node.expression, node)); - case 221 /* CaseClause */: - case 222 /* DefaultClause */: + case 223 /* CaseClause */: + case 224 /* DefaultClause */: // span in first statement of the clause return spanInNode(node.statements[0]); - case 197 /* TryStatement */: + case 199 /* TryStatement */: // span in try block return spanInBlock(node.tryBlock); - case 196 /* ThrowStatement */: + case 198 /* ThrowStatement */: // span in throw ... return textSpan(node, node.expression); - case 215 /* ExportAssignment */: + case 217 /* ExportAssignment */: // span on export = id return textSpan(node, node.expression); - case 209 /* ImportEqualsDeclaration */: + case 211 /* ImportEqualsDeclaration */: // import statement without including semicolon return textSpan(node, node.moduleReference); - case 210 /* ImportDeclaration */: + case 212 /* ImportDeclaration */: // import statement without including semicolon return textSpan(node, node.moduleSpecifier); - case 216 /* ExportDeclaration */: + case 218 /* ExportDeclaration */: // import statement without including semicolon return textSpan(node, node.moduleSpecifier); - case 206 /* ModuleDeclaration */: + case 208 /* ModuleDeclaration */: // span on complete module if it is instantiated if (ts.getModuleInstanceState(node) !== 1 /* Instantiated */) { return undefined; } - case 202 /* ClassDeclaration */: - case 205 /* EnumDeclaration */: - case 227 /* EnumMember */: - case 158 /* CallExpression */: - case 159 /* NewExpression */: + case 204 /* ClassDeclaration */: + case 207 /* EnumDeclaration */: + case 229 /* EnumMember */: + case 160 /* CallExpression */: + case 161 /* NewExpression */: // span on complete node return textSpan(node); - case 193 /* WithStatement */: + case 195 /* WithStatement */: // span in statement return spanInNode(node.statement); // No breakpoint in interface, type alias - case 203 /* InterfaceDeclaration */: - case 204 /* TypeAliasDeclaration */: + case 205 /* InterfaceDeclaration */: + case 206 /* TypeAliasDeclaration */: return undefined; // Tokens: case 22 /* SemicolonToken */: @@ -41540,11 +43500,11 @@ var ts; return spanInNextNode(node); default: // If this is name of property assignment, set breakpoint in the initializer - if (node.parent.kind === 225 /* PropertyAssignment */ && node.parent.name === node) { + if (node.parent.kind === 227 /* PropertyAssignment */ && node.parent.name === node) { return spanInNode(node.parent.initializer); } // Breakpoint in type assertion goes to its operand - if (node.parent.kind === 161 /* TypeAssertionExpression */ && node.parent.type === node) { + if (node.parent.kind === 163 /* TypeAssertionExpression */ && node.parent.type === node) { return spanInNode(node.parent.expression); } // return type of function go to previous token @@ -41557,12 +43517,12 @@ var ts; } function spanInVariableDeclaration(variableDeclaration) { // If declaration of for in statement, just set the span in parent - if (variableDeclaration.parent.parent.kind === 188 /* ForInStatement */ || - variableDeclaration.parent.parent.kind === 189 /* ForOfStatement */) { + if (variableDeclaration.parent.parent.kind === 190 /* ForInStatement */ || + variableDeclaration.parent.parent.kind === 191 /* ForOfStatement */) { return spanInNode(variableDeclaration.parent.parent); } - var isParentVariableStatement = variableDeclaration.parent.parent.kind === 181 /* VariableStatement */; - var isDeclarationOfForStatement = variableDeclaration.parent.parent.kind === 187 /* ForStatement */ && ts.contains(variableDeclaration.parent.parent.initializer.declarations, variableDeclaration); + var isParentVariableStatement = variableDeclaration.parent.parent.kind === 183 /* VariableStatement */; + var isDeclarationOfForStatement = variableDeclaration.parent.parent.kind === 189 /* ForStatement */ && ts.contains(variableDeclaration.parent.parent.initializer.declarations, variableDeclaration); var declarations = isParentVariableStatement ? variableDeclaration.parent.parent.declarationList.declarations : isDeclarationOfForStatement @@ -41616,7 +43576,7 @@ var ts; } function canFunctionHaveSpanInWholeDeclaration(functionDeclaration) { return !!(functionDeclaration.flags & 1 /* Export */) || - (functionDeclaration.parent.kind === 202 /* ClassDeclaration */ && functionDeclaration.kind !== 136 /* Constructor */); + (functionDeclaration.parent.kind === 204 /* ClassDeclaration */ && functionDeclaration.kind !== 137 /* Constructor */); } function spanInFunctionDeclaration(functionDeclaration) { // No breakpoints in the function signature @@ -41639,18 +43599,18 @@ var ts; } function spanInBlock(block) { switch (block.parent.kind) { - case 206 /* ModuleDeclaration */: + case 208 /* ModuleDeclaration */: if (ts.getModuleInstanceState(block.parent) !== 1 /* Instantiated */) { return undefined; } // Set on parent if on same line otherwise on first statement - case 186 /* WhileStatement */: - case 184 /* IfStatement */: - case 188 /* ForInStatement */: - case 189 /* ForOfStatement */: + case 188 /* WhileStatement */: + case 186 /* IfStatement */: + case 190 /* ForInStatement */: + case 191 /* ForOfStatement */: return spanInNodeIfStartsOnSameLine(block.parent, block.statements[0]); // Set span on previous token if it starts on same line otherwise on the first statement of the block - case 187 /* ForStatement */: + case 189 /* ForStatement */: return spanInNodeIfStartsOnSameLine(ts.findPrecedingToken(block.pos, sourceFile, block.parent), block.statements[0]); } // Default action is to set on first statement @@ -41658,7 +43618,7 @@ var ts; } function spanInForStatement(forStatement) { if (forStatement.initializer) { - if (forStatement.initializer.kind === 200 /* VariableDeclarationList */) { + if (forStatement.initializer.kind === 202 /* VariableDeclarationList */) { var variableDeclarationList = forStatement.initializer; if (variableDeclarationList.declarations.length > 0) { return spanInNode(variableDeclarationList.declarations[0]); @@ -41678,13 +43638,13 @@ var ts; // Tokens: function spanInOpenBraceToken(node) { switch (node.parent.kind) { - case 205 /* EnumDeclaration */: + case 207 /* EnumDeclaration */: var enumDeclaration = node.parent; return spanInNodeIfStartsOnSameLine(ts.findPrecedingToken(node.pos, sourceFile, node.parent), enumDeclaration.members.length ? enumDeclaration.members[0] : enumDeclaration.getLastToken(sourceFile)); - case 202 /* ClassDeclaration */: + case 204 /* ClassDeclaration */: var classDeclaration = node.parent; return spanInNodeIfStartsOnSameLine(ts.findPrecedingToken(node.pos, sourceFile, node.parent), classDeclaration.members.length ? classDeclaration.members[0] : classDeclaration.getLastToken(sourceFile)); - case 208 /* CaseBlock */: + case 210 /* CaseBlock */: return spanInNodeIfStartsOnSameLine(node.parent.parent, node.parent.clauses[0]); } // Default to parent node @@ -41692,25 +43652,25 @@ var ts; } function spanInCloseBraceToken(node) { switch (node.parent.kind) { - case 207 /* ModuleBlock */: + case 209 /* ModuleBlock */: // If this is not instantiated module block no bp span if (ts.getModuleInstanceState(node.parent.parent) !== 1 /* Instantiated */) { return undefined; } - case 205 /* EnumDeclaration */: - case 202 /* ClassDeclaration */: + case 207 /* EnumDeclaration */: + case 204 /* ClassDeclaration */: // Span on close brace token return textSpan(node); - case 180 /* Block */: + case 182 /* Block */: if (ts.isFunctionBlock(node.parent)) { // Span on close brace token return textSpan(node); } // fall through. - case 224 /* CatchClause */: + case 226 /* CatchClause */: return spanInNode(ts.lastOrUndefined(node.parent.statements)); ; - case 208 /* CaseBlock */: + case 210 /* CaseBlock */: // breakpoint in last statement of the last clause var caseBlock = node.parent; var lastClause = ts.lastOrUndefined(caseBlock.clauses); @@ -41724,7 +43684,7 @@ var ts; } } function spanInOpenParenToken(node) { - if (node.parent.kind === 185 /* DoStatement */) { + if (node.parent.kind === 187 /* DoStatement */) { // Go to while keyword and do action instead return spanInPreviousNode(node); } @@ -41734,17 +43694,17 @@ var ts; function spanInCloseParenToken(node) { // Is this close paren token of parameter list, set span in previous token switch (node.parent.kind) { - case 163 /* FunctionExpression */: - case 201 /* FunctionDeclaration */: - case 164 /* ArrowFunction */: - case 135 /* MethodDeclaration */: - case 134 /* MethodSignature */: - case 137 /* GetAccessor */: - case 138 /* SetAccessor */: - case 136 /* Constructor */: - case 186 /* WhileStatement */: - case 185 /* DoStatement */: - case 187 /* ForStatement */: + case 165 /* FunctionExpression */: + case 203 /* FunctionDeclaration */: + case 166 /* ArrowFunction */: + case 136 /* MethodDeclaration */: + case 135 /* MethodSignature */: + case 138 /* GetAccessor */: + case 139 /* SetAccessor */: + case 137 /* Constructor */: + case 188 /* WhileStatement */: + case 187 /* DoStatement */: + case 189 /* ForStatement */: return spanInPreviousNode(node); // Default to parent node default: @@ -41755,19 +43715,19 @@ var ts; } function spanInColonToken(node) { // Is this : specifying return annotation of the function declaration - if (ts.isFunctionLike(node.parent) || node.parent.kind === 225 /* PropertyAssignment */) { + if (ts.isFunctionLike(node.parent) || node.parent.kind === 227 /* PropertyAssignment */) { return spanInPreviousNode(node); } return spanInNode(node.parent); } function spanInGreaterThanOrLessThanToken(node) { - if (node.parent.kind === 161 /* TypeAssertionExpression */) { + if (node.parent.kind === 163 /* TypeAssertionExpression */) { return spanInNode(node.parent.expression); } return spanInNode(node.parent); } function spanInWhileKeyword(node) { - if (node.parent.kind === 185 /* DoStatement */) { + if (node.parent.kind === 187 /* DoStatement */) { // Set span on while expression return textSpan(node, ts.findNextToken(node.parent.expression, node.parent)); } @@ -41818,6 +43778,7 @@ var ts; ScriptSnapshotShimAdapter.prototype.getChangeRange = function (oldSnapshot) { var oldSnapshotShim = oldSnapshot; var encoded = this.scriptSnapshotShim.getChangeRange(oldSnapshotShim.scriptSnapshotShim); + // TODO: should this be '==='? if (encoded == null) { return null; } @@ -41829,12 +43790,18 @@ var ts; var LanguageServiceShimHostAdapter = (function () { function LanguageServiceShimHostAdapter(shimHost) { this.shimHost = shimHost; + this.loggingEnabled = false; + this.tracingEnabled = false; } LanguageServiceShimHostAdapter.prototype.log = function (s) { - this.shimHost.log(s); + if (this.loggingEnabled) { + this.shimHost.log(s); + } }; LanguageServiceShimHostAdapter.prototype.trace = function (s) { - this.shimHost.trace(s); + if (this.tracingEnabled) { + this.shimHost.trace(s); + } }; LanguageServiceShimHostAdapter.prototype.error = function (s) { this.shimHost.error(s); @@ -41846,8 +43813,12 @@ var ts; } return this.shimHost.getProjectVersion(); }; + LanguageServiceShimHostAdapter.prototype.useCaseSensitiveFileNames = function () { + return this.shimHost.useCaseSensitiveFileNames ? this.shimHost.useCaseSensitiveFileNames() : false; + }; LanguageServiceShimHostAdapter.prototype.getCompilationSettings = function () { var settingsJson = this.shimHost.getCompilationSettings(); + // TODO: should this be '==='? if (settingsJson == null || settingsJson == "") { throw Error("LanguageServiceShimHostAdapter.getCompilationSettings: empty compilationSettings"); return null; @@ -41913,13 +43884,13 @@ var ts; return CoreServicesShimHostAdapter; })(); ts.CoreServicesShimHostAdapter = CoreServicesShimHostAdapter; - function simpleForwardCall(logger, actionDescription, action, noPerfLogging) { - if (!noPerfLogging) { + function simpleForwardCall(logger, actionDescription, action, logPerformance) { + if (logPerformance) { logger.log(actionDescription); var start = Date.now(); } var result = action(); - if (!noPerfLogging) { + if (logPerformance) { var end = Date.now(); logger.log(actionDescription + " completed in " + (end - start) + " msec"); if (typeof (result) === "string") { @@ -41932,9 +43903,9 @@ var ts; } return result; } - function forwardJSONCall(logger, actionDescription, action, noPerfLogging) { + function forwardJSONCall(logger, actionDescription, action, logPerformance) { try { - var result = simpleForwardCall(logger, actionDescription, action, noPerfLogging); + var result = simpleForwardCall(logger, actionDescription, action, logPerformance); return JSON.stringify({ result: result }); } catch (err) { @@ -41976,10 +43947,11 @@ var ts; _super.call(this, factory); this.host = host; this.languageService = languageService; + this.logPerformance = false; this.logger = this.host; } LanguageServiceShimObject.prototype.forwardJSONCall = function (actionDescription, action) { - return forwardJSONCall(this.logger, actionDescription, action, false); + return forwardJSONCall(this.logger, actionDescription, action, this.logPerformance); }; /// DISPOSE /** @@ -42286,12 +44258,12 @@ var ts; function ClassifierShimObject(factory, logger) { _super.call(this, factory); this.logger = logger; + this.logPerformance = false; this.classifier = ts.createClassifier(); } ClassifierShimObject.prototype.getEncodedLexicalClassifications = function (text, lexState, syntacticClassifierAbsent) { var _this = this; - return forwardJSONCall(this.logger, "getEncodedLexicalClassifications", function () { return convertClassifications(_this.classifier.getEncodedLexicalClassifications(text, lexState, syntacticClassifierAbsent)); }, - /*noPerfLogging:*/ true); + return forwardJSONCall(this.logger, "getEncodedLexicalClassifications", function () { return convertClassifications(_this.classifier.getEncodedLexicalClassifications(text, lexState, syntacticClassifierAbsent)); }, this.logPerformance); }; /// COLORIZATION ClassifierShimObject.prototype.getClassificationsForLine = function (text, lexState, classifyKeywordsInGenerics) { @@ -42313,9 +44285,10 @@ var ts; _super.call(this, factory); this.logger = logger; this.host = host; + this.logPerformance = false; } CoreServicesShimObject.prototype.forwardJSONCall = function (actionDescription, action) { - return forwardJSONCall(this.logger, actionDescription, action, false); + return forwardJSONCall(this.logger, actionDescription, action, this.logPerformance); }; CoreServicesShimObject.prototype.getPreProcessedFileInfo = function (fileName, sourceTextSnapshot) { return this.forwardJSONCall("getPreProcessedFileInfo('" + fileName + "')", function () { @@ -42372,7 +44345,6 @@ var ts; var TypeScriptServicesFactory = (function () { function TypeScriptServicesFactory() { this._shims = []; - this.documentRegistry = ts.createDocumentRegistry(); } /* * Returns script API version. @@ -42382,6 +44354,9 @@ var ts; }; TypeScriptServicesFactory.prototype.createLanguageServiceShim = function (host) { try { + if (this.documentRegistry === undefined) { + this.documentRegistry = ts.createDocumentRegistry(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames()); + } var hostAdapter = new LanguageServiceShimHostAdapter(host); var languageService = ts.createLanguageService(hostAdapter, this.documentRegistry); return new LanguageServiceShimObject(this, host, languageService); @@ -42444,4 +44419,4 @@ var TypeScript; })(Services = TypeScript.Services || (TypeScript.Services = {})); })(TypeScript || (TypeScript = {})); /* @internal */ -var toolsVersion = "1.4"; +var toolsVersion = "1.5"; diff --git a/bin/typescriptServices.d.ts b/bin/typescriptServices.d.ts index f03a7a00e46..da6d55bfd80 100644 --- a/bin/typescriptServices.d.ts +++ b/bin/typescriptServices.d.ts @@ -13,10 +13,17 @@ See the Apache Version 2.0 License for specific language governing permissions and limitations under the License. ***************************************************************************** */ -declare module ts { +declare namespace ts { interface Map { [index: string]: T; } + interface FileMap { + get(fileName: string): T; + set(fileName: string, value: T): void; + contains(fileName: string): boolean; + remove(fileName: string): void; + forEachValue(f: (v: T) => void): void; + } interface TextRange { pos: number; end: number; @@ -139,134 +146,158 @@ declare module ts { ConstructorKeyword = 114, DeclareKeyword = 115, GetKeyword = 116, - ModuleKeyword = 117, - NamespaceKeyword = 118, - RequireKeyword = 119, - NumberKeyword = 120, - SetKeyword = 121, - StringKeyword = 122, - SymbolKeyword = 123, - TypeKeyword = 124, - FromKeyword = 125, - OfKeyword = 126, - QualifiedName = 127, - ComputedPropertyName = 128, - TypeParameter = 129, - Parameter = 130, - Decorator = 131, - PropertySignature = 132, - PropertyDeclaration = 133, - MethodSignature = 134, - MethodDeclaration = 135, - Constructor = 136, - GetAccessor = 137, - SetAccessor = 138, - CallSignature = 139, - ConstructSignature = 140, - IndexSignature = 141, - TypeReference = 142, - FunctionType = 143, - ConstructorType = 144, - TypeQuery = 145, - TypeLiteral = 146, - ArrayType = 147, - TupleType = 148, - UnionType = 149, - ParenthesizedType = 150, - ObjectBindingPattern = 151, - ArrayBindingPattern = 152, - BindingElement = 153, - ArrayLiteralExpression = 154, - ObjectLiteralExpression = 155, - PropertyAccessExpression = 156, - ElementAccessExpression = 157, - CallExpression = 158, - NewExpression = 159, - TaggedTemplateExpression = 160, - TypeAssertionExpression = 161, - ParenthesizedExpression = 162, - FunctionExpression = 163, - ArrowFunction = 164, - DeleteExpression = 165, - TypeOfExpression = 166, - VoidExpression = 167, - PrefixUnaryExpression = 168, - PostfixUnaryExpression = 169, - BinaryExpression = 170, - ConditionalExpression = 171, - TemplateExpression = 172, - YieldExpression = 173, - SpreadElementExpression = 174, - ClassExpression = 175, - OmittedExpression = 176, - ExpressionWithTypeArguments = 177, - TemplateSpan = 178, - SemicolonClassElement = 179, - Block = 180, - VariableStatement = 181, - EmptyStatement = 182, - ExpressionStatement = 183, - IfStatement = 184, - DoStatement = 185, - WhileStatement = 186, - ForStatement = 187, - ForInStatement = 188, - ForOfStatement = 189, - ContinueStatement = 190, - BreakStatement = 191, - ReturnStatement = 192, - WithStatement = 193, - SwitchStatement = 194, - LabeledStatement = 195, - ThrowStatement = 196, - TryStatement = 197, - DebuggerStatement = 198, - VariableDeclaration = 199, - VariableDeclarationList = 200, - FunctionDeclaration = 201, - ClassDeclaration = 202, - InterfaceDeclaration = 203, - TypeAliasDeclaration = 204, - EnumDeclaration = 205, - ModuleDeclaration = 206, - ModuleBlock = 207, - CaseBlock = 208, - ImportEqualsDeclaration = 209, - ImportDeclaration = 210, - ImportClause = 211, - NamespaceImport = 212, - NamedImports = 213, - ImportSpecifier = 214, - ExportAssignment = 215, - ExportDeclaration = 216, - NamedExports = 217, - ExportSpecifier = 218, - MissingDeclaration = 219, - ExternalModuleReference = 220, - CaseClause = 221, - DefaultClause = 222, - HeritageClause = 223, - CatchClause = 224, - PropertyAssignment = 225, - ShorthandPropertyAssignment = 226, - EnumMember = 227, - SourceFile = 228, - SyntaxList = 229, - Count = 230, + IsKeyword = 117, + ModuleKeyword = 118, + NamespaceKeyword = 119, + RequireKeyword = 120, + NumberKeyword = 121, + SetKeyword = 122, + StringKeyword = 123, + SymbolKeyword = 124, + TypeKeyword = 125, + FromKeyword = 126, + OfKeyword = 127, + QualifiedName = 128, + ComputedPropertyName = 129, + TypeParameter = 130, + Parameter = 131, + Decorator = 132, + PropertySignature = 133, + PropertyDeclaration = 134, + MethodSignature = 135, + MethodDeclaration = 136, + Constructor = 137, + GetAccessor = 138, + SetAccessor = 139, + CallSignature = 140, + ConstructSignature = 141, + IndexSignature = 142, + TypePredicate = 143, + TypeReference = 144, + FunctionType = 145, + ConstructorType = 146, + TypeQuery = 147, + TypeLiteral = 148, + ArrayType = 149, + TupleType = 150, + UnionType = 151, + ParenthesizedType = 152, + ObjectBindingPattern = 153, + ArrayBindingPattern = 154, + BindingElement = 155, + ArrayLiteralExpression = 156, + ObjectLiteralExpression = 157, + PropertyAccessExpression = 158, + ElementAccessExpression = 159, + CallExpression = 160, + NewExpression = 161, + TaggedTemplateExpression = 162, + TypeAssertionExpression = 163, + ParenthesizedExpression = 164, + FunctionExpression = 165, + ArrowFunction = 166, + DeleteExpression = 167, + TypeOfExpression = 168, + VoidExpression = 169, + PrefixUnaryExpression = 170, + PostfixUnaryExpression = 171, + BinaryExpression = 172, + ConditionalExpression = 173, + TemplateExpression = 174, + YieldExpression = 175, + SpreadElementExpression = 176, + ClassExpression = 177, + OmittedExpression = 178, + ExpressionWithTypeArguments = 179, + TemplateSpan = 180, + SemicolonClassElement = 181, + Block = 182, + VariableStatement = 183, + EmptyStatement = 184, + ExpressionStatement = 185, + IfStatement = 186, + DoStatement = 187, + WhileStatement = 188, + ForStatement = 189, + ForInStatement = 190, + ForOfStatement = 191, + ContinueStatement = 192, + BreakStatement = 193, + ReturnStatement = 194, + WithStatement = 195, + SwitchStatement = 196, + LabeledStatement = 197, + ThrowStatement = 198, + TryStatement = 199, + DebuggerStatement = 200, + VariableDeclaration = 201, + VariableDeclarationList = 202, + FunctionDeclaration = 203, + ClassDeclaration = 204, + InterfaceDeclaration = 205, + TypeAliasDeclaration = 206, + EnumDeclaration = 207, + ModuleDeclaration = 208, + ModuleBlock = 209, + CaseBlock = 210, + ImportEqualsDeclaration = 211, + ImportDeclaration = 212, + ImportClause = 213, + NamespaceImport = 214, + NamedImports = 215, + ImportSpecifier = 216, + ExportAssignment = 217, + ExportDeclaration = 218, + NamedExports = 219, + ExportSpecifier = 220, + MissingDeclaration = 221, + ExternalModuleReference = 222, + CaseClause = 223, + DefaultClause = 224, + HeritageClause = 225, + CatchClause = 226, + PropertyAssignment = 227, + ShorthandPropertyAssignment = 228, + EnumMember = 229, + SourceFile = 230, + JSDocTypeExpression = 231, + JSDocAllType = 232, + JSDocUnknownType = 233, + JSDocArrayType = 234, + JSDocUnionType = 235, + JSDocTupleType = 236, + JSDocNullableType = 237, + JSDocNonNullableType = 238, + JSDocRecordType = 239, + JSDocRecordMember = 240, + JSDocTypeReference = 241, + JSDocOptionalType = 242, + JSDocFunctionType = 243, + JSDocVariadicType = 244, + JSDocConstructorType = 245, + JSDocThisType = 246, + JSDocComment = 247, + JSDocTag = 248, + JSDocParameterTag = 249, + JSDocReturnTag = 250, + JSDocTypeTag = 251, + JSDocTemplateTag = 252, + SyntaxList = 253, + Count = 254, FirstAssignment = 53, LastAssignment = 64, FirstReservedWord = 66, LastReservedWord = 101, FirstKeyword = 66, - LastKeyword = 126, + LastKeyword = 127, FirstFutureReservedWord = 102, LastFutureReservedWord = 110, - FirstTypeNode = 142, - LastTypeNode = 150, + FirstTypeNode = 144, + LastTypeNode = 152, FirstPunctuation = 14, LastPunctuation = 64, FirstToken = 0, - LastToken = 126, + LastToken = 127, FirstTriviaToken = 2, LastTriviaToken = 6, FirstLiteralToken = 7, @@ -275,7 +306,7 @@ declare module ts { LastTemplateToken = 13, FirstBinaryOperator = 24, LastBinaryOperator = 64, - FirstNode = 127, + FirstNode = 128, } const enum NodeFlags { Export = 1, @@ -436,6 +467,10 @@ declare module ts { typeName: EntityName; typeArguments?: NodeArray; } + interface TypePredicateNode extends TypeNode { + parameterName: Identifier; + type: TypeNode; + } interface TypeQueryNode extends TypeNode { exprName: EntityName; } @@ -495,7 +530,7 @@ declare module ts { } interface YieldExpression extends Expression { asteriskToken?: Node; - expression: Expression; + expression?: Expression; } interface BinaryExpression extends Expression { left: Expression; @@ -570,7 +605,7 @@ declare module ts { type: TypeNode; expression: UnaryExpression; } - interface Statement extends Node, ModuleElement { + interface Statement extends Node { _statementBrand: any; } interface Block extends Statement { @@ -650,9 +685,6 @@ declare module ts { variableDeclaration: VariableDeclaration; block: Block; } - interface ModuleElement extends Node { - _moduleElementBrand: any; - } interface ClassLikeDeclaration extends Declaration { name?: Identifier; typeParameters?: NodeArray; @@ -666,7 +698,7 @@ declare module ts { interface ClassElement extends Declaration { _classElementBrand: any; } - interface InterfaceDeclaration extends Declaration, ModuleElement { + interface InterfaceDeclaration extends Declaration, Statement { name: Identifier; typeParameters?: NodeArray; heritageClauses?: NodeArray; @@ -676,33 +708,34 @@ declare module ts { token: SyntaxKind; types?: NodeArray; } - interface TypeAliasDeclaration extends Declaration, ModuleElement { + interface TypeAliasDeclaration extends Declaration, Statement { name: Identifier; + typeParameters?: NodeArray; type: TypeNode; } interface EnumMember extends Declaration { name: DeclarationName; initializer?: Expression; } - interface EnumDeclaration extends Declaration, ModuleElement { + interface EnumDeclaration extends Declaration, Statement { name: Identifier; members: NodeArray; } - interface ModuleDeclaration extends Declaration, ModuleElement { + interface ModuleDeclaration extends Declaration, Statement { name: Identifier | LiteralExpression; body: ModuleBlock | ModuleDeclaration; } - interface ModuleBlock extends Node, ModuleElement { - statements: NodeArray; + interface ModuleBlock extends Node, Statement { + statements: NodeArray; } - interface ImportEqualsDeclaration extends Declaration, ModuleElement { + interface ImportEqualsDeclaration extends Declaration, Statement { name: Identifier; moduleReference: EntityName | ExternalModuleReference; } interface ExternalModuleReference extends Node { expression?: Expression; } - interface ImportDeclaration extends ModuleElement { + interface ImportDeclaration extends Statement { importClause?: ImportClause; moduleSpecifier: Expression; } @@ -713,7 +746,7 @@ declare module ts { interface NamespaceImport extends Declaration { name: Identifier; } - interface ExportDeclaration extends Declaration, ModuleElement { + interface ExportDeclaration extends Declaration, Statement { exportClause?: NamedExports; moduleSpecifier?: Expression; } @@ -728,7 +761,7 @@ declare module ts { } type ImportSpecifier = ImportOrExportSpecifier; type ExportSpecifier = ImportOrExportSpecifier; - interface ExportAssignment extends Declaration, ModuleElement { + interface ExportAssignment extends Declaration, Statement { isExportEquals?: boolean; expression: Expression; } @@ -739,8 +772,84 @@ declare module ts { hasTrailingNewLine?: boolean; kind: SyntaxKind; } + interface JSDocTypeExpression extends Node { + type: JSDocType; + } + interface JSDocType extends TypeNode { + _jsDocTypeBrand: any; + } + interface JSDocAllType extends JSDocType { + _JSDocAllTypeBrand: any; + } + interface JSDocUnknownType extends JSDocType { + _JSDocUnknownTypeBrand: any; + } + interface JSDocArrayType extends JSDocType { + elementType: JSDocType; + } + interface JSDocUnionType extends JSDocType { + types: NodeArray; + } + interface JSDocTupleType extends JSDocType { + types: NodeArray; + } + interface JSDocNonNullableType extends JSDocType { + type: JSDocType; + } + interface JSDocNullableType extends JSDocType { + type: JSDocType; + } + interface JSDocRecordType extends JSDocType, TypeLiteralNode { + members: NodeArray; + } + interface JSDocTypeReference extends JSDocType { + name: EntityName; + typeArguments: NodeArray; + } + interface JSDocOptionalType extends JSDocType { + type: JSDocType; + } + interface JSDocFunctionType extends JSDocType, SignatureDeclaration { + parameters: NodeArray; + type: JSDocType; + } + interface JSDocVariadicType extends JSDocType { + type: JSDocType; + } + interface JSDocConstructorType extends JSDocType { + type: JSDocType; + } + interface JSDocThisType extends JSDocType { + type: JSDocType; + } + interface JSDocRecordMember extends PropertyDeclaration { + name: Identifier | LiteralExpression; + type?: JSDocType; + } + interface JSDocComment extends Node { + tags: NodeArray; + } + interface JSDocTag extends Node { + atToken: Node; + tagName: Identifier; + } + interface JSDocTemplateTag extends JSDocTag { + typeParameters: NodeArray; + } + interface JSDocReturnTag extends JSDocTag { + typeExpression: JSDocTypeExpression; + } + interface JSDocTypeTag extends JSDocTag { + typeExpression: JSDocTypeExpression; + } + interface JSDocParameterTag extends JSDocTag { + preParameterName?: Identifier; + typeExpression?: JSDocTypeExpression; + postParameterName?: Identifier; + isBracketed: boolean; + } interface SourceFile extends Declaration { - statements: NodeArray; + statements: NodeArray; endOfFileToken: Node; fileName: string; text: string; @@ -748,8 +857,16 @@ declare module ts { path: string; name: string; }[]; - amdModuleName: string; + moduleName: string; referencedFiles: FileReference[]; + /** + * lib.d.ts should have a reference comment like + * + * /// + * + * If any other file has this comment, it signals not to include lib.d.ts + * because this containing file is intended to act as a default library. + */ hasNoDefaultLib: boolean; languageVersion: ScriptTarget; } @@ -759,7 +876,7 @@ declare module ts { getCurrentDirectory(): string; } interface ParseConfigHost { - readDirectory(rootDir: string, extension: string): string[]; + readDirectory(rootDir: string, extension: string, exclude: string[]): string[]; } interface WriteFileCallback { (fileName: string, data: string, writeByteOrderMark: boolean, onError?: (message: string) => void): void; @@ -780,8 +897,9 @@ declare module ts { * will be invoked when writing the JavaScript and declaration files. */ emit(targetSourceFile?: SourceFile, writeFile?: WriteFileCallback): EmitResult; - getSyntacticDiagnostics(sourceFile?: SourceFile): Diagnostic[]; + getOptionsDiagnostics(): Diagnostic[]; getGlobalDiagnostics(): Diagnostic[]; + getSyntacticDiagnostics(sourceFile?: SourceFile): Diagnostic[]; getSemanticDiagnostics(sourceFile?: SourceFile): Diagnostic[]; getDeclarationDiagnostics(sourceFile?: SourceFile): Diagnostic[]; /** @@ -900,7 +1018,13 @@ declare module ts { WriteTypeParametersOrArguments = 1, UseOnlyExternalAliasing = 2, } + interface TypePredicate { + parameterName: string; + parameterIndex: number; + type: Type; + } const enum SymbolFlags { + None = 0, FunctionScopedVariable = 1, BlockScopedVariable = 2, Property = 4, @@ -959,10 +1083,9 @@ declare module ts { AliasExcludes = 8388608, ModuleMember = 8914931, ExportHasLocal = 944, - HasLocals = 255504, HasExports = 1952, HasMembers = 6240, - IsContainer = 262128, + BlockScoped = 418, PropertyOrAccessor = 98308, Export = 7340032, } @@ -970,9 +1093,9 @@ declare module ts { flags: SymbolFlags; name: string; declarations?: Declaration[]; + valueDeclaration?: Declaration; members?: SymbolTable; exports?: SymbolTable; - valueDeclaration?: Declaration; } interface SymbolTable { [index: string]: Symbol; @@ -994,8 +1117,9 @@ declare module ts { Tuple = 8192, Union = 16384, Anonymous = 32768, - ObjectLiteral = 131072, - ESSymbol = 1048576, + Instantiated = 65536, + ObjectLiteral = 262144, + ESSymbol = 2097152, StringLike = 258, NumberLike = 132, ObjectType = 48128, @@ -1011,9 +1135,10 @@ declare module ts { } interface InterfaceType extends ObjectType { typeParameters: TypeParameter[]; - } - interface InterfaceTypeWithBaseTypes extends InterfaceType { - baseTypes: ObjectType[]; + outerTypeParameters: TypeParameter[]; + localTypeParameters: TypeParameter[]; + resolvedBaseConstructorType?: Type; + resolvedBaseTypes: ObjectType[]; } interface InterfaceTypeWithDeclaredMembers extends InterfaceType { declaredProperties: Symbol[]; @@ -1046,6 +1171,7 @@ declare module ts { declaration: SignatureDeclaration; typeParameters: TypeParameter[]; parameters: Symbol[]; + typePredicate?: TypePredicate; } const enum IndexKind { String = 0, @@ -1114,7 +1240,8 @@ declare module ts { target?: ScriptTarget; version?: boolean; watch?: boolean; - separateCompilation?: boolean; + isolatedModules?: boolean; + experimentalDecorators?: boolean; emitDecoratorMetadata?: boolean; [option: string]: string | number | boolean; } @@ -1166,7 +1293,7 @@ declare module ts { newLength: number; } } -declare module ts { +declare namespace ts { interface System { args: string[]; newLine: string; @@ -1181,7 +1308,7 @@ declare module ts { createDirectory(path: string): void; getExecutingFilePath(): string; getCurrentDirectory(): string; - readDirectory(path: string, extension?: string): string[]; + readDirectory(path: string, extension?: string, exclude?: string[]): string[]; getMemoryUsage?(): number; exit(exitCode?: number): void; } @@ -1190,7 +1317,7 @@ declare module ts { } var sys: System; } -declare module ts { +declare namespace ts { interface ErrorCallback { (message: DiagnosticMessage, length: number): void; } @@ -1222,14 +1349,13 @@ declare module ts { function getLineAndCharacterOfPosition(sourceFile: SourceFile, position: number): LineAndCharacter; function isWhiteSpace(ch: number): boolean; function isLineBreak(ch: number): boolean; + function couldStartTrivia(text: string, pos: number): boolean; function getLeadingCommentRanges(text: string, pos: number): CommentRange[]; function getTrailingCommentRanges(text: string, pos: number): CommentRange[]; function isIdentifierStart(ch: number, languageVersion: ScriptTarget): boolean; function isIdentifierPart(ch: number, languageVersion: ScriptTarget): boolean; - /** Creates a scanner over a (possibly unspecified) range of a piece of text. */ - function createScanner(languageVersion: ScriptTarget, skipTrivia: boolean, text?: string, onError?: ErrorCallback, start?: number, length?: number): Scanner; } -declare module ts { +declare namespace ts { function getDefaultLibFileName(options: CompilerOptions): string; function textSpanEnd(span: TextSpan): number; function textSpanIsEmpty(span: TextSpan): boolean; @@ -1239,6 +1365,7 @@ declare module ts { 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; @@ -1256,15 +1383,16 @@ declare module ts { * Vn. */ function collapseTextChangeRangesAcrossMultipleVersions(changes: TextChangeRange[]): TextChangeRange; + function getTypeParameterOwner(d: Declaration): Declaration; } -declare module ts { +declare namespace ts { function getNodeConstructor(kind: SyntaxKind): new () => Node; function createNode(kind: SyntaxKind): Node; function forEachChild(node: Node, cbNode: (node: Node) => T, cbNodeArray?: (nodes: Node[]) => T): T; function createSourceFile(fileName: string, sourceText: string, languageVersion: ScriptTarget, setParentNodes?: boolean): SourceFile; function updateSourceFile(sourceFile: SourceFile, newText: string, textChangeRange: TextChangeRange, aggressiveChecks?: boolean): SourceFile; } -declare module ts { +declare namespace ts { /** The version of the TypeScript compiler release */ const version: string; function findConfigFile(searchPath: string): string; @@ -1273,7 +1401,7 @@ declare module ts { function flattenDiagnosticMessageText(messageText: string | DiagnosticMessageChain, newLine: string): string; function createProgram(rootNames: string[], options: CompilerOptions, host?: CompilerHost): Program; } -declare module ts { +declare namespace ts { function parseCommandLine(commandLine: string[]): ParsedCommandLine; /** * Read tsconfig.json file @@ -1300,7 +1428,7 @@ declare module ts { */ function parseConfigFile(json: any, host: ParseConfigHost, basePath: string): ParsedCommandLine; } -declare module ts { +declare namespace ts { /** The version of the language service API */ let servicesVersion: string; interface Node { @@ -1390,6 +1518,7 @@ declare module ts { log?(s: string): void; trace?(s: string): void; error?(s: string): void; + useCaseSensitiveFileNames?(): boolean; } interface LanguageService { cleanupSemanticCache(): void; @@ -1812,6 +1941,7 @@ declare module ts { static typeParameterName: string; static typeAliasName: string; static parameterName: string; + static docCommentTagName: string; } const enum ClassificationType { comment = 1, @@ -1831,6 +1961,7 @@ declare module ts { typeParameterName = 15, typeAliasName = 16, parameterName = 17, + docCommentTagName = 18, } interface DisplayPartsSymbolWriter extends SymbolWriter { displayParts(): SymbolDisplayPart[]; @@ -1846,11 +1977,11 @@ declare module ts { isCancellationRequested(): boolean; throwIfCancellationRequested(): void; } - function transpile(input: string, compilerOptions?: CompilerOptions, fileName?: string, diagnostics?: Diagnostic[]): string; + function transpile(input: string, compilerOptions?: CompilerOptions, fileName?: string, diagnostics?: Diagnostic[], moduleName?: string): string; function createLanguageServiceSourceFile(fileName: string, scriptSnapshot: IScriptSnapshot, scriptTarget: ScriptTarget, version: string, setNodeParents: boolean): SourceFile; let disableIncrementalParsing: boolean; function updateLanguageServiceSourceFile(sourceFile: SourceFile, scriptSnapshot: IScriptSnapshot, version: string, textChangeRange: TextChangeRange, aggressiveChecks?: boolean): SourceFile; - function createDocumentRegistry(): DocumentRegistry; + function createDocumentRegistry(useCaseSensitiveFileNames?: boolean): DocumentRegistry; function preProcessFile(sourceText: string, readImportFiles?: boolean): PreProcessedFileInfo; function createLanguageService(host: LanguageServiceHost, documentRegistry?: DocumentRegistry): LanguageService; function createClassifier(): Classifier; diff --git a/bin/typescriptServices.js b/bin/typescriptServices.js index 4cab75bfcb6..6989f225452 100644 --- a/bin/typescriptServices.js +++ b/bin/typescriptServices.js @@ -144,151 +144,178 @@ var ts; SyntaxKind[SyntaxKind["ConstructorKeyword"] = 114] = "ConstructorKeyword"; SyntaxKind[SyntaxKind["DeclareKeyword"] = 115] = "DeclareKeyword"; SyntaxKind[SyntaxKind["GetKeyword"] = 116] = "GetKeyword"; - SyntaxKind[SyntaxKind["ModuleKeyword"] = 117] = "ModuleKeyword"; - SyntaxKind[SyntaxKind["NamespaceKeyword"] = 118] = "NamespaceKeyword"; - SyntaxKind[SyntaxKind["RequireKeyword"] = 119] = "RequireKeyword"; - SyntaxKind[SyntaxKind["NumberKeyword"] = 120] = "NumberKeyword"; - SyntaxKind[SyntaxKind["SetKeyword"] = 121] = "SetKeyword"; - SyntaxKind[SyntaxKind["StringKeyword"] = 122] = "StringKeyword"; - SyntaxKind[SyntaxKind["SymbolKeyword"] = 123] = "SymbolKeyword"; - SyntaxKind[SyntaxKind["TypeKeyword"] = 124] = "TypeKeyword"; - SyntaxKind[SyntaxKind["FromKeyword"] = 125] = "FromKeyword"; - SyntaxKind[SyntaxKind["OfKeyword"] = 126] = "OfKeyword"; + SyntaxKind[SyntaxKind["IsKeyword"] = 117] = "IsKeyword"; + SyntaxKind[SyntaxKind["ModuleKeyword"] = 118] = "ModuleKeyword"; + SyntaxKind[SyntaxKind["NamespaceKeyword"] = 119] = "NamespaceKeyword"; + SyntaxKind[SyntaxKind["RequireKeyword"] = 120] = "RequireKeyword"; + SyntaxKind[SyntaxKind["NumberKeyword"] = 121] = "NumberKeyword"; + SyntaxKind[SyntaxKind["SetKeyword"] = 122] = "SetKeyword"; + SyntaxKind[SyntaxKind["StringKeyword"] = 123] = "StringKeyword"; + SyntaxKind[SyntaxKind["SymbolKeyword"] = 124] = "SymbolKeyword"; + SyntaxKind[SyntaxKind["TypeKeyword"] = 125] = "TypeKeyword"; + SyntaxKind[SyntaxKind["FromKeyword"] = 126] = "FromKeyword"; + SyntaxKind[SyntaxKind["OfKeyword"] = 127] = "OfKeyword"; // Parse tree nodes // Names - SyntaxKind[SyntaxKind["QualifiedName"] = 127] = "QualifiedName"; - SyntaxKind[SyntaxKind["ComputedPropertyName"] = 128] = "ComputedPropertyName"; + SyntaxKind[SyntaxKind["QualifiedName"] = 128] = "QualifiedName"; + SyntaxKind[SyntaxKind["ComputedPropertyName"] = 129] = "ComputedPropertyName"; // Signature elements - SyntaxKind[SyntaxKind["TypeParameter"] = 129] = "TypeParameter"; - SyntaxKind[SyntaxKind["Parameter"] = 130] = "Parameter"; - SyntaxKind[SyntaxKind["Decorator"] = 131] = "Decorator"; + SyntaxKind[SyntaxKind["TypeParameter"] = 130] = "TypeParameter"; + SyntaxKind[SyntaxKind["Parameter"] = 131] = "Parameter"; + SyntaxKind[SyntaxKind["Decorator"] = 132] = "Decorator"; // TypeMember - SyntaxKind[SyntaxKind["PropertySignature"] = 132] = "PropertySignature"; - SyntaxKind[SyntaxKind["PropertyDeclaration"] = 133] = "PropertyDeclaration"; - SyntaxKind[SyntaxKind["MethodSignature"] = 134] = "MethodSignature"; - SyntaxKind[SyntaxKind["MethodDeclaration"] = 135] = "MethodDeclaration"; - SyntaxKind[SyntaxKind["Constructor"] = 136] = "Constructor"; - SyntaxKind[SyntaxKind["GetAccessor"] = 137] = "GetAccessor"; - SyntaxKind[SyntaxKind["SetAccessor"] = 138] = "SetAccessor"; - SyntaxKind[SyntaxKind["CallSignature"] = 139] = "CallSignature"; - SyntaxKind[SyntaxKind["ConstructSignature"] = 140] = "ConstructSignature"; - SyntaxKind[SyntaxKind["IndexSignature"] = 141] = "IndexSignature"; + SyntaxKind[SyntaxKind["PropertySignature"] = 133] = "PropertySignature"; + SyntaxKind[SyntaxKind["PropertyDeclaration"] = 134] = "PropertyDeclaration"; + SyntaxKind[SyntaxKind["MethodSignature"] = 135] = "MethodSignature"; + SyntaxKind[SyntaxKind["MethodDeclaration"] = 136] = "MethodDeclaration"; + SyntaxKind[SyntaxKind["Constructor"] = 137] = "Constructor"; + SyntaxKind[SyntaxKind["GetAccessor"] = 138] = "GetAccessor"; + SyntaxKind[SyntaxKind["SetAccessor"] = 139] = "SetAccessor"; + SyntaxKind[SyntaxKind["CallSignature"] = 140] = "CallSignature"; + SyntaxKind[SyntaxKind["ConstructSignature"] = 141] = "ConstructSignature"; + SyntaxKind[SyntaxKind["IndexSignature"] = 142] = "IndexSignature"; // Type - SyntaxKind[SyntaxKind["TypeReference"] = 142] = "TypeReference"; - SyntaxKind[SyntaxKind["FunctionType"] = 143] = "FunctionType"; - SyntaxKind[SyntaxKind["ConstructorType"] = 144] = "ConstructorType"; - SyntaxKind[SyntaxKind["TypeQuery"] = 145] = "TypeQuery"; - SyntaxKind[SyntaxKind["TypeLiteral"] = 146] = "TypeLiteral"; - SyntaxKind[SyntaxKind["ArrayType"] = 147] = "ArrayType"; - SyntaxKind[SyntaxKind["TupleType"] = 148] = "TupleType"; - SyntaxKind[SyntaxKind["UnionType"] = 149] = "UnionType"; - SyntaxKind[SyntaxKind["ParenthesizedType"] = 150] = "ParenthesizedType"; + SyntaxKind[SyntaxKind["TypePredicate"] = 143] = "TypePredicate"; + SyntaxKind[SyntaxKind["TypeReference"] = 144] = "TypeReference"; + SyntaxKind[SyntaxKind["FunctionType"] = 145] = "FunctionType"; + SyntaxKind[SyntaxKind["ConstructorType"] = 146] = "ConstructorType"; + SyntaxKind[SyntaxKind["TypeQuery"] = 147] = "TypeQuery"; + SyntaxKind[SyntaxKind["TypeLiteral"] = 148] = "TypeLiteral"; + SyntaxKind[SyntaxKind["ArrayType"] = 149] = "ArrayType"; + SyntaxKind[SyntaxKind["TupleType"] = 150] = "TupleType"; + SyntaxKind[SyntaxKind["UnionType"] = 151] = "UnionType"; + SyntaxKind[SyntaxKind["ParenthesizedType"] = 152] = "ParenthesizedType"; // Binding patterns - SyntaxKind[SyntaxKind["ObjectBindingPattern"] = 151] = "ObjectBindingPattern"; - SyntaxKind[SyntaxKind["ArrayBindingPattern"] = 152] = "ArrayBindingPattern"; - SyntaxKind[SyntaxKind["BindingElement"] = 153] = "BindingElement"; + SyntaxKind[SyntaxKind["ObjectBindingPattern"] = 153] = "ObjectBindingPattern"; + SyntaxKind[SyntaxKind["ArrayBindingPattern"] = 154] = "ArrayBindingPattern"; + SyntaxKind[SyntaxKind["BindingElement"] = 155] = "BindingElement"; // Expression - SyntaxKind[SyntaxKind["ArrayLiteralExpression"] = 154] = "ArrayLiteralExpression"; - SyntaxKind[SyntaxKind["ObjectLiteralExpression"] = 155] = "ObjectLiteralExpression"; - SyntaxKind[SyntaxKind["PropertyAccessExpression"] = 156] = "PropertyAccessExpression"; - SyntaxKind[SyntaxKind["ElementAccessExpression"] = 157] = "ElementAccessExpression"; - SyntaxKind[SyntaxKind["CallExpression"] = 158] = "CallExpression"; - SyntaxKind[SyntaxKind["NewExpression"] = 159] = "NewExpression"; - SyntaxKind[SyntaxKind["TaggedTemplateExpression"] = 160] = "TaggedTemplateExpression"; - SyntaxKind[SyntaxKind["TypeAssertionExpression"] = 161] = "TypeAssertionExpression"; - SyntaxKind[SyntaxKind["ParenthesizedExpression"] = 162] = "ParenthesizedExpression"; - SyntaxKind[SyntaxKind["FunctionExpression"] = 163] = "FunctionExpression"; - SyntaxKind[SyntaxKind["ArrowFunction"] = 164] = "ArrowFunction"; - SyntaxKind[SyntaxKind["DeleteExpression"] = 165] = "DeleteExpression"; - SyntaxKind[SyntaxKind["TypeOfExpression"] = 166] = "TypeOfExpression"; - SyntaxKind[SyntaxKind["VoidExpression"] = 167] = "VoidExpression"; - SyntaxKind[SyntaxKind["PrefixUnaryExpression"] = 168] = "PrefixUnaryExpression"; - SyntaxKind[SyntaxKind["PostfixUnaryExpression"] = 169] = "PostfixUnaryExpression"; - SyntaxKind[SyntaxKind["BinaryExpression"] = 170] = "BinaryExpression"; - SyntaxKind[SyntaxKind["ConditionalExpression"] = 171] = "ConditionalExpression"; - SyntaxKind[SyntaxKind["TemplateExpression"] = 172] = "TemplateExpression"; - SyntaxKind[SyntaxKind["YieldExpression"] = 173] = "YieldExpression"; - SyntaxKind[SyntaxKind["SpreadElementExpression"] = 174] = "SpreadElementExpression"; - SyntaxKind[SyntaxKind["ClassExpression"] = 175] = "ClassExpression"; - SyntaxKind[SyntaxKind["OmittedExpression"] = 176] = "OmittedExpression"; - SyntaxKind[SyntaxKind["ExpressionWithTypeArguments"] = 177] = "ExpressionWithTypeArguments"; + SyntaxKind[SyntaxKind["ArrayLiteralExpression"] = 156] = "ArrayLiteralExpression"; + SyntaxKind[SyntaxKind["ObjectLiteralExpression"] = 157] = "ObjectLiteralExpression"; + SyntaxKind[SyntaxKind["PropertyAccessExpression"] = 158] = "PropertyAccessExpression"; + SyntaxKind[SyntaxKind["ElementAccessExpression"] = 159] = "ElementAccessExpression"; + SyntaxKind[SyntaxKind["CallExpression"] = 160] = "CallExpression"; + SyntaxKind[SyntaxKind["NewExpression"] = 161] = "NewExpression"; + SyntaxKind[SyntaxKind["TaggedTemplateExpression"] = 162] = "TaggedTemplateExpression"; + SyntaxKind[SyntaxKind["TypeAssertionExpression"] = 163] = "TypeAssertionExpression"; + SyntaxKind[SyntaxKind["ParenthesizedExpression"] = 164] = "ParenthesizedExpression"; + SyntaxKind[SyntaxKind["FunctionExpression"] = 165] = "FunctionExpression"; + SyntaxKind[SyntaxKind["ArrowFunction"] = 166] = "ArrowFunction"; + SyntaxKind[SyntaxKind["DeleteExpression"] = 167] = "DeleteExpression"; + SyntaxKind[SyntaxKind["TypeOfExpression"] = 168] = "TypeOfExpression"; + SyntaxKind[SyntaxKind["VoidExpression"] = 169] = "VoidExpression"; + SyntaxKind[SyntaxKind["PrefixUnaryExpression"] = 170] = "PrefixUnaryExpression"; + SyntaxKind[SyntaxKind["PostfixUnaryExpression"] = 171] = "PostfixUnaryExpression"; + SyntaxKind[SyntaxKind["BinaryExpression"] = 172] = "BinaryExpression"; + SyntaxKind[SyntaxKind["ConditionalExpression"] = 173] = "ConditionalExpression"; + SyntaxKind[SyntaxKind["TemplateExpression"] = 174] = "TemplateExpression"; + SyntaxKind[SyntaxKind["YieldExpression"] = 175] = "YieldExpression"; + SyntaxKind[SyntaxKind["SpreadElementExpression"] = 176] = "SpreadElementExpression"; + SyntaxKind[SyntaxKind["ClassExpression"] = 177] = "ClassExpression"; + SyntaxKind[SyntaxKind["OmittedExpression"] = 178] = "OmittedExpression"; + SyntaxKind[SyntaxKind["ExpressionWithTypeArguments"] = 179] = "ExpressionWithTypeArguments"; // Misc - SyntaxKind[SyntaxKind["TemplateSpan"] = 178] = "TemplateSpan"; - SyntaxKind[SyntaxKind["SemicolonClassElement"] = 179] = "SemicolonClassElement"; + SyntaxKind[SyntaxKind["TemplateSpan"] = 180] = "TemplateSpan"; + SyntaxKind[SyntaxKind["SemicolonClassElement"] = 181] = "SemicolonClassElement"; // Element - SyntaxKind[SyntaxKind["Block"] = 180] = "Block"; - SyntaxKind[SyntaxKind["VariableStatement"] = 181] = "VariableStatement"; - SyntaxKind[SyntaxKind["EmptyStatement"] = 182] = "EmptyStatement"; - SyntaxKind[SyntaxKind["ExpressionStatement"] = 183] = "ExpressionStatement"; - SyntaxKind[SyntaxKind["IfStatement"] = 184] = "IfStatement"; - SyntaxKind[SyntaxKind["DoStatement"] = 185] = "DoStatement"; - SyntaxKind[SyntaxKind["WhileStatement"] = 186] = "WhileStatement"; - SyntaxKind[SyntaxKind["ForStatement"] = 187] = "ForStatement"; - SyntaxKind[SyntaxKind["ForInStatement"] = 188] = "ForInStatement"; - SyntaxKind[SyntaxKind["ForOfStatement"] = 189] = "ForOfStatement"; - SyntaxKind[SyntaxKind["ContinueStatement"] = 190] = "ContinueStatement"; - SyntaxKind[SyntaxKind["BreakStatement"] = 191] = "BreakStatement"; - SyntaxKind[SyntaxKind["ReturnStatement"] = 192] = "ReturnStatement"; - SyntaxKind[SyntaxKind["WithStatement"] = 193] = "WithStatement"; - SyntaxKind[SyntaxKind["SwitchStatement"] = 194] = "SwitchStatement"; - SyntaxKind[SyntaxKind["LabeledStatement"] = 195] = "LabeledStatement"; - SyntaxKind[SyntaxKind["ThrowStatement"] = 196] = "ThrowStatement"; - SyntaxKind[SyntaxKind["TryStatement"] = 197] = "TryStatement"; - SyntaxKind[SyntaxKind["DebuggerStatement"] = 198] = "DebuggerStatement"; - SyntaxKind[SyntaxKind["VariableDeclaration"] = 199] = "VariableDeclaration"; - SyntaxKind[SyntaxKind["VariableDeclarationList"] = 200] = "VariableDeclarationList"; - SyntaxKind[SyntaxKind["FunctionDeclaration"] = 201] = "FunctionDeclaration"; - SyntaxKind[SyntaxKind["ClassDeclaration"] = 202] = "ClassDeclaration"; - SyntaxKind[SyntaxKind["InterfaceDeclaration"] = 203] = "InterfaceDeclaration"; - SyntaxKind[SyntaxKind["TypeAliasDeclaration"] = 204] = "TypeAliasDeclaration"; - SyntaxKind[SyntaxKind["EnumDeclaration"] = 205] = "EnumDeclaration"; - SyntaxKind[SyntaxKind["ModuleDeclaration"] = 206] = "ModuleDeclaration"; - SyntaxKind[SyntaxKind["ModuleBlock"] = 207] = "ModuleBlock"; - SyntaxKind[SyntaxKind["CaseBlock"] = 208] = "CaseBlock"; - SyntaxKind[SyntaxKind["ImportEqualsDeclaration"] = 209] = "ImportEqualsDeclaration"; - SyntaxKind[SyntaxKind["ImportDeclaration"] = 210] = "ImportDeclaration"; - SyntaxKind[SyntaxKind["ImportClause"] = 211] = "ImportClause"; - SyntaxKind[SyntaxKind["NamespaceImport"] = 212] = "NamespaceImport"; - SyntaxKind[SyntaxKind["NamedImports"] = 213] = "NamedImports"; - SyntaxKind[SyntaxKind["ImportSpecifier"] = 214] = "ImportSpecifier"; - SyntaxKind[SyntaxKind["ExportAssignment"] = 215] = "ExportAssignment"; - SyntaxKind[SyntaxKind["ExportDeclaration"] = 216] = "ExportDeclaration"; - SyntaxKind[SyntaxKind["NamedExports"] = 217] = "NamedExports"; - SyntaxKind[SyntaxKind["ExportSpecifier"] = 218] = "ExportSpecifier"; - SyntaxKind[SyntaxKind["MissingDeclaration"] = 219] = "MissingDeclaration"; + SyntaxKind[SyntaxKind["Block"] = 182] = "Block"; + SyntaxKind[SyntaxKind["VariableStatement"] = 183] = "VariableStatement"; + SyntaxKind[SyntaxKind["EmptyStatement"] = 184] = "EmptyStatement"; + SyntaxKind[SyntaxKind["ExpressionStatement"] = 185] = "ExpressionStatement"; + SyntaxKind[SyntaxKind["IfStatement"] = 186] = "IfStatement"; + SyntaxKind[SyntaxKind["DoStatement"] = 187] = "DoStatement"; + SyntaxKind[SyntaxKind["WhileStatement"] = 188] = "WhileStatement"; + SyntaxKind[SyntaxKind["ForStatement"] = 189] = "ForStatement"; + SyntaxKind[SyntaxKind["ForInStatement"] = 190] = "ForInStatement"; + SyntaxKind[SyntaxKind["ForOfStatement"] = 191] = "ForOfStatement"; + SyntaxKind[SyntaxKind["ContinueStatement"] = 192] = "ContinueStatement"; + SyntaxKind[SyntaxKind["BreakStatement"] = 193] = "BreakStatement"; + SyntaxKind[SyntaxKind["ReturnStatement"] = 194] = "ReturnStatement"; + SyntaxKind[SyntaxKind["WithStatement"] = 195] = "WithStatement"; + SyntaxKind[SyntaxKind["SwitchStatement"] = 196] = "SwitchStatement"; + SyntaxKind[SyntaxKind["LabeledStatement"] = 197] = "LabeledStatement"; + SyntaxKind[SyntaxKind["ThrowStatement"] = 198] = "ThrowStatement"; + SyntaxKind[SyntaxKind["TryStatement"] = 199] = "TryStatement"; + SyntaxKind[SyntaxKind["DebuggerStatement"] = 200] = "DebuggerStatement"; + SyntaxKind[SyntaxKind["VariableDeclaration"] = 201] = "VariableDeclaration"; + SyntaxKind[SyntaxKind["VariableDeclarationList"] = 202] = "VariableDeclarationList"; + SyntaxKind[SyntaxKind["FunctionDeclaration"] = 203] = "FunctionDeclaration"; + SyntaxKind[SyntaxKind["ClassDeclaration"] = 204] = "ClassDeclaration"; + SyntaxKind[SyntaxKind["InterfaceDeclaration"] = 205] = "InterfaceDeclaration"; + SyntaxKind[SyntaxKind["TypeAliasDeclaration"] = 206] = "TypeAliasDeclaration"; + SyntaxKind[SyntaxKind["EnumDeclaration"] = 207] = "EnumDeclaration"; + SyntaxKind[SyntaxKind["ModuleDeclaration"] = 208] = "ModuleDeclaration"; + SyntaxKind[SyntaxKind["ModuleBlock"] = 209] = "ModuleBlock"; + SyntaxKind[SyntaxKind["CaseBlock"] = 210] = "CaseBlock"; + SyntaxKind[SyntaxKind["ImportEqualsDeclaration"] = 211] = "ImportEqualsDeclaration"; + SyntaxKind[SyntaxKind["ImportDeclaration"] = 212] = "ImportDeclaration"; + SyntaxKind[SyntaxKind["ImportClause"] = 213] = "ImportClause"; + SyntaxKind[SyntaxKind["NamespaceImport"] = 214] = "NamespaceImport"; + SyntaxKind[SyntaxKind["NamedImports"] = 215] = "NamedImports"; + SyntaxKind[SyntaxKind["ImportSpecifier"] = 216] = "ImportSpecifier"; + SyntaxKind[SyntaxKind["ExportAssignment"] = 217] = "ExportAssignment"; + SyntaxKind[SyntaxKind["ExportDeclaration"] = 218] = "ExportDeclaration"; + SyntaxKind[SyntaxKind["NamedExports"] = 219] = "NamedExports"; + SyntaxKind[SyntaxKind["ExportSpecifier"] = 220] = "ExportSpecifier"; + SyntaxKind[SyntaxKind["MissingDeclaration"] = 221] = "MissingDeclaration"; // Module references - SyntaxKind[SyntaxKind["ExternalModuleReference"] = 220] = "ExternalModuleReference"; + SyntaxKind[SyntaxKind["ExternalModuleReference"] = 222] = "ExternalModuleReference"; // Clauses - SyntaxKind[SyntaxKind["CaseClause"] = 221] = "CaseClause"; - SyntaxKind[SyntaxKind["DefaultClause"] = 222] = "DefaultClause"; - SyntaxKind[SyntaxKind["HeritageClause"] = 223] = "HeritageClause"; - SyntaxKind[SyntaxKind["CatchClause"] = 224] = "CatchClause"; + SyntaxKind[SyntaxKind["CaseClause"] = 223] = "CaseClause"; + SyntaxKind[SyntaxKind["DefaultClause"] = 224] = "DefaultClause"; + SyntaxKind[SyntaxKind["HeritageClause"] = 225] = "HeritageClause"; + SyntaxKind[SyntaxKind["CatchClause"] = 226] = "CatchClause"; // Property assignments - SyntaxKind[SyntaxKind["PropertyAssignment"] = 225] = "PropertyAssignment"; - SyntaxKind[SyntaxKind["ShorthandPropertyAssignment"] = 226] = "ShorthandPropertyAssignment"; + SyntaxKind[SyntaxKind["PropertyAssignment"] = 227] = "PropertyAssignment"; + SyntaxKind[SyntaxKind["ShorthandPropertyAssignment"] = 228] = "ShorthandPropertyAssignment"; // Enum - SyntaxKind[SyntaxKind["EnumMember"] = 227] = "EnumMember"; + SyntaxKind[SyntaxKind["EnumMember"] = 229] = "EnumMember"; // Top-level nodes - SyntaxKind[SyntaxKind["SourceFile"] = 228] = "SourceFile"; + SyntaxKind[SyntaxKind["SourceFile"] = 230] = "SourceFile"; + // JSDoc nodes. + SyntaxKind[SyntaxKind["JSDocTypeExpression"] = 231] = "JSDocTypeExpression"; + // The * type. + SyntaxKind[SyntaxKind["JSDocAllType"] = 232] = "JSDocAllType"; + // The ? type. + SyntaxKind[SyntaxKind["JSDocUnknownType"] = 233] = "JSDocUnknownType"; + SyntaxKind[SyntaxKind["JSDocArrayType"] = 234] = "JSDocArrayType"; + SyntaxKind[SyntaxKind["JSDocUnionType"] = 235] = "JSDocUnionType"; + SyntaxKind[SyntaxKind["JSDocTupleType"] = 236] = "JSDocTupleType"; + SyntaxKind[SyntaxKind["JSDocNullableType"] = 237] = "JSDocNullableType"; + SyntaxKind[SyntaxKind["JSDocNonNullableType"] = 238] = "JSDocNonNullableType"; + SyntaxKind[SyntaxKind["JSDocRecordType"] = 239] = "JSDocRecordType"; + SyntaxKind[SyntaxKind["JSDocRecordMember"] = 240] = "JSDocRecordMember"; + SyntaxKind[SyntaxKind["JSDocTypeReference"] = 241] = "JSDocTypeReference"; + SyntaxKind[SyntaxKind["JSDocOptionalType"] = 242] = "JSDocOptionalType"; + SyntaxKind[SyntaxKind["JSDocFunctionType"] = 243] = "JSDocFunctionType"; + SyntaxKind[SyntaxKind["JSDocVariadicType"] = 244] = "JSDocVariadicType"; + SyntaxKind[SyntaxKind["JSDocConstructorType"] = 245] = "JSDocConstructorType"; + SyntaxKind[SyntaxKind["JSDocThisType"] = 246] = "JSDocThisType"; + SyntaxKind[SyntaxKind["JSDocComment"] = 247] = "JSDocComment"; + SyntaxKind[SyntaxKind["JSDocTag"] = 248] = "JSDocTag"; + SyntaxKind[SyntaxKind["JSDocParameterTag"] = 249] = "JSDocParameterTag"; + SyntaxKind[SyntaxKind["JSDocReturnTag"] = 250] = "JSDocReturnTag"; + SyntaxKind[SyntaxKind["JSDocTypeTag"] = 251] = "JSDocTypeTag"; + SyntaxKind[SyntaxKind["JSDocTemplateTag"] = 252] = "JSDocTemplateTag"; // Synthesized list - SyntaxKind[SyntaxKind["SyntaxList"] = 229] = "SyntaxList"; + SyntaxKind[SyntaxKind["SyntaxList"] = 253] = "SyntaxList"; // Enum value count - SyntaxKind[SyntaxKind["Count"] = 230] = "Count"; + SyntaxKind[SyntaxKind["Count"] = 254] = "Count"; // Markers SyntaxKind[SyntaxKind["FirstAssignment"] = 53] = "FirstAssignment"; SyntaxKind[SyntaxKind["LastAssignment"] = 64] = "LastAssignment"; SyntaxKind[SyntaxKind["FirstReservedWord"] = 66] = "FirstReservedWord"; SyntaxKind[SyntaxKind["LastReservedWord"] = 101] = "LastReservedWord"; SyntaxKind[SyntaxKind["FirstKeyword"] = 66] = "FirstKeyword"; - SyntaxKind[SyntaxKind["LastKeyword"] = 126] = "LastKeyword"; + SyntaxKind[SyntaxKind["LastKeyword"] = 127] = "LastKeyword"; SyntaxKind[SyntaxKind["FirstFutureReservedWord"] = 102] = "FirstFutureReservedWord"; SyntaxKind[SyntaxKind["LastFutureReservedWord"] = 110] = "LastFutureReservedWord"; - SyntaxKind[SyntaxKind["FirstTypeNode"] = 142] = "FirstTypeNode"; - SyntaxKind[SyntaxKind["LastTypeNode"] = 150] = "LastTypeNode"; + SyntaxKind[SyntaxKind["FirstTypeNode"] = 144] = "FirstTypeNode"; + SyntaxKind[SyntaxKind["LastTypeNode"] = 152] = "LastTypeNode"; SyntaxKind[SyntaxKind["FirstPunctuation"] = 14] = "FirstPunctuation"; SyntaxKind[SyntaxKind["LastPunctuation"] = 64] = "LastPunctuation"; SyntaxKind[SyntaxKind["FirstToken"] = 0] = "FirstToken"; - SyntaxKind[SyntaxKind["LastToken"] = 126] = "LastToken"; + SyntaxKind[SyntaxKind["LastToken"] = 127] = "LastToken"; SyntaxKind[SyntaxKind["FirstTriviaToken"] = 2] = "FirstTriviaToken"; SyntaxKind[SyntaxKind["LastTriviaToken"] = 6] = "LastTriviaToken"; SyntaxKind[SyntaxKind["FirstLiteralToken"] = 7] = "FirstLiteralToken"; @@ -297,7 +324,7 @@ var ts; SyntaxKind[SyntaxKind["LastTemplateToken"] = 13] = "LastTemplateToken"; SyntaxKind[SyntaxKind["FirstBinaryOperator"] = 24] = "FirstBinaryOperator"; SyntaxKind[SyntaxKind["LastBinaryOperator"] = 64] = "LastBinaryOperator"; - SyntaxKind[SyntaxKind["FirstNode"] = 127] = "FirstNode"; + SyntaxKind[SyntaxKind["FirstNode"] = 128] = "FirstNode"; })(ts.SyntaxKind || (ts.SyntaxKind = {})); var SyntaxKind = ts.SyntaxKind; (function (NodeFlags) { @@ -323,9 +350,7 @@ var ts; var NodeFlags = ts.NodeFlags; /* @internal */ (function (ParserContextFlags) { - // Set if this node was parsed in strict mode. Used for grammar error checks, as well as - // checking if the node can be reused in incremental settings. - ParserContextFlags[ParserContextFlags["StrictMode"] = 1] = "StrictMode"; + ParserContextFlags[ParserContextFlags["None"] = 0] = "None"; // If this node was parsed in a context where 'in-expressions' are not allowed. ParserContextFlags[ParserContextFlags["DisallowIn"] = 2] = "DisallowIn"; // If this node was parsed in the 'yield' context created when parsing a generator. @@ -338,14 +363,17 @@ var ts; // the parser only sets this directly on the node it creates right after encountering the // error. ParserContextFlags[ParserContextFlags["ThisNodeHasError"] = 32] = "ThisNodeHasError"; + // This node was parsed in a JavaScript file and can be processed differently. For example + // its type can be specified usign a JSDoc comment. + ParserContextFlags[ParserContextFlags["JavaScriptFile"] = 64] = "JavaScriptFile"; // Context flags set directly by the parser. - ParserContextFlags[ParserContextFlags["ParserGeneratedFlags"] = 63] = "ParserGeneratedFlags"; + ParserContextFlags[ParserContextFlags["ParserGeneratedFlags"] = 62] = "ParserGeneratedFlags"; // Context flags computed by aggregating child flags upwards. // Used during incremental parsing to determine if this node or any of its children had an // error. Computed only once and then cached. - ParserContextFlags[ParserContextFlags["ThisNodeOrAnySubNodesHasError"] = 64] = "ThisNodeOrAnySubNodesHasError"; + ParserContextFlags[ParserContextFlags["ThisNodeOrAnySubNodesHasError"] = 128] = "ThisNodeOrAnySubNodesHasError"; // Used to know if we've computed data from children and cached it in this node. - ParserContextFlags[ParserContextFlags["HasAggregatedChildData"] = 128] = "HasAggregatedChildData"; + ParserContextFlags[ParserContextFlags["HasAggregatedChildData"] = 256] = "HasAggregatedChildData"; })(ts.ParserContextFlags || (ts.ParserContextFlags = {})); var ParserContextFlags = ts.ParserContextFlags; /* @internal */ @@ -400,6 +428,7 @@ var ts; })(ts.SymbolAccessibility || (ts.SymbolAccessibility = {})); var SymbolAccessibility = ts.SymbolAccessibility; (function (SymbolFlags) { + SymbolFlags[SymbolFlags["None"] = 0] = "None"; SymbolFlags[SymbolFlags["FunctionScopedVariable"] = 1] = "FunctionScopedVariable"; SymbolFlags[SymbolFlags["BlockScopedVariable"] = 2] = "BlockScopedVariable"; SymbolFlags[SymbolFlags["Property"] = 4] = "Property"; @@ -462,12 +491,15 @@ var ts; SymbolFlags[SymbolFlags["AliasExcludes"] = 8388608] = "AliasExcludes"; SymbolFlags[SymbolFlags["ModuleMember"] = 8914931] = "ModuleMember"; SymbolFlags[SymbolFlags["ExportHasLocal"] = 944] = "ExportHasLocal"; - SymbolFlags[SymbolFlags["HasLocals"] = 255504] = "HasLocals"; SymbolFlags[SymbolFlags["HasExports"] = 1952] = "HasExports"; SymbolFlags[SymbolFlags["HasMembers"] = 6240] = "HasMembers"; - SymbolFlags[SymbolFlags["IsContainer"] = 262128] = "IsContainer"; + SymbolFlags[SymbolFlags["BlockScoped"] = 418] = "BlockScoped"; SymbolFlags[SymbolFlags["PropertyOrAccessor"] = 98308] = "PropertyOrAccessor"; SymbolFlags[SymbolFlags["Export"] = 7340032] = "Export"; + /* @internal */ + // The set of things we consider semantically classifiable. Used to speed up the LS during + // classification. + SymbolFlags[SymbolFlags["Classifiable"] = 788448] = "Classifiable"; })(ts.SymbolFlags || (ts.SymbolFlags = {})); var SymbolFlags = ts.SymbolFlags; /* @internal */ @@ -504,23 +536,24 @@ var ts; TypeFlags[TypeFlags["Tuple"] = 8192] = "Tuple"; TypeFlags[TypeFlags["Union"] = 16384] = "Union"; TypeFlags[TypeFlags["Anonymous"] = 32768] = "Anonymous"; + TypeFlags[TypeFlags["Instantiated"] = 65536] = "Instantiated"; /* @internal */ - TypeFlags[TypeFlags["FromSignature"] = 65536] = "FromSignature"; - TypeFlags[TypeFlags["ObjectLiteral"] = 131072] = "ObjectLiteral"; + TypeFlags[TypeFlags["FromSignature"] = 131072] = "FromSignature"; + TypeFlags[TypeFlags["ObjectLiteral"] = 262144] = "ObjectLiteral"; /* @internal */ - TypeFlags[TypeFlags["ContainsUndefinedOrNull"] = 262144] = "ContainsUndefinedOrNull"; + TypeFlags[TypeFlags["ContainsUndefinedOrNull"] = 524288] = "ContainsUndefinedOrNull"; /* @internal */ - TypeFlags[TypeFlags["ContainsObjectLiteral"] = 524288] = "ContainsObjectLiteral"; - TypeFlags[TypeFlags["ESSymbol"] = 1048576] = "ESSymbol"; + TypeFlags[TypeFlags["ContainsObjectLiteral"] = 1048576] = "ContainsObjectLiteral"; + TypeFlags[TypeFlags["ESSymbol"] = 2097152] = "ESSymbol"; /* @internal */ - TypeFlags[TypeFlags["Intrinsic"] = 1048703] = "Intrinsic"; + TypeFlags[TypeFlags["Intrinsic"] = 2097279] = "Intrinsic"; /* @internal */ - TypeFlags[TypeFlags["Primitive"] = 1049086] = "Primitive"; + TypeFlags[TypeFlags["Primitive"] = 2097662] = "Primitive"; TypeFlags[TypeFlags["StringLike"] = 258] = "StringLike"; TypeFlags[TypeFlags["NumberLike"] = 132] = "NumberLike"; TypeFlags[TypeFlags["ObjectType"] = 48128] = "ObjectType"; /* @internal */ - TypeFlags[TypeFlags["RequiresWidening"] = 786432] = "RequiresWidening"; + TypeFlags[TypeFlags["RequiresWidening"] = 1572864] = "RequiresWidening"; })(ts.TypeFlags || (ts.TypeFlags = {})); var TypeFlags = ts.TypeFlags; (function (SignatureKind) { @@ -706,6 +739,36 @@ var ts; Ternary[Ternary["True"] = -1] = "True"; })(ts.Ternary || (ts.Ternary = {})); var Ternary = ts.Ternary; + function createFileMap(getCanonicalFileName) { + var files = {}; + return { + get: get, + set: set, + contains: contains, + remove: remove, + forEachValue: forEachValueInMap + }; + function set(fileName, value) { + files[normalizeKey(fileName)] = value; + } + function get(fileName) { + return files[normalizeKey(fileName)]; + } + function contains(fileName) { + return hasProperty(files, normalizeKey(fileName)); + } + function remove(fileName) { + var key = normalizeKey(fileName); + delete files[key]; + } + function forEachValueInMap(f) { + forEachValue(files, f); + } + function normalizeKey(key) { + return getCanonicalFileName(normalizeSlashes(key)); + } + } + ts.createFileMap = createFileMap; (function (Comparison) { Comparison[Comparison["LessThan"] = -1] = "LessThan"; Comparison[Comparison["EqualTo"] = 0] = "EqualTo"; @@ -826,6 +889,16 @@ var ts; } } ts.addRange = addRange; + function rangeEquals(array1, array2, pos, end) { + while (pos < end) { + if (array1[pos] !== array2[pos]) { + return false; + } + pos++; + } + return true; + } + ts.rangeEquals = rangeEquals; /** * Returns the last element of an array if non-empty, undefined otherwise. */ @@ -995,8 +1068,10 @@ var ts; var end = start + length; Debug.assert(start >= 0, "start must be non-negative, is " + start); Debug.assert(length >= 0, "length must be non-negative, is " + length); - Debug.assert(start <= file.text.length, "start must be within the bounds of the file. " + start + " > " + file.text.length); - Debug.assert(end <= file.text.length, "end must be the bounds of the file. " + end + " > " + file.text.length); + if (file) { + Debug.assert(start <= file.text.length, "start must be within the bounds of the file. " + start + " > " + file.text.length); + Debug.assert(end <= file.text.length, "end must be the bounds of the file. " + end + " > " + file.text.length); + } var text = getLocaleSpecificMessage(message.key); if (arguments.length > 4) { text = formatStringFromArgs(text, arguments, 4); @@ -1191,7 +1266,7 @@ var ts; function getNormalizedPathComponents(path, currentDirectory) { path = normalizeSlashes(path); var rootLength = getRootLength(path); - if (rootLength == 0) { + if (rootLength === 0) { // If the path is not rooted it is relative to current directory path = combinePaths(normalizeSlashes(currentDirectory), path); rootLength = getRootLength(path); @@ -1466,6 +1541,9 @@ var ts; fileStream.Close(); } } + function getCanonicalPath(path) { + return path.toLowerCase(); + } function getNames(collection) { var result = []; for (var e = new Enumerator(collection); !e.atEnd(); e.moveNext()) { @@ -1473,23 +1551,28 @@ var ts; } return result.sort(); } - function readDirectory(path, extension) { + function readDirectory(path, extension, exclude) { var result = []; + exclude = ts.map(exclude, function (s) { return getCanonicalPath(ts.combinePaths(path, s)); }); visitDirectory(path); return result; function visitDirectory(path) { var folder = fso.GetFolder(path || "."); var files = getNames(folder.files); for (var _i = 0; _i < files.length; _i++) { - var name_1 = files[_i]; - if (!extension || ts.fileExtensionIs(name_1, extension)) { - result.push(ts.combinePaths(path, name_1)); + var current = files[_i]; + var name_1 = ts.combinePaths(path, current); + if ((!extension || ts.fileExtensionIs(name_1, extension)) && !ts.contains(exclude, getCanonicalPath(name_1))) { + result.push(name_1); } } var subfolders = getNames(folder.subfolders); for (var _a = 0; _a < subfolders.length; _a++) { var current = subfolders[_a]; - visitDirectory(ts.combinePaths(path, current)); + var name_2 = ts.combinePaths(path, current); + if (!ts.contains(exclude, getCanonicalPath(name_2))) { + visitDirectory(name_2); + } } } } @@ -1574,8 +1657,12 @@ var ts; } _fs.writeFileSync(fileName, data, "utf8"); } - function readDirectory(path, extension) { + function getCanonicalPath(path) { + return useCaseSensitiveFileNames ? path.toLowerCase() : path; + } + function readDirectory(path, extension, exclude) { var result = []; + exclude = ts.map(exclude, function (s) { return getCanonicalPath(ts.combinePaths(path, s)); }); visitDirectory(path); return result; function visitDirectory(path) { @@ -1584,14 +1671,16 @@ var ts; for (var _i = 0; _i < files.length; _i++) { var current = files[_i]; var name = ts.combinePaths(path, current); - var stat = _fs.lstatSync(name); - if (stat.isFile()) { - if (!extension || ts.fileExtensionIs(name, extension)) { - result.push(name); + if (!ts.contains(exclude, getCanonicalPath(name))) { + var stat = _fs.statSync(name); + if (stat.isFile()) { + if (!extension || ts.fileExtensionIs(name, extension)) { + result.push(name); + } + } + else if (stat.isDirectory()) { + directories.push(name); } - } - else if (stat.isDirectory()) { - directories.push(name); } } for (var _a = 0; _a < directories.length; _a++) { @@ -1790,7 +1879,7 @@ var ts; Unterminated_template_literal: { code: 1160, category: ts.DiagnosticCategory.Error, key: "Unterminated template literal." }, Unterminated_regular_expression_literal: { code: 1161, category: ts.DiagnosticCategory.Error, key: "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." }, - yield_expression_must_be_contained_within_a_generator_declaration: { code: 1163, category: ts.DiagnosticCategory.Error, key: "'yield' expression must be contained_within a generator declaration." }, + 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." }, Computed_property_names_are_not_allowed_in_enums: { code: 1164, category: ts.DiagnosticCategory.Error, key: "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." }, 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." }, @@ -1835,15 +1924,32 @@ var ts; Decorators_are_only_available_when_targeting_ECMAScript_5_and_higher: { code: 1205, category: ts.DiagnosticCategory.Error, key: "Decorators are only available when targeting ECMAScript 5 and higher." }, Decorators_are_not_valid_here: { code: 1206, category: ts.DiagnosticCategory.Error, key: "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/set accessors of the same name." }, - Cannot_compile_namespaces_when_the_separateCompilation_flag_is_provided: { code: 1208, category: ts.DiagnosticCategory.Error, key: "Cannot compile namespaces when the '--separateCompilation' flag is provided." }, - Ambient_const_enums_are_not_allowed_when_the_separateCompilation_flag_is_provided: { code: 1209, category: ts.DiagnosticCategory.Error, key: "Ambient const enums are not allowed when the '--separateCompilation' flag is provided." }, + 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." }, + 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." }, 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." }, 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" }, 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" }, 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 strict mode." }, - Type_expected_0_is_a_reserved_word_in_strict_mode: { code: 1215, category: ts.DiagnosticCategory.Error, key: "Type expected. '{0}' is a reserved word in strict mode" }, - Type_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_strict_mode: { code: 1216, category: ts.DiagnosticCategory.Error, key: "Type 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." }, + 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." }, 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'." }, + Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Specify_experimentalDecorators_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. Specify '--experimentalDecorators' to remove this warning." }, + Generators_are_only_available_when_targeting_ECMAScript_6_or_higher: { code: 1220, category: ts.DiagnosticCategory.Error, key: "Generators are only available when targeting ECMAScript 6 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." }, + 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." }, + _0_tag_already_specified: { code: 1223, category: ts.DiagnosticCategory.Error, key: "'{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." }, + Cannot_find_parameter_0: { code: 1225, category: ts.DiagnosticCategory.Error, key: "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}'." }, + 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}'." }, + 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." }, + A_type_predicate_cannot_reference_a_rest_parameter: { code: 1229, category: ts.DiagnosticCategory.Error, key: "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." }, + 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." }, + 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." }, + 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." }, + 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." }, + 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." }, Duplicate_identifier_0: { code: 2300, category: ts.DiagnosticCategory.Error, key: "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." }, Static_members_cannot_reference_class_type_parameters: { code: 2302, category: ts.DiagnosticCategory.Error, key: "Static members cannot reference class type parameters." }, @@ -2004,7 +2110,7 @@ var ts; 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'." }, 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." }, 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'." }, - Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_6_and_higher: { code: 2472, category: ts.DiagnosticCategory.Error, key: "Spread operator in 'new' expressions is only available when targeting ECMAScript 6 and higher." }, + 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." }, 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." }, 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." }, 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 import declaration or export assignment." }, @@ -2035,6 +2141,13 @@ var ts; A_rest_element_cannot_contain_a_binding_pattern: { code: 2501, category: ts.DiagnosticCategory.Error, key: "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." }, Cannot_find_namespace_0: { code: 2503, category: ts.DiagnosticCategory.Error, key: "Cannot find namespace '{0}'." }, + No_best_common_type_exists_among_yield_expressions: { code: 2504, category: ts.DiagnosticCategory.Error, key: "No best common type exists among yield expressions." }, + A_generator_cannot_have_a_void_type_annotation: { code: 2505, category: ts.DiagnosticCategory.Error, key: "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." }, + Type_0_is_not_a_constructor_function_type: { code: 2507, category: ts.DiagnosticCategory.Error, key: "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." }, + 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." }, + 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." }, Import_declaration_0_is_using_private_name_1: { code: 4000, category: ts.DiagnosticCategory.Error, key: "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}'." }, 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}'." }, @@ -2119,11 +2232,11 @@ var ts; Option_noEmit_cannot_be_specified_with_option_out_or_outDir: { code: 5040, category: ts.DiagnosticCategory.Error, key: "Option 'noEmit' cannot be specified with option 'out' or 'outDir'." }, Option_noEmit_cannot_be_specified_with_option_declaration: { code: 5041, category: ts.DiagnosticCategory.Error, key: "Option 'noEmit' cannot be specified with option 'declaration'." }, 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." }, - Option_sourceMap_cannot_be_specified_with_option_separateCompilation: { code: 5043, category: ts.DiagnosticCategory.Error, key: "Option 'sourceMap' cannot be specified with option 'separateCompilation'." }, - Option_declaration_cannot_be_specified_with_option_separateCompilation: { code: 5044, category: ts.DiagnosticCategory.Error, key: "Option 'declaration' cannot be specified with option 'separateCompilation'." }, - Option_noEmitOnError_cannot_be_specified_with_option_separateCompilation: { code: 5045, category: ts.DiagnosticCategory.Error, key: "Option 'noEmitOnError' cannot be specified with option 'separateCompilation'." }, - Option_out_cannot_be_specified_with_option_separateCompilation: { code: 5046, category: ts.DiagnosticCategory.Error, key: "Option 'out' cannot be specified with option 'separateCompilation'." }, - Option_separateCompilation_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES6_or_higher: { code: 5047, category: ts.DiagnosticCategory.Error, key: "Option 'separateCompilation' can only be used when either option'--module' is provided or option 'target' is 'ES6' or higher." }, + Option_sourceMap_cannot_be_specified_with_option_isolatedModules: { code: 5043, category: ts.DiagnosticCategory.Error, key: "Option 'sourceMap' cannot be specified with option 'isolatedModules'." }, + Option_declaration_cannot_be_specified_with_option_isolatedModules: { code: 5044, category: ts.DiagnosticCategory.Error, key: "Option 'declaration' cannot be specified with option 'isolatedModules'." }, + Option_noEmitOnError_cannot_be_specified_with_option_isolatedModules: { code: 5045, category: ts.DiagnosticCategory.Error, key: "Option 'noEmitOnError' cannot be specified with option 'isolatedModules'." }, + Option_out_cannot_be_specified_with_option_isolatedModules: { code: 5046, category: ts.DiagnosticCategory.Error, key: "Option 'out' cannot be specified with option 'isolatedModules'." }, + Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES6_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 'ES6' or higher." }, Option_sourceMap_cannot_be_specified_with_option_inlineSourceMap: { code: 5048, category: ts.DiagnosticCategory.Error, key: "Option 'sourceMap' cannot be specified with option 'inlineSourceMap'." }, Option_sourceRoot_cannot_be_specified_with_option_inlineSourceMap: { code: 5049, category: ts.DiagnosticCategory.Error, key: "Option 'sourceRoot' cannot be specified with option 'inlineSourceMap'." }, Option_mapRoot_cannot_be_specified_with_option_inlineSourceMap: { code: 5050, category: ts.DiagnosticCategory.Error, key: "Option 'mapRoot' cannot be specified with option 'inlineSourceMap'." }, @@ -2177,6 +2290,9 @@ var ts; Specifies_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix: { code: 6060, category: ts.DiagnosticCategory.Message, key: "Specifies 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" }, Argument_for_newLine_option_must_be_CRLF_or_LF: { code: 6062, category: ts.DiagnosticCategory.Error, key: "Argument for '--newLine' option must be 'CRLF' or 'LF'." }, + Option_experimentalDecorators_must_also_be_specified_when_option_emitDecoratorMetadata_is_specified: { code: 6064, category: ts.DiagnosticCategory.Error, key: "Option 'experimentalDecorators' must also be specified when option 'emitDecoratorMetadata' is specified." }, + Enables_experimental_support_for_ES7_decorators: { code: 6065, category: ts.DiagnosticCategory.Message, key: "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." }, Variable_0_implicitly_has_an_1_type: { code: 7005, category: ts.DiagnosticCategory.Error, key: "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." }, Member_0_implicitly_has_an_1_type: { code: 7008, category: ts.DiagnosticCategory.Error, key: "Member '{0}' implicitly has an '{1}' type." }, @@ -2189,9 +2305,10 @@ var ts; 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." }, Rest_parameter_0_implicitly_has_an_any_type: { code: 7019, category: ts.DiagnosticCategory.Error, key: "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." }, - _0_implicitly_has_type_any_because_it_is_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 is does not have a type annotation and is referenced directly or indirectly in its own initializer." }, + _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 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 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 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 type." }, You_cannot_rename_this_element: { code: 8000, category: ts.DiagnosticCategory.Error, key: "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." }, 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." }, @@ -2205,16 +2322,12 @@ var ts; 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." }, 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." }, 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." }, - can_only_be_used_in_a_ts_file: { code: 8013, category: ts.DiagnosticCategory.Error, key: "'?' can only be used in a .ts file." }, property_declarations_can_only_be_used_in_a_ts_file: { code: 8014, category: ts.DiagnosticCategory.Error, key: "'property declarations' 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." }, 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." }, decorators_can_only_be_used_in_a_ts_file: { code: 8017, category: ts.DiagnosticCategory.Error, key: "'decorators' can only be used in a .ts file." }, - yield_expressions_are_not_currently_supported: { code: 9000, category: ts.DiagnosticCategory.Error, key: "'yield' expressions are not currently supported." }, - Generators_are_not_currently_supported: { code: 9001, category: ts.DiagnosticCategory.Error, key: "Generators are not currently supported." }, Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_class_extends_clauses: { code: 9002, category: ts.DiagnosticCategory.Error, key: "Only identifiers/qualified-names with optional type arguments are currently supported in a class 'extends' clauses." }, - class_expressions_are_not_currently_supported: { code: 9003, category: ts.DiagnosticCategory.Error, key: "'class' expressions are not currently supported." }, - class_declarations_are_only_supported_directly_inside_a_module_or_as_a_top_level_declaration: { code: 9004, category: ts.DiagnosticCategory.Error, key: "'class' declarations are only supported directly inside a module or as a top level declaration." } + class_expressions_are_not_currently_supported: { code: 9003, category: ts.DiagnosticCategory.Error, key: "'class' expressions are not currently supported." } }; })(ts || (ts = {})); /// @@ -2244,7 +2357,7 @@ var ts; "false": 80 /* FalseKeyword */, "finally": 81 /* FinallyKeyword */, "for": 82 /* ForKeyword */, - "from": 125 /* FromKeyword */, + "from": 126 /* FromKeyword */, "function": 83 /* FunctionKeyword */, "get": 116 /* GetKeyword */, "if": 84 /* IfKeyword */, @@ -2253,36 +2366,37 @@ var ts; "in": 86 /* InKeyword */, "instanceof": 87 /* InstanceOfKeyword */, "interface": 103 /* InterfaceKeyword */, + "is": 117 /* IsKeyword */, "let": 104 /* LetKeyword */, - "module": 117 /* ModuleKeyword */, - "namespace": 118 /* NamespaceKeyword */, + "module": 118 /* ModuleKeyword */, + "namespace": 119 /* NamespaceKeyword */, "new": 88 /* NewKeyword */, "null": 89 /* NullKeyword */, - "number": 120 /* NumberKeyword */, + "number": 121 /* NumberKeyword */, "package": 105 /* PackageKeyword */, "private": 106 /* PrivateKeyword */, "protected": 107 /* ProtectedKeyword */, "public": 108 /* PublicKeyword */, - "require": 119 /* RequireKeyword */, + "require": 120 /* RequireKeyword */, "return": 90 /* ReturnKeyword */, - "set": 121 /* SetKeyword */, + "set": 122 /* SetKeyword */, "static": 109 /* StaticKeyword */, - "string": 122 /* StringKeyword */, + "string": 123 /* StringKeyword */, "super": 91 /* SuperKeyword */, "switch": 92 /* SwitchKeyword */, - "symbol": 123 /* SymbolKeyword */, + "symbol": 124 /* SymbolKeyword */, "this": 93 /* ThisKeyword */, "throw": 94 /* ThrowKeyword */, "true": 95 /* TrueKeyword */, "try": 96 /* TryKeyword */, - "type": 124 /* TypeKeyword */, + "type": 125 /* TypeKeyword */, "typeof": 97 /* TypeOfKeyword */, "var": 98 /* VarKeyword */, "void": 99 /* VoidKeyword */, "while": 100 /* WhileKeyword */, "with": 101 /* WithKeyword */, "yield": 110 /* YieldKeyword */, - "of": 126 /* OfKeyword */, + "of": 127 /* OfKeyword */, "{": 14 /* OpenBraceToken */, "}": 15 /* CloseBraceToken */, "(": 16 /* OpenParenToken */, @@ -2419,9 +2533,9 @@ var ts; } function makeReverseMap(source) { var result = []; - for (var name_2 in source) { - if (source.hasOwnProperty(name_2)) { - result[source[name_2]] = name_2; + for (var name_3 in source) { + if (source.hasOwnProperty(name_3)) { + result[source[name_3]] = name_3; } } return result; @@ -2542,8 +2656,31 @@ var ts; return ch >= 48 /* _0 */ && ch <= 55 /* _7 */; } ts.isOctalDigit = isOctalDigit; + function couldStartTrivia(text, pos) { + // Keep in sync with skipTrivia + var ch = text.charCodeAt(pos); + switch (ch) { + case 13 /* carriageReturn */: + case 10 /* lineFeed */: + case 9 /* tab */: + case 11 /* verticalTab */: + case 12 /* formFeed */: + case 32 /* space */: + case 47 /* slash */: + // starts of normal trivia + case 60 /* lessThan */: + case 61 /* equals */: + case 62 /* greaterThan */: + // Starts of conflict marker trivia + return true; + default: + return ch > 127 /* maxAsciiCharacter */; + } + } + ts.couldStartTrivia = couldStartTrivia; /* @internal */ function skipTrivia(text, pos, stopAfterLineBreak) { + // Keep in sync with couldStartTrivia while (true) { var ch = text.charCodeAt(pos); switch (ch) { @@ -2750,12 +2887,17 @@ var ts; ch > 127 /* maxAsciiCharacter */ && isUnicodeIdentifierPart(ch, languageVersion); } ts.isIdentifierPart = isIdentifierPart; - /** Creates a scanner over a (possibly unspecified) range of a piece of text. */ + /* @internal */ + // Creates a scanner over a (possibly unspecified) range of a piece of text. function createScanner(languageVersion, skipTrivia, text, onError, start, length) { - var pos; // Current position (end position of text of current token) - var end; // end of text - var startPos; // Start position of whitespace before current token - var tokenPos; // Start position of text of current token + // Current position (end position of text of current token) + var pos; + // end of text + var end; + // Start position of whitespace before current token + var startPos; + // Start position of text of current token + var tokenPos; var token; var tokenValue; var precedingLineBreak; @@ -3042,7 +3184,7 @@ var ts; error(ts.Diagnostics.Unexpected_end_of_text); isInvalidExtendedEscape = true; } - else if (text.charCodeAt(pos) == 125 /* closeBrace */) { + else if (text.charCodeAt(pos) === 125 /* closeBrace */) { // Only swallow the following character up if it's a '}'. pos++; } @@ -3599,16 +3741,16 @@ var ts; function getModuleInstanceState(node) { // A module is uninstantiated if it contains only // 1. interface declarations, type alias declarations - if (node.kind === 203 /* InterfaceDeclaration */ || node.kind === 204 /* TypeAliasDeclaration */) { + if (node.kind === 205 /* InterfaceDeclaration */ || node.kind === 206 /* TypeAliasDeclaration */) { return 0 /* NonInstantiated */; } else if (ts.isConstEnumDeclaration(node)) { return 2 /* ConstEnumOnly */; } - else if ((node.kind === 210 /* ImportDeclaration */ || node.kind === 209 /* ImportEqualsDeclaration */) && !(node.flags & 1 /* Export */)) { + else if ((node.kind === 212 /* ImportDeclaration */ || node.kind === 211 /* ImportEqualsDeclaration */) && !(node.flags & 1 /* Export */)) { return 0 /* NonInstantiated */; } - else if (node.kind === 207 /* ModuleBlock */) { + else if (node.kind === 209 /* ModuleBlock */) { var state = 0 /* NonInstantiated */; ts.forEachChild(node, function (n) { switch (getModuleInstanceState(n)) { @@ -3627,7 +3769,7 @@ var ts; }); return state; } - else if (node.kind === 206 /* ModuleDeclaration */) { + else if (node.kind === 208 /* ModuleDeclaration */) { return getModuleInstanceState(node.body); } else { @@ -3635,6 +3777,27 @@ var ts; } } 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"; + ContainerFlags[ContainerFlags["HasLocals"] = 4] = "HasLocals"; + // If the current node is a container that also container that also contains locals. Examples: + // + // Functions, Methods, Modules, Source-files. + ContainerFlags[ContainerFlags["IsContainerWithLocals"] = 5] = "IsContainerWithLocals"; + })(ContainerFlags || (ContainerFlags = {})); function bindSourceFile(file) { var start = new Date().getTime(); bindSourceFileWorker(file); @@ -3646,46 +3809,48 @@ var ts; var container; var blockScopeContainer; var lastContainer; + // 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). + var inStrictMode = !!file.externalModuleIndicator; var symbolCount = 0; var Symbol = ts.objectAllocator.getSymbolConstructor(); + var classifiableNames = {}; if (!file.locals) { - file.locals = {}; - container = file; - setBlockScopeContainer(file, false); bind(file); file.symbolCount = symbolCount; + file.classifiableNames = classifiableNames; } + return; function createSymbol(flags, name) { symbolCount++; return new Symbol(flags, name); } - function setBlockScopeContainer(node, cleanLocals) { - blockScopeContainer = node; - if (cleanLocals) { - blockScopeContainer.locals = undefined; - } - } - function addDeclarationToSymbol(symbol, node, symbolKind) { - symbol.flags |= symbolKind; - if (!symbol.declarations) - symbol.declarations = []; - symbol.declarations.push(node); - if (symbolKind & 1952 /* HasExports */ && !symbol.exports) - symbol.exports = {}; - if (symbolKind & 6240 /* HasMembers */ && !symbol.members) - symbol.members = {}; + function addDeclarationToSymbol(symbol, node, symbolFlags) { + symbol.flags |= symbolFlags; node.symbol = symbol; - if (symbolKind & 107455 /* Value */ && !symbol.valueDeclaration) + if (!symbol.declarations) { + symbol.declarations = []; + } + symbol.declarations.push(node); + if (symbolFlags & 1952 /* HasExports */ && !symbol.exports) { + symbol.exports = {}; + } + if (symbolFlags & 6240 /* HasMembers */ && !symbol.members) { + symbol.members = {}; + } + if (symbolFlags & 107455 /* Value */ && !symbol.valueDeclaration) { 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) { if (node.name) { - if (node.kind === 206 /* ModuleDeclaration */ && node.name.kind === 8 /* StringLiteral */) { + if (node.kind === 208 /* ModuleDeclaration */ && node.name.kind === 8 /* StringLiteral */) { return '"' + node.name.text + '"'; } - if (node.name.kind === 128 /* ComputedPropertyName */) { + if (node.name.kind === 129 /* ComputedPropertyName */) { var nameExpression = node.name.expression; ts.Debug.assert(ts.isWellKnownSymbolSyntactically(nameExpression)); return ts.getPropertyNameForKnownSymbolName(nameExpression.name.text); @@ -3693,35 +3858,58 @@ var ts; return node.name.text; } switch (node.kind) { - case 144 /* ConstructorType */: - case 136 /* Constructor */: + case 137 /* Constructor */: return "__constructor"; - case 143 /* FunctionType */: - case 139 /* CallSignature */: + case 145 /* FunctionType */: + case 140 /* CallSignature */: return "__call"; - case 140 /* ConstructSignature */: + case 146 /* ConstructorType */: + case 141 /* ConstructSignature */: return "__new"; - case 141 /* IndexSignature */: + case 142 /* IndexSignature */: return "__index"; - case 216 /* ExportDeclaration */: + case 218 /* ExportDeclaration */: return "__export"; - case 215 /* ExportAssignment */: + case 217 /* ExportAssignment */: return node.isExportEquals ? "export=" : "default"; - case 201 /* FunctionDeclaration */: - case 202 /* ClassDeclaration */: + case 203 /* FunctionDeclaration */: + case 204 /* ClassDeclaration */: return node.flags & 256 /* Default */ ? "default" : undefined; } } function getDisplayName(node) { return node.name ? ts.declarationNameToString(node.name) : getDeclarationName(node); } - function declareSymbol(symbols, parent, node, includes, excludes) { + function declareSymbol(symbolTable, parent, node, includes, excludes) { ts.Debug.assert(!ts.hasDynamicName(node)); // The exported symbol for an export default function/class node is always named "default" var name = node.flags & 256 /* Default */ && parent ? "default" : getDeclarationName(node); var symbol; if (name !== undefined) { - symbol = ts.hasProperty(symbols, name) ? symbols[name] : (symbols[name] = createSymbol(0, name)); + // 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 + // witht he '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. + // + // 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 = ts.hasProperty(symbolTable, name) + ? symbolTable[name] + : (symbolTable[name] = createSymbol(0 /* None */, name)); + if (name && (includes & 788448 /* Classifiable */)) { + classifiableNames[name] = name; + } if (symbol.flags & excludes) { if (node.name) { node.name.parent = node; @@ -3735,39 +3923,24 @@ var ts; file.bindDiagnostics.push(ts.createDiagnosticForNode(declaration.name || declaration, message, getDisplayName(declaration))); }); file.bindDiagnostics.push(ts.createDiagnosticForNode(node.name || node, message, getDisplayName(node))); - symbol = createSymbol(0, name); + symbol = createSymbol(0 /* None */, name); } } else { - symbol = createSymbol(0, "__missing"); + symbol = createSymbol(0 /* None */, "__missing"); } addDeclarationToSymbol(symbol, node, includes); symbol.parent = parent; - if ((node.kind === 202 /* ClassDeclaration */ || node.kind === 175 /* ClassExpression */) && symbol.exports) { - // 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 prototypeSymbol = createSymbol(4 /* Property */ | 134217728 /* Prototype */, "prototype"); - if (ts.hasProperty(symbol.exports, prototypeSymbol.name)) { - if (node.name) { - node.name.parent = node; - } - file.bindDiagnostics.push(ts.createDiagnosticForNode(symbol.exports[prototypeSymbol.name].declarations[0], ts.Diagnostics.Duplicate_identifier_0, prototypeSymbol.name)); - } - symbol.exports[prototypeSymbol.name] = prototypeSymbol; - prototypeSymbol.parent = symbol; - } return symbol; } - function declareModuleMember(node, symbolKind, symbolExcludes) { + function declareModuleMember(node, symbolFlags, symbolExcludes) { var hasExportModifier = ts.getCombinedNodeFlags(node) & 1 /* Export */; - if (symbolKind & 8388608 /* Alias */) { - if (node.kind === 218 /* ExportSpecifier */ || (node.kind === 209 /* ImportEqualsDeclaration */ && hasExportModifier)) { - declareSymbol(container.symbol.exports, container.symbol, node, symbolKind, symbolExcludes); + if (symbolFlags & 8388608 /* Alias */) { + if (node.kind === 220 /* ExportSpecifier */ || (node.kind === 211 /* ImportEqualsDeclaration */ && hasExportModifier)) { + return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); } else { - declareSymbol(container.locals, undefined, node, symbolKind, symbolExcludes); + return declareSymbol(container.locals, undefined, node, symbolFlags, symbolExcludes); } } else { @@ -3783,108 +3956,200 @@ var ts; // 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. if (hasExportModifier || container.flags & 65536 /* ExportContext */) { - var exportKind = (symbolKind & 107455 /* Value */ ? 1048576 /* ExportValue */ : 0) | - (symbolKind & 793056 /* Type */ ? 2097152 /* ExportType */ : 0) | - (symbolKind & 1536 /* Namespace */ ? 4194304 /* ExportNamespace */ : 0); + var exportKind = (symbolFlags & 107455 /* Value */ ? 1048576 /* ExportValue */ : 0) | + (symbolFlags & 793056 /* Type */ ? 2097152 /* ExportType */ : 0) | + (symbolFlags & 1536 /* Namespace */ ? 4194304 /* ExportNamespace */ : 0); var local = declareSymbol(container.locals, undefined, node, exportKind, symbolExcludes); - local.exportSymbol = declareSymbol(container.symbol.exports, container.symbol, node, symbolKind, symbolExcludes); + local.exportSymbol = declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); node.localSymbol = local; + return local; } else { - declareSymbol(container.locals, undefined, node, symbolKind, symbolExcludes); + return declareSymbol(container.locals, 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 bindChildren(node, symbolKind, isBlockScopeContainer) { - if (symbolKind & 255504 /* HasLocals */) { - node.locals = {}; - } + // 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 bindChildren(node) { + // Before we recurse into a node's chilren, 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 saveParent = parent; var saveContainer = container; var savedBlockScopeContainer = blockScopeContainer; + // This node will now be set as the parent of all of its children as we recurse into them. parent = node; - if (symbolKind & 262128 /* IsContainer */) { - container = node; + // 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 accidently move any stale data forward from + // a previous compilation. + var containerFlags = getContainerFlags(node); + if (containerFlags & 1 /* IsContainer */) { + container = blockScopeContainer = node; + if (containerFlags & 4 /* HasLocals */) { + container.locals = {}; + } addToContainerChain(container); } - if (isBlockScopeContainer) { - // in incremental scenarios we might reuse nodes that already have locals being allocated - // during the bind step these locals should be dropped to prevent using stale data. - // locals should always be dropped unless they were previously initialized by the binder - // these cases are: - // - node has locals (symbolKind & HasLocals) !== 0 - // - node is a source file - setBlockScopeContainer(node, (symbolKind & 255504 /* HasLocals */) === 0 && node.kind !== 228 /* SourceFile */); + else if (containerFlags & 2 /* IsBlockScopedContainer */) { + blockScopeContainer = node; + blockScopeContainer.locals = undefined; } ts.forEachChild(node, bind); container = saveContainer; parent = saveParent; blockScopeContainer = savedBlockScopeContainer; } - function addToContainerChain(node) { - if (lastContainer) { - lastContainer.nextContainer = node; + function getContainerFlags(node) { + switch (node.kind) { + case 177 /* ClassExpression */: + case 204 /* ClassDeclaration */: + case 205 /* InterfaceDeclaration */: + case 207 /* EnumDeclaration */: + case 148 /* TypeLiteral */: + case 157 /* ObjectLiteralExpression */: + return 1 /* IsContainer */; + case 140 /* CallSignature */: + case 141 /* ConstructSignature */: + case 142 /* IndexSignature */: + case 136 /* MethodDeclaration */: + case 135 /* MethodSignature */: + case 203 /* FunctionDeclaration */: + case 137 /* Constructor */: + case 138 /* GetAccessor */: + case 139 /* SetAccessor */: + case 145 /* FunctionType */: + case 146 /* ConstructorType */: + case 165 /* FunctionExpression */: + case 166 /* ArrowFunction */: + case 208 /* ModuleDeclaration */: + case 230 /* SourceFile */: + case 206 /* TypeAliasDeclaration */: + return 5 /* IsContainerWithLocals */; + case 226 /* CatchClause */: + case 189 /* ForStatement */: + case 190 /* ForInStatement */: + case 191 /* ForOfStatement */: + case 210 /* CaseBlock */: + return 2 /* IsBlockScopedContainer */; + case 182 /* 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. Othewise '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 */; } - lastContainer = node; + return 0 /* None */; } - function bindDeclaration(node, symbolKind, symbolExcludes, isBlockScopeContainer) { - switch (container.kind) { - case 206 /* ModuleDeclaration */: - declareModuleMember(node, symbolKind, symbolExcludes); - break; - case 228 /* SourceFile */: - if (ts.isExternalModule(container)) { - declareModuleMember(node, symbolKind, symbolExcludes); - break; - } - case 143 /* FunctionType */: - case 144 /* ConstructorType */: - case 139 /* CallSignature */: - case 140 /* ConstructSignature */: - case 141 /* IndexSignature */: - case 135 /* MethodDeclaration */: - case 134 /* MethodSignature */: - case 136 /* Constructor */: - case 137 /* GetAccessor */: - case 138 /* SetAccessor */: - case 201 /* FunctionDeclaration */: - case 163 /* FunctionExpression */: - case 164 /* ArrowFunction */: - declareSymbol(container.locals, undefined, node, symbolKind, symbolExcludes); - break; - case 175 /* ClassExpression */: - case 202 /* ClassDeclaration */: - if (node.flags & 128 /* Static */) { - declareSymbol(container.symbol.exports, container.symbol, node, symbolKind, symbolExcludes); - break; - } - case 146 /* TypeLiteral */: - case 155 /* ObjectLiteralExpression */: - case 203 /* InterfaceDeclaration */: - declareSymbol(container.symbol.members, container.symbol, node, symbolKind, symbolExcludes); - break; - case 205 /* EnumDeclaration */: - declareSymbol(container.symbol.exports, container.symbol, node, symbolKind, symbolExcludes); - break; + function addToContainerChain(next) { + if (lastContainer) { + lastContainer.nextContainer = next; } - bindChildren(node, symbolKind, isBlockScopeContainer); + lastContainer = next; + } + function declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes) { + // Just call this directly so that the return type of this function stays "void". + 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 208 /* ModuleDeclaration */: + return declareModuleMember(node, symbolFlags, symbolExcludes); + case 230 /* SourceFile */: + return declareSourceFileMember(node, symbolFlags, symbolExcludes); + case 177 /* ClassExpression */: + case 204 /* ClassDeclaration */: + return declareClassMember(node, symbolFlags, symbolExcludes); + case 207 /* EnumDeclaration */: + return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); + case 148 /* TypeLiteral */: + case 157 /* ObjectLiteralExpression */: + case 205 /* InterfaceDeclaration */: + // 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 145 /* FunctionType */: + case 146 /* ConstructorType */: + case 140 /* CallSignature */: + case 141 /* ConstructSignature */: + case 142 /* IndexSignature */: + case 136 /* MethodDeclaration */: + case 135 /* MethodSignature */: + case 137 /* Constructor */: + case 138 /* GetAccessor */: + case 139 /* SetAccessor */: + case 203 /* FunctionDeclaration */: + case 165 /* FunctionExpression */: + case 166 /* ArrowFunction */: + case 206 /* TypeAliasDeclaration */: + // 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, undefined, node, symbolFlags, symbolExcludes); + } + } + function declareClassMember(node, symbolFlags, symbolExcludes) { + return node.flags & 128 /* 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, undefined, node, symbolFlags, symbolExcludes); } function isAmbientContext(node) { while (node) { - if (node.flags & 2 /* Ambient */) + if (node.flags & 2 /* Ambient */) { return true; + } node = node.parent; } return false; } function hasExportDeclarations(node) { - var body = node.kind === 228 /* SourceFile */ ? node : node.body; - if (body.kind === 228 /* SourceFile */ || body.kind === 207 /* ModuleBlock */) { + var body = node.kind === 230 /* SourceFile */ ? node : node.body; + if (body.kind === 230 /* SourceFile */ || body.kind === 209 /* ModuleBlock */) { for (var _i = 0, _a = body.statements; _i < _a.length; _i++) { var stat = _a[_i]; - if (stat.kind === 216 /* ExportDeclaration */ || stat.kind === 215 /* ExportAssignment */) { + if (stat.kind === 218 /* ExportDeclaration */ || stat.kind === 217 /* ExportAssignment */) { return true; } } @@ -3904,15 +4169,15 @@ var ts; function bindModuleDeclaration(node) { setExportContextFlag(node); if (node.name.kind === 8 /* StringLiteral */) { - bindDeclaration(node, 512 /* ValueModule */, 106639 /* ValueModuleExcludes */, true); + declareSymbolAndAddToSymbolTable(node, 512 /* ValueModule */, 106639 /* ValueModuleExcludes */); } else { var state = getModuleInstanceState(node); if (state === 0 /* NonInstantiated */) { - bindDeclaration(node, 1024 /* NamespaceModule */, 0 /* NamespaceModuleExcludes */, true); + declareSymbolAndAddToSymbolTable(node, 1024 /* NamespaceModule */, 0 /* NamespaceModuleExcludes */); } else { - bindDeclaration(node, 512 /* ValueModule */, 106639 /* ValueModuleExcludes */, true); + declareSymbolAndAddToSymbolTable(node, 512 /* ValueModule */, 106639 /* ValueModuleExcludes */); var currentModuleIsConstEnumOnly = state === 2 /* ConstEnumOnly */; if (node.symbol.constEnumOnlyModule === undefined) { // non-merged case - use the current state @@ -3934,28 +4199,61 @@ var ts; // 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 */); - bindChildren(node, 131072 /* Signature */, false); var typeLiteralSymbol = createSymbol(2048 /* TypeLiteral */, "__type"); addDeclarationToSymbol(typeLiteralSymbol, node, 2048 /* TypeLiteral */); - typeLiteralSymbol.members = {}; - typeLiteralSymbol.members[node.kind === 143 /* FunctionType */ ? "__call" : "__new"] = symbol; + typeLiteralSymbol.members = (_a = {}, _a[symbol.name] = symbol, _a); + var _a; } - function bindAnonymousDeclaration(node, symbolKind, name, isBlockScopeContainer) { - var symbol = createSymbol(symbolKind, name); - addDeclarationToSymbol(symbol, node, symbolKind); - bindChildren(node, symbolKind, isBlockScopeContainer); + function bindObjectLiteralExpression(node) { + var ElementKind; + (function (ElementKind) { + ElementKind[ElementKind["Property"] = 1] = "Property"; + ElementKind[ElementKind["Accessor"] = 2] = "Accessor"; + })(ElementKind || (ElementKind = {})); + if (inStrictMode) { + var seen = {}; + for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { + var prop = _a[_i]; + if (prop.name.kind !== 65 /* Identifier */) { + continue; + } + var identifier = prop.name; + // ECMA-262 11.1.5 Object Initialiser + // 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 === 227 /* PropertyAssignment */ || prop.kind === 228 /* ShorthandPropertyAssignment */ || prop.kind === 136 /* MethodDeclaration */ + ? 1 /* Property */ + : 2 /* Accessor */; + var existingKind = seen[identifier.text]; + if (!existingKind) { + seen[identifier.text] = currentKind; + continue; + } + if (currentKind === 1 /* Property */ && existingKind === 1 /* Property */) { + var span = ts.getErrorSpanForNode(file, identifier); + file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, ts.Diagnostics.An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode)); + } + } + } + return bindAnonymousDeclaration(node, 4096 /* ObjectLiteral */, "__object"); } - function bindCatchVariableDeclaration(node) { - bindChildren(node, 0, true); + function bindAnonymousDeclaration(node, symbolFlags, name) { + var symbol = createSymbol(symbolFlags, name); + addDeclarationToSymbol(symbol, node, symbolFlags); } - function bindBlockScopedDeclaration(node, symbolKind, symbolExcludes) { + function bindBlockScopedDeclaration(node, symbolFlags, symbolExcludes) { switch (blockScopeContainer.kind) { - case 206 /* ModuleDeclaration */: - declareModuleMember(node, symbolKind, symbolExcludes); + case 208 /* ModuleDeclaration */: + declareModuleMember(node, symbolFlags, symbolExcludes); break; - case 228 /* SourceFile */: + case 230 /* SourceFile */: if (ts.isExternalModule(container)) { - declareModuleMember(node, symbolKind, symbolExcludes); + declareModuleMember(node, symbolFlags, symbolExcludes); break; } // fall through. @@ -3964,211 +4262,394 @@ var ts; blockScopeContainer.locals = {}; addToContainerChain(blockScopeContainer); } - declareSymbol(blockScopeContainer.locals, undefined, node, symbolKind, symbolExcludes); + declareSymbol(blockScopeContainer.locals, undefined, node, symbolFlags, symbolExcludes); } - bindChildren(node, symbolKind, false); } 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 >= 102 /* FirstFutureReservedWord */ && + node.originalKeywordKind <= 110 /* LastFutureReservedWord */ && + !ts.isIdentifierName(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.getAncestor(node, 204 /* ClassDeclaration */) || ts.getAncestor(node, 177 /* ClassExpression */)) { + 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 === 65 /* 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 = ts.getErrorSpanForNode(file, node.expression); + file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, ts.Diagnostics.delete_cannot_be_called_on_an_identifier_in_strict_mode)); + } + } + function isEvalOrArgumentsIdentifier(node) { + return node.kind === 65 /* Identifier */ && + (node.text === "eval" || node.text === "arguments"); + } + function checkStrictModeEvalOrArguments(contextNode, name) { + if (name && name.kind === 65 /* 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 = ts.getErrorSpanForNode(file, name); + file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.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.getAncestor(node, 204 /* ClassDeclaration */) || ts.getAncestor(node, 177 /* ClassExpression */)) { + 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 checkStrictModeNumericLiteral(node) { + if (inStrictMode && node.flags & 16384 /* OctalLiteral */) { + 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 === 38 /* PlusPlusToken */ || node.operator === 39 /* MinusMinusToken */) { + checkStrictModeEvalOrArguments(node, node.operand); + } + } + } + function checkStrictModeWithStatement(node) { + // Grammar checking for withStatement + if (inStrictMode) { + grammarErrorOnFirstToken(node, ts.Diagnostics.with_statements_are_not_allowed_in_strict_mode); + } + } + function grammarErrorOnFirstToken(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) { node.parent = parent; + var savedInStrictMode = inStrictMode; + if (!savedInStrictMode) { + updateStrictMode(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. + bindChildren(node); + inStrictMode = savedInStrictMode; + } + function updateStrictMode(node) { switch (node.kind) { - case 129 /* TypeParameter */: - bindDeclaration(node, 262144 /* TypeParameter */, 530912 /* TypeParameterExcludes */, false); - break; - case 130 /* Parameter */: - bindParameter(node); - break; - case 199 /* VariableDeclaration */: - case 153 /* BindingElement */: - if (ts.isBindingPattern(node.name)) { - bindChildren(node, 0, false); + case 230 /* SourceFile */: + case 209 /* ModuleBlock */: + updateStrictModeStatementList(node.statements); + return; + case 182 /* Block */: + if (ts.isFunctionLike(node.parent)) { + updateStrictModeStatementList(node.statements); } - else 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 - bindDeclaration(node, 1 /* FunctionScopedVariable */, 107455 /* ParameterExcludes */, false); - } - else { - bindDeclaration(node, 1 /* FunctionScopedVariable */, 107454 /* FunctionScopedVariableExcludes */, false); - } - break; - case 133 /* PropertyDeclaration */: - case 132 /* PropertySignature */: - bindPropertyOrMethodOrAccessor(node, 4 /* Property */ | (node.questionToken ? 536870912 /* Optional */ : 0), 107455 /* PropertyExcludes */, false); - break; - case 225 /* PropertyAssignment */: - case 226 /* ShorthandPropertyAssignment */: - bindPropertyOrMethodOrAccessor(node, 4 /* Property */, 107455 /* PropertyExcludes */, false); - break; - case 227 /* EnumMember */: - bindPropertyOrMethodOrAccessor(node, 8 /* EnumMember */, 107455 /* EnumMemberExcludes */, false); - break; - case 139 /* CallSignature */: - case 140 /* ConstructSignature */: - case 141 /* IndexSignature */: - bindDeclaration(node, 131072 /* Signature */, 0, false); - break; - case 135 /* MethodDeclaration */: - case 134 /* MethodSignature */: + return; + case 204 /* ClassDeclaration */: + case 177 /* ClassExpression */: + // All classes are automatically in strict mode in ES6. + inStrictMode = true; + return; + } + } + function updateStrictModeStatementList(statements) { + for (var _i = 0; _i < statements.length; _i++) { + var statement = statements[_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) { + case 65 /* Identifier */: + return checkStrictModeIdentifier(node); + case 172 /* BinaryExpression */: + return checkStrictModeBinaryExpression(node); + case 226 /* CatchClause */: + return checkStrictModeCatchClause(node); + case 167 /* DeleteExpression */: + return checkStrictModeDeleteExpression(node); + case 7 /* NumericLiteral */: + return checkStrictModeNumericLiteral(node); + case 171 /* PostfixUnaryExpression */: + return checkStrictModePostfixUnaryExpression(node); + case 170 /* PrefixUnaryExpression */: + return checkStrictModePrefixUnaryExpression(node); + case 195 /* WithStatement */: + return checkStrictModeWithStatement(node); + case 130 /* TypeParameter */: + return declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 530912 /* TypeParameterExcludes */); + case 131 /* Parameter */: + return bindParameter(node); + case 201 /* VariableDeclaration */: + case 155 /* BindingElement */: + return bindVariableDeclarationOrBindingElement(node); + case 134 /* PropertyDeclaration */: + case 133 /* PropertySignature */: + return bindPropertyOrMethodOrAccessor(node, 4 /* Property */ | (node.questionToken ? 536870912 /* Optional */ : 0 /* None */), 107455 /* PropertyExcludes */); + case 227 /* PropertyAssignment */: + case 228 /* ShorthandPropertyAssignment */: + return bindPropertyOrMethodOrAccessor(node, 4 /* Property */, 107455 /* PropertyExcludes */); + case 229 /* EnumMember */: + return bindPropertyOrMethodOrAccessor(node, 8 /* EnumMember */, 107455 /* EnumMemberExcludes */); + case 140 /* CallSignature */: + case 141 /* ConstructSignature */: + case 142 /* IndexSignature */: + return declareSymbolAndAddToSymbolTable(node, 131072 /* Signature */, 0 /* None */); + case 136 /* MethodDeclaration */: + case 135 /* 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. - bindPropertyOrMethodOrAccessor(node, 8192 /* Method */ | (node.questionToken ? 536870912 /* Optional */ : 0), ts.isObjectLiteralMethod(node) ? 107455 /* PropertyExcludes */ : 99263 /* MethodExcludes */, true); - break; - case 201 /* FunctionDeclaration */: - bindDeclaration(node, 16 /* Function */, 106927 /* FunctionExcludes */, true); - break; - case 136 /* Constructor */: - bindDeclaration(node, 16384 /* Constructor */, 0, true); - break; - case 137 /* GetAccessor */: - bindPropertyOrMethodOrAccessor(node, 32768 /* GetAccessor */, 41919 /* GetAccessorExcludes */, true); - break; - case 138 /* SetAccessor */: - bindPropertyOrMethodOrAccessor(node, 65536 /* SetAccessor */, 74687 /* SetAccessorExcludes */, true); - break; - case 143 /* FunctionType */: - case 144 /* ConstructorType */: - bindFunctionOrConstructorType(node); - break; - case 146 /* TypeLiteral */: - bindAnonymousDeclaration(node, 2048 /* TypeLiteral */, "__type", false); - break; - case 155 /* ObjectLiteralExpression */: - bindAnonymousDeclaration(node, 4096 /* ObjectLiteral */, "__object", false); - break; - case 163 /* FunctionExpression */: - case 164 /* ArrowFunction */: - bindAnonymousDeclaration(node, 16 /* Function */, "__function", true); - break; - case 175 /* ClassExpression */: - bindAnonymousDeclaration(node, 32 /* Class */, "__class", false); - break; - case 224 /* CatchClause */: - bindCatchVariableDeclaration(node); - break; - case 202 /* ClassDeclaration */: - bindBlockScopedDeclaration(node, 32 /* Class */, 899583 /* ClassExcludes */); - break; - case 203 /* InterfaceDeclaration */: - bindDeclaration(node, 64 /* Interface */, 792992 /* InterfaceExcludes */, false); - break; - case 204 /* TypeAliasDeclaration */: - bindDeclaration(node, 524288 /* TypeAlias */, 793056 /* TypeAliasExcludes */, false); - break; - case 205 /* EnumDeclaration */: - if (ts.isConst(node)) { - bindDeclaration(node, 128 /* ConstEnum */, 899967 /* ConstEnumExcludes */, false); - } - else { - bindDeclaration(node, 256 /* RegularEnum */, 899327 /* RegularEnumExcludes */, false); - } - break; - case 206 /* ModuleDeclaration */: - bindModuleDeclaration(node); - break; - case 209 /* ImportEqualsDeclaration */: - case 212 /* NamespaceImport */: - case 214 /* ImportSpecifier */: - case 218 /* ExportSpecifier */: - bindDeclaration(node, 8388608 /* Alias */, 8388608 /* AliasExcludes */, false); - break; - case 211 /* ImportClause */: - if (node.name) { - bindDeclaration(node, 8388608 /* Alias */, 8388608 /* AliasExcludes */, false); - } - else { - bindChildren(node, 0, false); - } - break; - case 216 /* ExportDeclaration */: - if (!node.exportClause) { - // All export * declarations are collected in an __export symbol - declareSymbol(container.symbol.exports, container.symbol, node, 1073741824 /* ExportStar */, 0); - } - bindChildren(node, 0, false); - break; - case 215 /* ExportAssignment */: - if (node.expression.kind === 65 /* Identifier */) { - // An export default clause with an identifier exports all meanings of that identifier - declareSymbol(container.symbol.exports, container.symbol, node, 8388608 /* Alias */, 107455 /* PropertyExcludes */ | 8388608 /* AliasExcludes */); - } - else { - // An export default clause with an expression exports a value - declareSymbol(container.symbol.exports, container.symbol, node, 4 /* Property */, 107455 /* PropertyExcludes */ | 8388608 /* AliasExcludes */); - } - bindChildren(node, 0, false); - break; - case 228 /* SourceFile */: - setExportContextFlag(node); - if (ts.isExternalModule(node)) { - bindAnonymousDeclaration(node, 512 /* ValueModule */, '"' + ts.removeFileExtension(node.fileName) + '"', true); - break; - } - case 180 /* Block */: - // do not treat function block a block-scope container - // all block-scope locals that reside in this block should go to the function locals. - // Otherwise this won't be considered as redeclaration of a block scoped local: - // function foo() { - // let x; - // let x; - // } - // 'let x' will be placed into the function locals and 'let x' - into the locals of the block - bindChildren(node, 0, !ts.isFunctionLike(node.parent)); - break; - case 224 /* CatchClause */: - case 187 /* ForStatement */: - case 188 /* ForInStatement */: - case 189 /* ForOfStatement */: - case 208 /* CaseBlock */: - bindChildren(node, 0, true); - break; - default: - var saveParent = parent; - parent = node; - ts.forEachChild(node, bind); - parent = saveParent; + return bindPropertyOrMethodOrAccessor(node, 8192 /* Method */ | (node.questionToken ? 536870912 /* Optional */ : 0 /* None */), ts.isObjectLiteralMethod(node) ? 107455 /* PropertyExcludes */ : 99263 /* MethodExcludes */); + case 203 /* FunctionDeclaration */: + checkStrictModeFunctionName(node); + return declareSymbolAndAddToSymbolTable(node, 16 /* Function */, 106927 /* FunctionExcludes */); + case 137 /* Constructor */: + return declareSymbolAndAddToSymbolTable(node, 16384 /* Constructor */, 0 /* None */); + case 138 /* GetAccessor */: + return bindPropertyOrMethodOrAccessor(node, 32768 /* GetAccessor */, 41919 /* GetAccessorExcludes */); + case 139 /* SetAccessor */: + return bindPropertyOrMethodOrAccessor(node, 65536 /* SetAccessor */, 74687 /* SetAccessorExcludes */); + case 145 /* FunctionType */: + case 146 /* ConstructorType */: + return bindFunctionOrConstructorType(node); + case 148 /* TypeLiteral */: + return bindAnonymousDeclaration(node, 2048 /* TypeLiteral */, "__type"); + case 157 /* ObjectLiteralExpression */: + return bindObjectLiteralExpression(node); + case 165 /* FunctionExpression */: + case 166 /* ArrowFunction */: + checkStrictModeFunctionName(node); + return bindAnonymousDeclaration(node, 16 /* Function */, "__function"); + case 177 /* ClassExpression */: + case 204 /* ClassDeclaration */: + return bindClassLikeDeclaration(node); + case 205 /* InterfaceDeclaration */: + return bindBlockScopedDeclaration(node, 64 /* Interface */, 792992 /* InterfaceExcludes */); + case 206 /* TypeAliasDeclaration */: + return bindBlockScopedDeclaration(node, 524288 /* TypeAlias */, 793056 /* TypeAliasExcludes */); + case 207 /* EnumDeclaration */: + return bindEnumDeclaration(node); + case 208 /* ModuleDeclaration */: + return bindModuleDeclaration(node); + case 211 /* ImportEqualsDeclaration */: + case 214 /* NamespaceImport */: + case 216 /* ImportSpecifier */: + case 220 /* ExportSpecifier */: + return declareSymbolAndAddToSymbolTable(node, 8388608 /* Alias */, 8388608 /* AliasExcludes */); + case 213 /* ImportClause */: + return bindImportClause(node); + case 218 /* ExportDeclaration */: + return bindExportDeclaration(node); + case 217 /* ExportAssignment */: + return bindExportAssignment(node); + case 230 /* SourceFile */: + return bindSourceFileIfExternalModule(); + } + } + function bindSourceFileIfExternalModule() { + setExportContextFlag(file); + if (ts.isExternalModule(file)) { + 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 if (node.expression.kind === 65 /* Identifier */) { + // An export default clause with an identifier exports all meanings of that identifier + declareSymbol(container.symbol.exports, container.symbol, node, 8388608 /* Alias */, 107455 /* PropertyExcludes */ | 8388608 /* AliasExcludes */); + } + else { + // An export default clause with an expression exports a value + declareSymbol(container.symbol.exports, container.symbol, node, 4 /* Property */, 107455 /* PropertyExcludes */ | 8388608 /* AliasExcludes */); + } + } + function bindExportDeclaration(node) { + if (!container.symbol || !container.symbol.exports) { + // Export * in some sort of block construct + bindAnonymousDeclaration(node, 1073741824 /* ExportStar */, getDeclarationName(node)); + } + else if (!node.exportClause) { + // All export * declarations are collected in an __export symbol + declareSymbol(container.symbol.exports, container.symbol, node, 1073741824 /* ExportStar */, 0 /* None */); + } + } + function bindImportClause(node) { + if (node.name) { + declareSymbolAndAddToSymbolTable(node, 8388608 /* Alias */, 8388608 /* AliasExcludes */); + } + } + function bindClassLikeDeclaration(node) { + if (node.kind === 204 /* ClassDeclaration */) { + bindBlockScopedDeclaration(node, 32 /* Class */, 899583 /* ClassExcludes */); + } + else { + bindAnonymousDeclaration(node, 32 /* Class */, "__class"); + } + 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 */ | 134217728 /* Prototype */, "prototype"); + if (ts.hasProperty(symbol.exports, prototypeSymbol.name)) { + if (node.name) { + node.name.parent = node; + } + file.bindDiagnostics.push(ts.createDiagnosticForNode(symbol.exports[prototypeSymbol.name].declarations[0], ts.Diagnostics.Duplicate_identifier_0, prototypeSymbol.name)); + } + symbol.exports[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) { + // 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), false); + bindAnonymousDeclaration(node, 1 /* FunctionScopedVariable */, getDestructuringParameterName(node)); } else { - bindDeclaration(node, 1 /* FunctionScopedVariable */, 107455 /* ParameterExcludes */, false); + declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 107455 /* ParameterExcludes */); } // If this is a property-parameter, then also declare the property symbol into the // containing class. if (node.flags & 112 /* AccessibilityModifier */ && - node.parent.kind === 136 /* Constructor */ && - (node.parent.parent.kind === 202 /* ClassDeclaration */ || node.parent.parent.kind === 175 /* ClassExpression */)) { + node.parent.kind === 137 /* Constructor */ && + (node.parent.parent.kind === 204 /* ClassDeclaration */ || node.parent.parent.kind === 177 /* ClassExpression */)) { var classDeclaration = node.parent.parent; declareSymbol(classDeclaration.symbol.members, classDeclaration.symbol, node, 4 /* Property */, 107455 /* PropertyExcludes */); } } - function bindPropertyOrMethodOrAccessor(node, symbolKind, symbolExcludes, isBlockScopeContainer) { - if (ts.hasDynamicName(node)) { - bindAnonymousDeclaration(node, symbolKind, "__computed", isBlockScopeContainer); - } - else { - bindDeclaration(node, symbolKind, symbolExcludes, isBlockScopeContainer); - } + function bindPropertyOrMethodOrAccessor(node, symbolFlags, symbolExcludes) { + return ts.hasDynamicName(node) + ? bindAnonymousDeclaration(node, symbolFlags, "__computed") + : declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes); } } })(ts || (ts = {})); @@ -4190,7 +4671,7 @@ var ts; // Pool writers to avoid needing to allocate them for every symbol we write. var stringWriters = []; function getSingleLineStringWriter() { - if (stringWriters.length == 0) { + if (stringWriters.length === 0) { var str = ""; var writeText = function (text) { return str += text; }; return { @@ -4226,11 +4707,11 @@ var ts; // Returns true if this node contains a parse error anywhere underneath it. function containsParseError(node) { aggregateChildData(node); - return (node.parserContextFlags & 64 /* ThisNodeOrAnySubNodesHasError */) !== 0; + return (node.parserContextFlags & 128 /* ThisNodeOrAnySubNodesHasError */) !== 0; } ts.containsParseError = containsParseError; function aggregateChildData(node) { - if (!(node.parserContextFlags & 128 /* HasAggregatedChildData */)) { + if (!(node.parserContextFlags & 256 /* HasAggregatedChildData */)) { // A node is considered to contain a parse error if: // a) the parser explicitly marked that it had an error // b) any of it's children reported that it had an error. @@ -4238,16 +4719,16 @@ var ts; ts.forEachChild(node, containsParseError); // If so, mark ourselves accordingly. if (thisNodeOrAnySubNodesHasError) { - node.parserContextFlags |= 64 /* ThisNodeOrAnySubNodesHasError */; + node.parserContextFlags |= 128 /* ThisNodeOrAnySubNodesHasError */; } // Also mark that we've propogated the child information to this node. This way we can // always consult the bit directly on this node without needing to check its children // again. - node.parserContextFlags |= 128 /* HasAggregatedChildData */; + node.parserContextFlags |= 256 /* HasAggregatedChildData */; } } function getSourceFileOfNode(node) { - while (node && node.kind !== 228 /* SourceFile */) { + while (node && node.kind !== 230 /* SourceFile */) { node = node.parent; } return node; @@ -4357,15 +4838,15 @@ var ts; return current; } switch (current.kind) { - case 228 /* SourceFile */: - case 208 /* CaseBlock */: - case 224 /* CatchClause */: - case 206 /* ModuleDeclaration */: - case 187 /* ForStatement */: - case 188 /* ForInStatement */: - case 189 /* ForOfStatement */: + case 230 /* SourceFile */: + case 210 /* CaseBlock */: + case 226 /* CatchClause */: + case 208 /* ModuleDeclaration */: + case 189 /* ForStatement */: + case 190 /* ForInStatement */: + case 191 /* ForOfStatement */: return current; - case 180 /* Block */: + case 182 /* Block */: // function block is not considered block-scope container // see comment in binder.ts: bind(...), case for SyntaxKind.Block if (!isFunctionLike(current.parent)) { @@ -4378,9 +4859,9 @@ var ts; ts.getEnclosingBlockScopeContainer = getEnclosingBlockScopeContainer; function isCatchClauseVariableDeclaration(declaration) { return declaration && - declaration.kind === 199 /* VariableDeclaration */ && + declaration.kind === 201 /* VariableDeclaration */ && declaration.parent && - declaration.parent.kind === 224 /* CatchClause */; + declaration.parent.kind === 226 /* CatchClause */; } ts.isCatchClauseVariableDeclaration = isCatchClauseVariableDeclaration; // Return display name of an identifier @@ -4419,7 +4900,7 @@ var ts; function getErrorSpanForNode(sourceFile, node) { var errorNode = node; switch (node.kind) { - case 228 /* SourceFile */: + case 230 /* SourceFile */: var pos_1 = ts.skipTrivia(sourceFile.text, 0, false); if (pos_1 === sourceFile.text.length) { // file is empty - return span for the beginning of the file @@ -4428,16 +4909,16 @@ var ts; return getSpanOfTokenAtPosition(sourceFile, pos_1); // This list is a work in progress. Add missing node kinds to improve their error // spans. - case 199 /* VariableDeclaration */: - case 153 /* BindingElement */: - case 202 /* ClassDeclaration */: - case 175 /* ClassExpression */: - case 203 /* InterfaceDeclaration */: - case 206 /* ModuleDeclaration */: - case 205 /* EnumDeclaration */: - case 227 /* EnumMember */: - case 201 /* FunctionDeclaration */: - case 163 /* FunctionExpression */: + case 201 /* VariableDeclaration */: + case 155 /* BindingElement */: + case 204 /* ClassDeclaration */: + case 177 /* ClassExpression */: + case 205 /* InterfaceDeclaration */: + case 208 /* ModuleDeclaration */: + case 207 /* EnumDeclaration */: + case 229 /* EnumMember */: + case 203 /* FunctionDeclaration */: + case 165 /* FunctionExpression */: errorNode = node.name; break; } @@ -4461,11 +4942,11 @@ var ts; } ts.isDeclarationFile = isDeclarationFile; function isConstEnumDeclaration(node) { - return node.kind === 205 /* EnumDeclaration */ && isConst(node); + return node.kind === 207 /* EnumDeclaration */ && isConst(node); } ts.isConstEnumDeclaration = isConstEnumDeclaration; function walkUpBindingElementsAndPatterns(node) { - while (node && (node.kind === 153 /* BindingElement */ || isBindingPattern(node))) { + while (node && (node.kind === 155 /* BindingElement */ || isBindingPattern(node))) { node = node.parent; } return node; @@ -4480,14 +4961,14 @@ var ts; function getCombinedNodeFlags(node) { node = walkUpBindingElementsAndPatterns(node); var flags = node.flags; - if (node.kind === 199 /* VariableDeclaration */) { + if (node.kind === 201 /* VariableDeclaration */) { node = node.parent; } - if (node && node.kind === 200 /* VariableDeclarationList */) { + if (node && node.kind === 202 /* VariableDeclarationList */) { flags |= node.flags; node = node.parent; } - if (node && node.kind === 181 /* VariableStatement */) { + if (node && node.kind === 183 /* VariableStatement */) { flags |= node.flags; } return flags; @@ -4502,12 +4983,12 @@ var ts; } ts.isLet = isLet; function isPrologueDirective(node) { - return node.kind === 183 /* ExpressionStatement */ && node.expression.kind === 8 /* StringLiteral */; + return node.kind === 185 /* ExpressionStatement */ && node.expression.kind === 8 /* StringLiteral */; } ts.isPrologueDirective = isPrologueDirective; function getLeadingCommentRangesOfNode(node, sourceFileOfNode) { // If parameter/type parameter, the prev token trailing comments are part of this node too - if (node.kind === 130 /* Parameter */ || node.kind === 129 /* TypeParameter */) { + if (node.kind === 131 /* Parameter */ || node.kind === 130 /* TypeParameter */) { // e.g. (/** blah */ a, /** blah */ b); // e.g.: ( // /** blah */ a, @@ -4530,45 +5011,165 @@ var ts; } ts.getJsDocComments = getJsDocComments; ts.fullTripleSlashReferencePathRegEx = /^(\/\/\/\s*/; + function isTypeNode(node) { + if (144 /* FirstTypeNode */ <= node.kind && node.kind <= 152 /* LastTypeNode */) { + return true; + } + switch (node.kind) { + case 112 /* AnyKeyword */: + case 121 /* NumberKeyword */: + case 123 /* StringKeyword */: + case 113 /* BooleanKeyword */: + case 124 /* SymbolKeyword */: + return true; + case 99 /* VoidKeyword */: + return node.parent.kind !== 169 /* VoidExpression */; + case 8 /* StringLiteral */: + // Specialized signatures can have string literals as their parameters' type names + return node.parent.kind === 131 /* Parameter */; + case 179 /* ExpressionWithTypeArguments */: + return !isExpressionWithTypeArgumentsInClassExtendsClause(node); + // Identifiers and qualified names may be type nodes, depending on their context. Climb + // above them to find the lowest container + case 65 /* Identifier */: + // If the identifier is the RHS of a qualified name, then it's a type iff its parent is. + if (node.parent.kind === 128 /* QualifiedName */ && node.parent.right === node) { + node = node.parent; + } + else if (node.parent.kind === 158 /* PropertyAccessExpression */ && node.parent.name === node) { + node = node.parent; + } + // fall through + case 128 /* QualifiedName */: + case 158 /* PropertyAccessExpression */: + // At this point, node is either a qualified name or an identifier + ts.Debug.assert(node.kind === 65 /* Identifier */ || node.kind === 128 /* QualifiedName */ || node.kind === 158 /* PropertyAccessExpression */, "'node' was expected to be a qualified name, identifier or property access in 'isTypeNode'."); + var parent_1 = node.parent; + if (parent_1.kind === 147 /* TypeQuery */) { + return false; + } + // Do not recursively call isTypeNode on the parent. In the example: + // + // let a: A.B.C; + // + // Calling isTypeNode would consider the qualified name A.B a type node. Only C or + // A.B.C is a type node. + if (144 /* FirstTypeNode */ <= parent_1.kind && parent_1.kind <= 152 /* LastTypeNode */) { + return true; + } + switch (parent_1.kind) { + case 179 /* ExpressionWithTypeArguments */: + return !isExpressionWithTypeArgumentsInClassExtendsClause(parent_1); + case 130 /* TypeParameter */: + return node === parent_1.constraint; + case 134 /* PropertyDeclaration */: + case 133 /* PropertySignature */: + case 131 /* Parameter */: + case 201 /* VariableDeclaration */: + return node === parent_1.type; + case 203 /* FunctionDeclaration */: + case 165 /* FunctionExpression */: + case 166 /* ArrowFunction */: + case 137 /* Constructor */: + case 136 /* MethodDeclaration */: + case 135 /* MethodSignature */: + case 138 /* GetAccessor */: + case 139 /* SetAccessor */: + return node === parent_1.type; + case 140 /* CallSignature */: + case 141 /* ConstructSignature */: + case 142 /* IndexSignature */: + return node === parent_1.type; + case 163 /* TypeAssertionExpression */: + return node === parent_1.type; + case 160 /* CallExpression */: + case 161 /* NewExpression */: + return parent_1.typeArguments && ts.indexOf(parent_1.typeArguments, node) >= 0; + case 162 /* TaggedTemplateExpression */: + // TODO (drosen): TaggedTemplateExpressions may eventually support type arguments. + return false; + } + } + return false; + } + ts.isTypeNode = isTypeNode; // 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) { return traverse(body); function traverse(node) { switch (node.kind) { - case 192 /* ReturnStatement */: + case 194 /* ReturnStatement */: return visitor(node); - case 208 /* CaseBlock */: - case 180 /* Block */: - case 184 /* IfStatement */: - case 185 /* DoStatement */: - case 186 /* WhileStatement */: - case 187 /* ForStatement */: - case 188 /* ForInStatement */: - case 189 /* ForOfStatement */: - case 193 /* WithStatement */: - case 194 /* SwitchStatement */: - case 221 /* CaseClause */: - case 222 /* DefaultClause */: - case 195 /* LabeledStatement */: - case 197 /* TryStatement */: - case 224 /* CatchClause */: + case 210 /* CaseBlock */: + case 182 /* Block */: + case 186 /* IfStatement */: + case 187 /* DoStatement */: + case 188 /* WhileStatement */: + case 189 /* ForStatement */: + case 190 /* ForInStatement */: + case 191 /* ForOfStatement */: + case 195 /* WithStatement */: + case 196 /* SwitchStatement */: + case 223 /* CaseClause */: + case 224 /* DefaultClause */: + case 197 /* LabeledStatement */: + case 199 /* TryStatement */: + case 226 /* CatchClause */: return ts.forEachChild(node, traverse); } } } ts.forEachReturnStatement = forEachReturnStatement; + function forEachYieldExpression(body, visitor) { + return traverse(body); + function traverse(node) { + switch (node.kind) { + case 175 /* YieldExpression */: + visitor(node); + var operand = node.expression; + if (operand) { + traverse(operand); + } + case 207 /* EnumDeclaration */: + case 205 /* InterfaceDeclaration */: + case 208 /* ModuleDeclaration */: + case 206 /* TypeAliasDeclaration */: + case 204 /* ClassDeclaration */: + // These are not allowed inside a generator now, but eventually they may be allowed + // as local types. Regardless, any yield statements contained within them should be + // skipped in this traversal. + return; + default: + if (isFunctionLike(node)) { + var name_4 = node.name; + if (name_4 && name_4.kind === 129 /* ComputedPropertyName */) { + // Note that we will not include methods/accessors of a class because they would require + // first descending into the class. This is by design. + traverse(name_4.expression); + return; + } + } + else if (!isTypeNode(node)) { + // This is the general case, which should include mostly expressions and statements. + // Also includes NodeArrays. + ts.forEachChild(node, traverse); + } + } + } + } + ts.forEachYieldExpression = forEachYieldExpression; function isVariableLike(node) { if (node) { switch (node.kind) { - case 153 /* BindingElement */: - case 227 /* EnumMember */: - case 130 /* Parameter */: - case 225 /* PropertyAssignment */: - case 133 /* PropertyDeclaration */: - case 132 /* PropertySignature */: - case 226 /* ShorthandPropertyAssignment */: - case 199 /* VariableDeclaration */: + case 155 /* BindingElement */: + case 229 /* EnumMember */: + case 131 /* Parameter */: + case 227 /* PropertyAssignment */: + case 134 /* PropertyDeclaration */: + case 133 /* PropertySignature */: + case 228 /* ShorthandPropertyAssignment */: + case 201 /* VariableDeclaration */: return true; } } @@ -4578,30 +5179,36 @@ var ts; function isAccessor(node) { if (node) { switch (node.kind) { - case 137 /* GetAccessor */: - case 138 /* SetAccessor */: + case 138 /* GetAccessor */: + case 139 /* SetAccessor */: return true; } } return false; } ts.isAccessor = isAccessor; + function isClassLike(node) { + if (node) { + return node.kind === 204 /* ClassDeclaration */ || node.kind === 177 /* ClassExpression */; + } + } + ts.isClassLike = isClassLike; function isFunctionLike(node) { if (node) { switch (node.kind) { - case 136 /* Constructor */: - case 163 /* FunctionExpression */: - case 201 /* FunctionDeclaration */: - case 164 /* ArrowFunction */: - case 135 /* MethodDeclaration */: - case 134 /* MethodSignature */: - case 137 /* GetAccessor */: - case 138 /* SetAccessor */: - case 139 /* CallSignature */: - case 140 /* ConstructSignature */: - case 141 /* IndexSignature */: - case 143 /* FunctionType */: - case 144 /* ConstructorType */: + case 137 /* Constructor */: + case 165 /* FunctionExpression */: + case 203 /* FunctionDeclaration */: + case 166 /* ArrowFunction */: + case 136 /* MethodDeclaration */: + case 135 /* MethodSignature */: + case 138 /* GetAccessor */: + case 139 /* SetAccessor */: + case 140 /* CallSignature */: + case 141 /* ConstructSignature */: + case 142 /* IndexSignature */: + case 145 /* FunctionType */: + case 146 /* ConstructorType */: return true; } } @@ -4609,11 +5216,11 @@ var ts; } ts.isFunctionLike = isFunctionLike; function isFunctionBlock(node) { - return node && node.kind === 180 /* Block */ && isFunctionLike(node.parent); + return node && node.kind === 182 /* Block */ && isFunctionLike(node.parent); } ts.isFunctionBlock = isFunctionBlock; function isObjectLiteralMethod(node) { - return node && node.kind === 135 /* MethodDeclaration */ && node.parent.kind === 155 /* ObjectLiteralExpression */; + return node && node.kind === 136 /* MethodDeclaration */ && node.parent.kind === 157 /* ObjectLiteralExpression */; } ts.isObjectLiteralMethod = isObjectLiteralMethod; function getContainingFunction(node) { @@ -4632,12 +5239,12 @@ var ts; return undefined; } switch (node.kind) { - case 128 /* ComputedPropertyName */: + case 129 /* ComputedPropertyName */: // If the grandparent node is an object literal (as opposed to a class), // 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 (node.parent.parent.kind === 202 /* ClassDeclaration */) { + if (node.parent.parent.kind === 204 /* ClassDeclaration */) { return node; } // If this is a computed property, then the parent should not @@ -4647,9 +5254,9 @@ var ts; // the *body* of the container. node = node.parent; break; - case 131 /* Decorator */: + case 132 /* Decorator */: // Decorators are always applied outside of the body of a class or method. - if (node.parent.kind === 130 /* Parameter */ && isClassElement(node.parent.parent)) { + if (node.parent.kind === 131 /* Parameter */ && 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; @@ -4660,23 +5267,23 @@ var ts; node = node.parent; } break; - case 164 /* ArrowFunction */: + case 166 /* ArrowFunction */: if (!includeArrowFunctions) { continue; } // Fall through - case 201 /* FunctionDeclaration */: - case 163 /* FunctionExpression */: - case 206 /* ModuleDeclaration */: - case 133 /* PropertyDeclaration */: - case 132 /* PropertySignature */: - case 135 /* MethodDeclaration */: - case 134 /* MethodSignature */: - case 136 /* Constructor */: - case 137 /* GetAccessor */: - case 138 /* SetAccessor */: - case 205 /* EnumDeclaration */: - case 228 /* SourceFile */: + case 203 /* FunctionDeclaration */: + case 165 /* FunctionExpression */: + case 208 /* ModuleDeclaration */: + case 134 /* PropertyDeclaration */: + case 133 /* PropertySignature */: + case 136 /* MethodDeclaration */: + case 135 /* MethodSignature */: + case 137 /* Constructor */: + case 138 /* GetAccessor */: + case 139 /* SetAccessor */: + case 207 /* EnumDeclaration */: + case 230 /* SourceFile */: return node; } } @@ -4688,12 +5295,12 @@ var ts; if (!node) return node; switch (node.kind) { - case 128 /* ComputedPropertyName */: + case 129 /* ComputedPropertyName */: // If the grandparent node is an object literal (as opposed to a class), // then the computed property is not a 'super' container. // A computed property name in a class needs to be a super container // so that we can error on it. - if (node.parent.parent.kind === 202 /* ClassDeclaration */) { + if (node.parent.parent.kind === 204 /* ClassDeclaration */) { return node; } // If this is a computed property, then the parent should not @@ -4703,9 +5310,9 @@ var ts; // the *body* of the container. node = node.parent; break; - case 131 /* Decorator */: + case 132 /* Decorator */: // Decorators are always applied outside of the body of a class or method. - if (node.parent.kind === 130 /* Parameter */ && isClassElement(node.parent.parent)) { + if (node.parent.kind === 131 /* Parameter */ && 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; @@ -4716,26 +5323,26 @@ var ts; node = node.parent; } break; - case 201 /* FunctionDeclaration */: - case 163 /* FunctionExpression */: - case 164 /* ArrowFunction */: + case 203 /* FunctionDeclaration */: + case 165 /* FunctionExpression */: + case 166 /* ArrowFunction */: if (!includeFunctions) { continue; } - case 133 /* PropertyDeclaration */: - case 132 /* PropertySignature */: - case 135 /* MethodDeclaration */: - case 134 /* MethodSignature */: - case 136 /* Constructor */: - case 137 /* GetAccessor */: - case 138 /* SetAccessor */: + case 134 /* PropertyDeclaration */: + case 133 /* PropertySignature */: + case 136 /* MethodDeclaration */: + case 135 /* MethodSignature */: + case 137 /* Constructor */: + case 138 /* GetAccessor */: + case 139 /* SetAccessor */: return node; } } } ts.getSuperContainer = getSuperContainer; function getInvokedExpression(node) { - if (node.kind === 160 /* TaggedTemplateExpression */) { + if (node.kind === 162 /* TaggedTemplateExpression */) { return node.tag; } // Will either be a CallExpression or NewExpression. @@ -4744,44 +5351,44 @@ var ts; ts.getInvokedExpression = getInvokedExpression; function nodeCanBeDecorated(node) { switch (node.kind) { - case 202 /* ClassDeclaration */: + case 204 /* ClassDeclaration */: // classes are valid targets return true; - case 133 /* PropertyDeclaration */: + case 134 /* PropertyDeclaration */: // property declarations are valid if their parent is a class declaration. - return node.parent.kind === 202 /* ClassDeclaration */; - case 130 /* Parameter */: + return node.parent.kind === 204 /* ClassDeclaration */; + case 131 /* Parameter */: // if the parameter's parent has a body and its grandparent is a class declaration, this is a valid target; - return node.parent.body && node.parent.parent.kind === 202 /* ClassDeclaration */; - case 137 /* GetAccessor */: - case 138 /* SetAccessor */: - case 135 /* MethodDeclaration */: + return node.parent.body && node.parent.parent.kind === 204 /* ClassDeclaration */; + case 138 /* GetAccessor */: + case 139 /* SetAccessor */: + case 136 /* MethodDeclaration */: // if this method has a body and its parent is a class declaration, this is a valid target. - return node.body && node.parent.kind === 202 /* ClassDeclaration */; + return node.body && node.parent.kind === 204 /* ClassDeclaration */; } return false; } ts.nodeCanBeDecorated = nodeCanBeDecorated; function nodeIsDecorated(node) { switch (node.kind) { - case 202 /* ClassDeclaration */: + case 204 /* ClassDeclaration */: if (node.decorators) { return true; } return false; - case 133 /* PropertyDeclaration */: - case 130 /* Parameter */: + case 134 /* PropertyDeclaration */: + case 131 /* Parameter */: if (node.decorators) { return true; } return false; - case 137 /* GetAccessor */: + case 138 /* GetAccessor */: if (node.body && node.decorators) { return true; } return false; - case 135 /* MethodDeclaration */: - case 138 /* SetAccessor */: + case 136 /* MethodDeclaration */: + case 139 /* SetAccessor */: if (node.body && node.decorators) { return true; } @@ -4792,10 +5399,10 @@ var ts; ts.nodeIsDecorated = nodeIsDecorated; function childIsDecorated(node) { switch (node.kind) { - case 202 /* ClassDeclaration */: + case 204 /* ClassDeclaration */: return ts.forEach(node.members, nodeOrChildIsDecorated); - case 135 /* MethodDeclaration */: - case 138 /* SetAccessor */: + case 136 /* MethodDeclaration */: + case 139 /* SetAccessor */: return ts.forEach(node.parameters, nodeIsDecorated); } return false; @@ -4813,83 +5420,86 @@ var ts; case 95 /* TrueKeyword */: case 80 /* FalseKeyword */: case 9 /* RegularExpressionLiteral */: - case 154 /* ArrayLiteralExpression */: - case 155 /* ObjectLiteralExpression */: - case 156 /* PropertyAccessExpression */: - case 157 /* ElementAccessExpression */: - case 158 /* CallExpression */: - case 159 /* NewExpression */: - case 160 /* TaggedTemplateExpression */: - case 161 /* TypeAssertionExpression */: - case 162 /* ParenthesizedExpression */: - case 163 /* FunctionExpression */: - case 175 /* ClassExpression */: - case 164 /* ArrowFunction */: - case 167 /* VoidExpression */: - case 165 /* DeleteExpression */: - case 166 /* TypeOfExpression */: - case 168 /* PrefixUnaryExpression */: - case 169 /* PostfixUnaryExpression */: - case 170 /* BinaryExpression */: - case 171 /* ConditionalExpression */: - case 174 /* SpreadElementExpression */: - case 172 /* TemplateExpression */: + case 156 /* ArrayLiteralExpression */: + case 157 /* ObjectLiteralExpression */: + case 158 /* PropertyAccessExpression */: + case 159 /* ElementAccessExpression */: + case 160 /* CallExpression */: + case 161 /* NewExpression */: + case 162 /* TaggedTemplateExpression */: + case 163 /* TypeAssertionExpression */: + case 164 /* ParenthesizedExpression */: + case 165 /* FunctionExpression */: + case 177 /* ClassExpression */: + case 166 /* ArrowFunction */: + case 169 /* VoidExpression */: + case 167 /* DeleteExpression */: + case 168 /* TypeOfExpression */: + case 170 /* PrefixUnaryExpression */: + case 171 /* PostfixUnaryExpression */: + case 172 /* BinaryExpression */: + case 173 /* ConditionalExpression */: + case 176 /* SpreadElementExpression */: + case 174 /* TemplateExpression */: case 10 /* NoSubstitutionTemplateLiteral */: - case 176 /* OmittedExpression */: + case 178 /* OmittedExpression */: + case 175 /* YieldExpression */: return true; - case 127 /* QualifiedName */: - while (node.parent.kind === 127 /* QualifiedName */) { + case 128 /* QualifiedName */: + while (node.parent.kind === 128 /* QualifiedName */) { node = node.parent; } - return node.parent.kind === 145 /* TypeQuery */; + return node.parent.kind === 147 /* TypeQuery */; case 65 /* Identifier */: - if (node.parent.kind === 145 /* TypeQuery */) { + if (node.parent.kind === 147 /* TypeQuery */) { return true; } // fall through case 7 /* NumericLiteral */: case 8 /* StringLiteral */: - var parent_1 = node.parent; - switch (parent_1.kind) { - case 199 /* VariableDeclaration */: - case 130 /* Parameter */: - case 133 /* PropertyDeclaration */: - case 132 /* PropertySignature */: - case 227 /* EnumMember */: - case 225 /* PropertyAssignment */: - case 153 /* BindingElement */: - return parent_1.initializer === node; - case 183 /* ExpressionStatement */: - case 184 /* IfStatement */: - case 185 /* DoStatement */: - case 186 /* WhileStatement */: - case 192 /* ReturnStatement */: - case 193 /* WithStatement */: - case 194 /* SwitchStatement */: - case 221 /* CaseClause */: - case 196 /* ThrowStatement */: - case 194 /* SwitchStatement */: - return parent_1.expression === node; - case 187 /* ForStatement */: - var forStatement = parent_1; - return (forStatement.initializer === node && forStatement.initializer.kind !== 200 /* VariableDeclarationList */) || + var parent_2 = node.parent; + switch (parent_2.kind) { + case 201 /* VariableDeclaration */: + case 131 /* Parameter */: + case 134 /* PropertyDeclaration */: + case 133 /* PropertySignature */: + case 229 /* EnumMember */: + case 227 /* PropertyAssignment */: + case 155 /* BindingElement */: + return parent_2.initializer === node; + case 185 /* ExpressionStatement */: + case 186 /* IfStatement */: + case 187 /* DoStatement */: + case 188 /* WhileStatement */: + case 194 /* ReturnStatement */: + case 195 /* WithStatement */: + case 196 /* SwitchStatement */: + case 223 /* CaseClause */: + case 198 /* ThrowStatement */: + case 196 /* SwitchStatement */: + return parent_2.expression === node; + case 189 /* ForStatement */: + var forStatement = parent_2; + return (forStatement.initializer === node && forStatement.initializer.kind !== 202 /* VariableDeclarationList */) || forStatement.condition === node || forStatement.incrementor === node; - case 188 /* ForInStatement */: - case 189 /* ForOfStatement */: - var forInStatement = parent_1; - return (forInStatement.initializer === node && forInStatement.initializer.kind !== 200 /* VariableDeclarationList */) || + case 190 /* ForInStatement */: + case 191 /* ForOfStatement */: + var forInStatement = parent_2; + return (forInStatement.initializer === node && forInStatement.initializer.kind !== 202 /* VariableDeclarationList */) || forInStatement.expression === node; - case 161 /* TypeAssertionExpression */: - return node === parent_1.expression; - case 178 /* TemplateSpan */: - return node === parent_1.expression; - case 128 /* ComputedPropertyName */: - return node === parent_1.expression; - case 131 /* Decorator */: + case 163 /* TypeAssertionExpression */: + return node === parent_2.expression; + case 180 /* TemplateSpan */: + return node === parent_2.expression; + case 129 /* ComputedPropertyName */: + return node === parent_2.expression; + case 132 /* Decorator */: return true; + case 179 /* ExpressionWithTypeArguments */: + return parent_2.expression === node && isExpressionWithTypeArgumentsInClassExtendsClause(parent_2); default: - if (isExpression(parent_1)) { + if (isExpression(parent_2)) { return true; } } @@ -4904,7 +5514,7 @@ var ts; } ts.isInstantiatedModule = isInstantiatedModule; function isExternalModuleImportEqualsDeclaration(node) { - return node.kind === 209 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 220 /* ExternalModuleReference */; + return node.kind === 211 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 222 /* ExternalModuleReference */; } ts.isExternalModuleImportEqualsDeclaration = isExternalModuleImportEqualsDeclaration; function getExternalModuleImportEqualsDeclarationExpression(node) { @@ -4913,50 +5523,110 @@ var ts; } ts.getExternalModuleImportEqualsDeclarationExpression = getExternalModuleImportEqualsDeclarationExpression; function isInternalModuleImportEqualsDeclaration(node) { - return node.kind === 209 /* ImportEqualsDeclaration */ && node.moduleReference.kind !== 220 /* ExternalModuleReference */; + return node.kind === 211 /* ImportEqualsDeclaration */ && node.moduleReference.kind !== 222 /* ExternalModuleReference */; } ts.isInternalModuleImportEqualsDeclaration = isInternalModuleImportEqualsDeclaration; function getExternalModuleName(node) { - if (node.kind === 210 /* ImportDeclaration */) { + if (node.kind === 212 /* ImportDeclaration */) { return node.moduleSpecifier; } - if (node.kind === 209 /* ImportEqualsDeclaration */) { + if (node.kind === 211 /* ImportEqualsDeclaration */) { var reference = node.moduleReference; - if (reference.kind === 220 /* ExternalModuleReference */) { + if (reference.kind === 222 /* ExternalModuleReference */) { return reference.expression; } } - if (node.kind === 216 /* ExportDeclaration */) { + if (node.kind === 218 /* ExportDeclaration */) { return node.moduleSpecifier; } } ts.getExternalModuleName = getExternalModuleName; - function hasDotDotDotToken(node) { - return node && node.kind === 130 /* Parameter */ && node.dotDotDotToken !== undefined; - } - ts.hasDotDotDotToken = hasDotDotDotToken; function hasQuestionToken(node) { if (node) { switch (node.kind) { - case 130 /* Parameter */: + case 131 /* Parameter */: return node.questionToken !== undefined; - case 135 /* MethodDeclaration */: - case 134 /* MethodSignature */: + case 136 /* MethodDeclaration */: + case 135 /* MethodSignature */: return node.questionToken !== undefined; - case 226 /* ShorthandPropertyAssignment */: - case 225 /* PropertyAssignment */: - case 133 /* PropertyDeclaration */: - case 132 /* PropertySignature */: + case 228 /* ShorthandPropertyAssignment */: + case 227 /* PropertyAssignment */: + case 134 /* PropertyDeclaration */: + case 133 /* PropertySignature */: return node.questionToken !== undefined; } } return false; } ts.hasQuestionToken = hasQuestionToken; - function hasRestParameters(s) { - return s.parameters.length > 0 && ts.lastOrUndefined(s.parameters).dotDotDotToken !== undefined; + function isJSDocConstructSignature(node) { + return node.kind === 243 /* JSDocFunctionType */ && + node.parameters.length > 0 && + node.parameters[0].type.kind === 245 /* JSDocConstructorType */; } - ts.hasRestParameters = hasRestParameters; + ts.isJSDocConstructSignature = isJSDocConstructSignature; + function getJSDocTag(node, kind) { + if (node && node.jsDocComment) { + for (var _i = 0, _a = node.jsDocComment.tags; _i < _a.length; _i++) { + var tag = _a[_i]; + if (tag.kind === kind) { + return tag; + } + } + } + } + function getJSDocTypeTag(node) { + return getJSDocTag(node, 251 /* JSDocTypeTag */); + } + ts.getJSDocTypeTag = getJSDocTypeTag; + function getJSDocReturnTag(node) { + return getJSDocTag(node, 250 /* JSDocReturnTag */); + } + ts.getJSDocReturnTag = getJSDocReturnTag; + function getJSDocTemplateTag(node) { + return getJSDocTag(node, 252 /* JSDocTemplateTag */); + } + ts.getJSDocTemplateTag = getJSDocTemplateTag; + function getCorrespondingJSDocParameterTag(parameter) { + if (parameter.name && parameter.name.kind === 65 /* Identifier */) { + // If it's a parameter, see if the parent has a jsdoc comment with an @param + // annotation. + var parameterName = parameter.name.text; + var docComment = parameter.parent.jsDocComment; + if (docComment) { + return ts.forEach(docComment.tags, function (t) { + if (t.kind === 249 /* JSDocParameterTag */) { + var parameterTag = t; + var name_5 = parameterTag.preParameterName || parameterTag.postParameterName; + if (name_5.text === parameterName) { + return t; + } + } + }); + } + } + } + ts.getCorrespondingJSDocParameterTag = getCorrespondingJSDocParameterTag; + function hasRestParameter(s) { + return isRestParameter(ts.lastOrUndefined(s.parameters)); + } + ts.hasRestParameter = hasRestParameter; + function isRestParameter(node) { + if (node) { + if (node.parserContextFlags & 64 /* JavaScriptFile */) { + if (node.type && node.type.kind === 244 /* JSDocVariadicType */) { + return true; + } + var paramTag = getCorrespondingJSDocParameterTag(node); + if (paramTag && paramTag.typeExpression) { + return paramTag.typeExpression.type.kind === 244 /* JSDocVariadicType */; + } + } + return node.dotDotDotToken !== undefined; + } + return false; + } + ts.isRestParameter = isRestParameter; function isLiteralKind(kind) { return 7 /* FirstLiteralToken */ <= kind && kind <= 10 /* LastLiteralToken */; } @@ -4970,7 +5640,7 @@ var ts; } ts.isTemplateLiteralKind = isTemplateLiteralKind; function isBindingPattern(node) { - return !!node && (node.kind === 152 /* ArrayBindingPattern */ || node.kind === 151 /* ObjectBindingPattern */); + return !!node && (node.kind === 154 /* ArrayBindingPattern */ || node.kind === 153 /* ObjectBindingPattern */); } ts.isBindingPattern = isBindingPattern; function isInAmbientContext(node) { @@ -4985,33 +5655,33 @@ var ts; ts.isInAmbientContext = isInAmbientContext; function isDeclaration(node) { switch (node.kind) { - case 164 /* ArrowFunction */: - case 153 /* BindingElement */: - case 202 /* ClassDeclaration */: - case 136 /* Constructor */: - case 205 /* EnumDeclaration */: - case 227 /* EnumMember */: - case 218 /* ExportSpecifier */: - case 201 /* FunctionDeclaration */: - case 163 /* FunctionExpression */: - case 137 /* GetAccessor */: - case 211 /* ImportClause */: - case 209 /* ImportEqualsDeclaration */: - case 214 /* ImportSpecifier */: - case 203 /* InterfaceDeclaration */: - case 135 /* MethodDeclaration */: - case 134 /* MethodSignature */: - case 206 /* ModuleDeclaration */: - case 212 /* NamespaceImport */: - case 130 /* Parameter */: - case 225 /* PropertyAssignment */: - case 133 /* PropertyDeclaration */: - case 132 /* PropertySignature */: - case 138 /* SetAccessor */: - case 226 /* ShorthandPropertyAssignment */: - case 204 /* TypeAliasDeclaration */: - case 129 /* TypeParameter */: - case 199 /* VariableDeclaration */: + case 166 /* ArrowFunction */: + case 155 /* BindingElement */: + case 204 /* ClassDeclaration */: + case 137 /* Constructor */: + case 207 /* EnumDeclaration */: + case 229 /* EnumMember */: + case 220 /* ExportSpecifier */: + case 203 /* FunctionDeclaration */: + case 165 /* FunctionExpression */: + case 138 /* GetAccessor */: + case 213 /* ImportClause */: + case 211 /* ImportEqualsDeclaration */: + case 216 /* ImportSpecifier */: + case 205 /* InterfaceDeclaration */: + case 136 /* MethodDeclaration */: + case 135 /* MethodSignature */: + case 208 /* ModuleDeclaration */: + case 214 /* NamespaceImport */: + case 131 /* Parameter */: + case 227 /* PropertyAssignment */: + case 134 /* PropertyDeclaration */: + case 133 /* PropertySignature */: + case 139 /* SetAccessor */: + case 228 /* ShorthandPropertyAssignment */: + case 206 /* TypeAliasDeclaration */: + case 130 /* TypeParameter */: + case 201 /* VariableDeclaration */: return true; } return false; @@ -5019,25 +5689,25 @@ var ts; ts.isDeclaration = isDeclaration; function isStatement(n) { switch (n.kind) { - case 191 /* BreakStatement */: - case 190 /* ContinueStatement */: - case 198 /* DebuggerStatement */: - case 185 /* DoStatement */: - case 183 /* ExpressionStatement */: - case 182 /* EmptyStatement */: - case 188 /* ForInStatement */: - case 189 /* ForOfStatement */: - case 187 /* ForStatement */: - case 184 /* IfStatement */: - case 195 /* LabeledStatement */: - case 192 /* ReturnStatement */: - case 194 /* SwitchStatement */: + case 193 /* BreakStatement */: + case 192 /* ContinueStatement */: + case 200 /* DebuggerStatement */: + case 187 /* DoStatement */: + case 185 /* ExpressionStatement */: + case 184 /* EmptyStatement */: + case 190 /* ForInStatement */: + case 191 /* ForOfStatement */: + case 189 /* ForStatement */: + case 186 /* IfStatement */: + case 197 /* LabeledStatement */: + case 194 /* ReturnStatement */: + case 196 /* SwitchStatement */: case 94 /* ThrowKeyword */: - case 197 /* TryStatement */: - case 181 /* VariableStatement */: - case 186 /* WhileStatement */: - case 193 /* WithStatement */: - case 215 /* ExportAssignment */: + case 199 /* TryStatement */: + case 183 /* VariableStatement */: + case 188 /* WhileStatement */: + case 195 /* WithStatement */: + case 217 /* ExportAssignment */: return true; default: return false; @@ -5046,13 +5716,13 @@ var ts; ts.isStatement = isStatement; function isClassElement(n) { switch (n.kind) { - case 136 /* Constructor */: - case 133 /* PropertyDeclaration */: - case 135 /* MethodDeclaration */: - case 137 /* GetAccessor */: - case 138 /* SetAccessor */: - case 134 /* MethodSignature */: - case 141 /* IndexSignature */: + case 137 /* Constructor */: + case 134 /* PropertyDeclaration */: + case 136 /* MethodDeclaration */: + case 138 /* GetAccessor */: + case 139 /* SetAccessor */: + case 135 /* MethodSignature */: + case 142 /* IndexSignature */: return true; default: return false; @@ -5065,7 +5735,7 @@ var ts; return false; } var parent = name.parent; - if (parent.kind === 214 /* ImportSpecifier */ || parent.kind === 218 /* ExportSpecifier */) { + if (parent.kind === 216 /* ImportSpecifier */ || parent.kind === 220 /* ExportSpecifier */) { if (parent.propertyName) { return true; } @@ -5076,6 +5746,41 @@ var ts; return false; } ts.isDeclarationName = isDeclarationName; + // Return true if the given identifier is classified as an IdentifierName + function isIdentifierName(node) { + var parent = node.parent; + switch (parent.kind) { + case 134 /* PropertyDeclaration */: + case 133 /* PropertySignature */: + case 136 /* MethodDeclaration */: + case 135 /* MethodSignature */: + case 138 /* GetAccessor */: + case 139 /* SetAccessor */: + case 229 /* EnumMember */: + case 227 /* PropertyAssignment */: + case 158 /* PropertyAccessExpression */: + // Name in member declaration or property name in property access + return parent.name === node; + case 128 /* QualifiedName */: + // Name on right hand side of dot in a type query + if (parent.right === node) { + while (parent.kind === 128 /* QualifiedName */) { + parent = parent.parent; + } + return parent.kind === 147 /* TypeQuery */; + } + return false; + case 155 /* BindingElement */: + case 216 /* ImportSpecifier */: + // Property name in binding element or import specifier + return parent.propertyName === node; + case 220 /* ExportSpecifier */: + // Any name in an export specifier + return true; + } + return false; + } + ts.isIdentifierName = isIdentifierName; // An alias symbol is created by one of the following declarations: // import = ... // import from ... @@ -5085,12 +5790,12 @@ var ts; // export = ... // export default ... function isAliasSymbolDeclaration(node) { - return node.kind === 209 /* ImportEqualsDeclaration */ || - node.kind === 211 /* ImportClause */ && !!node.name || - node.kind === 212 /* NamespaceImport */ || - node.kind === 214 /* ImportSpecifier */ || - node.kind === 218 /* ExportSpecifier */ || - node.kind === 215 /* ExportAssignment */ && node.expression.kind === 65 /* Identifier */; + return node.kind === 211 /* ImportEqualsDeclaration */ || + node.kind === 213 /* ImportClause */ && !!node.name || + node.kind === 214 /* NamespaceImport */ || + node.kind === 216 /* ImportSpecifier */ || + node.kind === 220 /* ExportSpecifier */ || + node.kind === 217 /* ExportAssignment */ && node.expression.kind === 65 /* Identifier */; } ts.isAliasSymbolDeclaration = isAliasSymbolDeclaration; function getClassExtendsHeritageClauseElement(node) { @@ -5173,7 +5878,7 @@ var ts; } ts.getFileReferenceFromReferencePath = getFileReferenceFromReferencePath; function isKeyword(token) { - return 66 /* FirstKeyword */ <= token && token <= 126 /* LastKeyword */; + return 66 /* FirstKeyword */ <= token && token <= 127 /* LastKeyword */; } ts.isKeyword = isKeyword; function isTrivia(token) { @@ -5189,7 +5894,7 @@ var ts; */ function hasDynamicName(declaration) { return declaration.name && - declaration.name.kind === 128 /* ComputedPropertyName */ && + declaration.name.kind === 129 /* ComputedPropertyName */ && !isWellKnownSymbolSyntactically(declaration.name.expression); } ts.hasDynamicName = hasDynamicName; @@ -5199,14 +5904,14 @@ var ts; * where Symbol is literally the word "Symbol", and name is any identifierName */ function isWellKnownSymbolSyntactically(node) { - return node.kind === 156 /* PropertyAccessExpression */ && isESSymbolIdentifier(node.expression); + return node.kind === 158 /* PropertyAccessExpression */ && isESSymbolIdentifier(node.expression); } ts.isWellKnownSymbolSyntactically = isWellKnownSymbolSyntactically; function getPropertyNameForPropertyNameNode(name) { if (name.kind === 65 /* Identifier */ || name.kind === 8 /* StringLiteral */ || name.kind === 7 /* NumericLiteral */) { return name.text; } - if (name.kind === 128 /* ComputedPropertyName */) { + if (name.kind === 129 /* ComputedPropertyName */) { var nameExpression = name.expression; if (isWellKnownSymbolSyntactically(nameExpression)) { var rightHandSideName = nameExpression.name.text; @@ -5244,18 +5949,18 @@ var ts; ts.isModifier = isModifier; function isParameterDeclaration(node) { var root = getRootDeclaration(node); - return root.kind === 130 /* Parameter */; + return root.kind === 131 /* Parameter */; } ts.isParameterDeclaration = isParameterDeclaration; function getRootDeclaration(node) { - while (node.kind === 153 /* BindingElement */) { + while (node.kind === 155 /* BindingElement */) { node = node.parent.parent; } return node; } ts.getRootDeclaration = getRootDeclaration; function nodeStartsNewLexicalEnvironment(n) { - return isFunctionLike(n) || n.kind === 206 /* ModuleDeclaration */ || n.kind === 228 /* SourceFile */; + return isFunctionLike(n) || n.kind === 208 /* ModuleDeclaration */ || n.kind === 230 /* SourceFile */; } ts.nodeStartsNewLexicalEnvironment = nodeStartsNewLexicalEnvironment; function nodeIsSynthesized(node) { @@ -5491,7 +6196,7 @@ var ts; ts.getLineOfLocalPosition = getLineOfLocalPosition; function getFirstConstructorWithBody(node) { return ts.forEach(node.members, function (member) { - if (member.kind === 136 /* Constructor */ && nodeIsPresent(member.body)) { + if (member.kind === 137 /* Constructor */ && nodeIsPresent(member.body)) { return member; } }); @@ -5502,7 +6207,7 @@ var ts; if ((isExternalModule(sourceFile) || !compilerOptions.out)) { // 1. in-browser single file compilation scenario // 2. non .js file - return compilerOptions.separateCompilation || !ts.fileExtensionIs(sourceFile.fileName, ".js"); + return compilerOptions.isolatedModules || !ts.fileExtensionIs(sourceFile.fileName, ".js"); } return false; } @@ -5516,10 +6221,10 @@ var ts; var setAccessor; if (hasDynamicName(accessor)) { firstAccessor = accessor; - if (accessor.kind === 137 /* GetAccessor */) { + if (accessor.kind === 138 /* GetAccessor */) { getAccessor = accessor; } - else if (accessor.kind === 138 /* SetAccessor */) { + else if (accessor.kind === 139 /* SetAccessor */) { setAccessor = accessor; } else { @@ -5528,7 +6233,7 @@ var ts; } else { ts.forEach(declarations, function (member) { - if ((member.kind === 137 /* GetAccessor */ || member.kind === 138 /* SetAccessor */) + if ((member.kind === 138 /* GetAccessor */ || member.kind === 139 /* SetAccessor */) && (member.flags & 128 /* Static */) === (accessor.flags & 128 /* Static */)) { var memberName = getPropertyNameForPropertyNameNode(member.name); var accessorName = getPropertyNameForPropertyNameNode(accessor.name); @@ -5539,10 +6244,10 @@ var ts; else if (!secondAccessor) { secondAccessor = member; } - if (member.kind === 137 /* GetAccessor */ && !getAccessor) { + if (member.kind === 138 /* GetAccessor */ && !getAccessor) { getAccessor = member; } - if (member.kind === 138 /* SetAccessor */ && !setAccessor) { + if (member.kind === 139 /* SetAccessor */ && !setAccessor) { setAccessor = member; } } @@ -5690,22 +6395,22 @@ var ts; function isLeftHandSideExpression(expr) { if (expr) { switch (expr.kind) { - case 156 /* PropertyAccessExpression */: - case 157 /* ElementAccessExpression */: - case 159 /* NewExpression */: - case 158 /* CallExpression */: - case 160 /* TaggedTemplateExpression */: - case 154 /* ArrayLiteralExpression */: - case 162 /* ParenthesizedExpression */: - case 155 /* ObjectLiteralExpression */: - case 175 /* ClassExpression */: - case 163 /* FunctionExpression */: + case 158 /* PropertyAccessExpression */: + case 159 /* ElementAccessExpression */: + case 161 /* NewExpression */: + case 160 /* CallExpression */: + case 162 /* TaggedTemplateExpression */: + case 156 /* ArrayLiteralExpression */: + case 164 /* ParenthesizedExpression */: + case 157 /* ObjectLiteralExpression */: + case 177 /* ClassExpression */: + case 165 /* FunctionExpression */: case 65 /* Identifier */: case 9 /* RegularExpressionLiteral */: case 7 /* NumericLiteral */: case 8 /* StringLiteral */: case 10 /* NoSubstitutionTemplateLiteral */: - case 172 /* TemplateExpression */: + case 174 /* TemplateExpression */: case 80 /* FalseKeyword */: case 89 /* NullKeyword */: case 93 /* ThisKeyword */: @@ -5721,6 +6426,12 @@ var ts; return token >= 53 /* FirstAssignment */ && token <= 64 /* LastAssignment */; } ts.isAssignmentOperator = isAssignmentOperator; + function isExpressionWithTypeArgumentsInClassExtendsClause(node) { + return node.kind === 179 /* ExpressionWithTypeArguments */ && + node.parent.token === 79 /* ExtendsKeyword */ && + node.parent.parent.kind === 204 /* ClassDeclaration */; + } + ts.isExpressionWithTypeArgumentsInClassExtendsClause = isExpressionWithTypeArgumentsInClassExtendsClause; // Returns false if this heritage clause element's expression contains something unsupported // (i.e. not a name or dotted name). function isSupportedExpressionWithTypeArguments(node) { @@ -5731,7 +6442,7 @@ var ts; if (node.kind === 65 /* Identifier */) { return true; } - else if (node.kind === 156 /* PropertyAccessExpression */) { + else if (node.kind === 158 /* PropertyAccessExpression */) { return isSupportedExpressionWithTypeArgumentsRest(node.expression); } else { @@ -5739,14 +6450,18 @@ var ts; } } function isRightSideOfQualifiedNameOrPropertyAccess(node) { - return (node.parent.kind === 127 /* QualifiedName */ && node.parent.right === node) || - (node.parent.kind === 156 /* PropertyAccessExpression */ && node.parent.name === node); + return (node.parent.kind === 128 /* QualifiedName */ && node.parent.right === node) || + (node.parent.kind === 158 /* PropertyAccessExpression */ && node.parent.name === node); } ts.isRightSideOfQualifiedNameOrPropertyAccess = isRightSideOfQualifiedNameOrPropertyAccess; function getLocalSymbolForExportDefault(symbol) { return symbol && symbol.valueDeclaration && (symbol.valueDeclaration.flags & 256 /* Default */) ? symbol.valueDeclaration.localSymbol : undefined; } ts.getLocalSymbolForExportDefault = getLocalSymbolForExportDefault; + function isJavaScript(fileName) { + return ts.fileExtensionIs(fileName, ".js"); + } + ts.isJavaScript = isJavaScript; /** * Replace each instance of non-ascii characters by one, two, three, or four escape sequences * representing the UTF-8 encoding of the character, and return the expanded char code list. @@ -5814,6 +6529,21 @@ var ts; return result; } ts.convertToBase64 = convertToBase64; + var carriageReturnLineFeed = "\r\n"; + var lineFeed = "\n"; + function getNewLineCharacter(options) { + if (options.newLine === 0 /* CarriageReturnLineFeed */) { + return carriageReturnLineFeed; + } + else if (options.newLine === 1 /* LineFeed */) { + return lineFeed; + } + else if (ts.sys) { + return ts.sys.newLine; + } + return carriageReturnLineFeed; + } + ts.getNewLineCharacter = getNewLineCharacter; })(ts || (ts = {})); var ts; (function (ts) { @@ -5862,6 +6592,12 @@ var ts; 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; } @@ -6020,12 +6756,22 @@ var ts; return createTextChangeRange(createTextSpanFromBounds(oldStartN, oldEndN), newEndN - oldStartN); } ts.collapseTextChangeRangesAcrossMultipleVersions = collapseTextChangeRangesAcrossMultipleVersions; + function getTypeParameterOwner(d) { + if (d && d.kind === 130 /* TypeParameter */) { + for (var current = d; current; current = current.parent) { + if (ts.isFunctionLike(current) || ts.isClassLike(current) || current.kind === 205 /* InterfaceDeclaration */) { + return current; + } + } + } + } + ts.getTypeParameterOwner = getTypeParameterOwner; })(ts || (ts = {})); /// /// var ts; (function (ts) { - var nodeConstructors = new Array(230 /* Count */); + var nodeConstructors = new Array(254 /* Count */); /* @internal */ ts.parseTime = 0; function getNodeConstructor(kind) { return nodeConstructors[kind] || (nodeConstructors[kind] = ts.objectAllocator.getNodeConstructor(kind)); @@ -6070,20 +6816,20 @@ var ts; var visitNodes = cbNodeArray ? visitNodeArray : visitEachNode; var cbNodes = cbNodeArray || cbNode; switch (node.kind) { - case 127 /* QualifiedName */: + case 128 /* QualifiedName */: return visitNode(cbNode, node.left) || visitNode(cbNode, node.right); - case 129 /* TypeParameter */: + case 130 /* TypeParameter */: return visitNode(cbNode, node.name) || visitNode(cbNode, node.constraint) || visitNode(cbNode, node.expression); - case 130 /* Parameter */: - case 133 /* PropertyDeclaration */: - case 132 /* PropertySignature */: - case 225 /* PropertyAssignment */: - case 226 /* ShorthandPropertyAssignment */: - case 199 /* VariableDeclaration */: - case 153 /* BindingElement */: + case 131 /* Parameter */: + case 134 /* PropertyDeclaration */: + case 133 /* PropertySignature */: + case 227 /* PropertyAssignment */: + case 228 /* ShorthandPropertyAssignment */: + case 201 /* VariableDeclaration */: + case 155 /* BindingElement */: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.propertyName) || @@ -6092,24 +6838,24 @@ var ts; visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.type) || visitNode(cbNode, node.initializer); - case 143 /* FunctionType */: - case 144 /* ConstructorType */: - case 139 /* CallSignature */: - case 140 /* ConstructSignature */: - case 141 /* IndexSignature */: + case 145 /* FunctionType */: + case 146 /* ConstructorType */: + case 140 /* CallSignature */: + case 141 /* ConstructSignature */: + case 142 /* IndexSignature */: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNodes(cbNodes, node.typeParameters) || visitNodes(cbNodes, node.parameters) || visitNode(cbNode, node.type); - case 135 /* MethodDeclaration */: - case 134 /* MethodSignature */: - case 136 /* Constructor */: - case 137 /* GetAccessor */: - case 138 /* SetAccessor */: - case 163 /* FunctionExpression */: - case 201 /* FunctionDeclaration */: - case 164 /* ArrowFunction */: + case 136 /* MethodDeclaration */: + case 135 /* MethodSignature */: + case 137 /* Constructor */: + case 138 /* GetAccessor */: + case 139 /* SetAccessor */: + case 165 /* FunctionExpression */: + case 203 /* FunctionDeclaration */: + case 166 /* ArrowFunction */: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.asteriskToken) || @@ -6120,221 +6866,268 @@ var ts; visitNode(cbNode, node.type) || visitNode(cbNode, node.equalsGreaterThanToken) || visitNode(cbNode, node.body); - case 142 /* TypeReference */: + case 144 /* TypeReference */: return visitNode(cbNode, node.typeName) || visitNodes(cbNodes, node.typeArguments); - case 145 /* TypeQuery */: + case 143 /* TypePredicate */: + return visitNode(cbNode, node.parameterName) || + visitNode(cbNode, node.type); + case 147 /* TypeQuery */: return visitNode(cbNode, node.exprName); - case 146 /* TypeLiteral */: + case 148 /* TypeLiteral */: return visitNodes(cbNodes, node.members); - case 147 /* ArrayType */: + case 149 /* ArrayType */: return visitNode(cbNode, node.elementType); - case 148 /* TupleType */: + case 150 /* TupleType */: return visitNodes(cbNodes, node.elementTypes); - case 149 /* UnionType */: + case 151 /* UnionType */: return visitNodes(cbNodes, node.types); - case 150 /* ParenthesizedType */: + case 152 /* ParenthesizedType */: return visitNode(cbNode, node.type); - case 151 /* ObjectBindingPattern */: - case 152 /* ArrayBindingPattern */: + case 153 /* ObjectBindingPattern */: + case 154 /* ArrayBindingPattern */: return visitNodes(cbNodes, node.elements); - case 154 /* ArrayLiteralExpression */: + case 156 /* ArrayLiteralExpression */: return visitNodes(cbNodes, node.elements); - case 155 /* ObjectLiteralExpression */: + case 157 /* ObjectLiteralExpression */: return visitNodes(cbNodes, node.properties); - case 156 /* PropertyAccessExpression */: + case 158 /* PropertyAccessExpression */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.dotToken) || visitNode(cbNode, node.name); - case 157 /* ElementAccessExpression */: + case 159 /* ElementAccessExpression */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.argumentExpression); - case 158 /* CallExpression */: - case 159 /* NewExpression */: + case 160 /* CallExpression */: + case 161 /* NewExpression */: return visitNode(cbNode, node.expression) || visitNodes(cbNodes, node.typeArguments) || visitNodes(cbNodes, node.arguments); - case 160 /* TaggedTemplateExpression */: + case 162 /* TaggedTemplateExpression */: return visitNode(cbNode, node.tag) || visitNode(cbNode, node.template); - case 161 /* TypeAssertionExpression */: + case 163 /* TypeAssertionExpression */: return visitNode(cbNode, node.type) || visitNode(cbNode, node.expression); - case 162 /* ParenthesizedExpression */: + case 164 /* ParenthesizedExpression */: return visitNode(cbNode, node.expression); - case 165 /* DeleteExpression */: + case 167 /* DeleteExpression */: return visitNode(cbNode, node.expression); - case 166 /* TypeOfExpression */: + case 168 /* TypeOfExpression */: return visitNode(cbNode, node.expression); - case 167 /* VoidExpression */: + case 169 /* VoidExpression */: return visitNode(cbNode, node.expression); - case 168 /* PrefixUnaryExpression */: + case 170 /* PrefixUnaryExpression */: return visitNode(cbNode, node.operand); - case 173 /* YieldExpression */: + case 175 /* YieldExpression */: return visitNode(cbNode, node.asteriskToken) || visitNode(cbNode, node.expression); - case 169 /* PostfixUnaryExpression */: + case 171 /* PostfixUnaryExpression */: return visitNode(cbNode, node.operand); - case 170 /* BinaryExpression */: + case 172 /* BinaryExpression */: return visitNode(cbNode, node.left) || visitNode(cbNode, node.operatorToken) || visitNode(cbNode, node.right); - case 171 /* ConditionalExpression */: + case 173 /* ConditionalExpression */: return visitNode(cbNode, node.condition) || visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.whenTrue) || visitNode(cbNode, node.colonToken) || visitNode(cbNode, node.whenFalse); - case 174 /* SpreadElementExpression */: + case 176 /* SpreadElementExpression */: return visitNode(cbNode, node.expression); - case 180 /* Block */: - case 207 /* ModuleBlock */: + case 182 /* Block */: + case 209 /* ModuleBlock */: return visitNodes(cbNodes, node.statements); - case 228 /* SourceFile */: + case 230 /* SourceFile */: return visitNodes(cbNodes, node.statements) || visitNode(cbNode, node.endOfFileToken); - case 181 /* VariableStatement */: + case 183 /* VariableStatement */: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.declarationList); - case 200 /* VariableDeclarationList */: + case 202 /* VariableDeclarationList */: return visitNodes(cbNodes, node.declarations); - case 183 /* ExpressionStatement */: + case 185 /* ExpressionStatement */: return visitNode(cbNode, node.expression); - case 184 /* IfStatement */: + case 186 /* IfStatement */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.thenStatement) || visitNode(cbNode, node.elseStatement); - case 185 /* DoStatement */: + case 187 /* DoStatement */: return visitNode(cbNode, node.statement) || visitNode(cbNode, node.expression); - case 186 /* WhileStatement */: + case 188 /* WhileStatement */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.statement); - case 187 /* ForStatement */: + case 189 /* ForStatement */: return visitNode(cbNode, node.initializer) || visitNode(cbNode, node.condition) || visitNode(cbNode, node.incrementor) || visitNode(cbNode, node.statement); - case 188 /* ForInStatement */: + case 190 /* ForInStatement */: return visitNode(cbNode, node.initializer) || visitNode(cbNode, node.expression) || visitNode(cbNode, node.statement); - case 189 /* ForOfStatement */: + case 191 /* ForOfStatement */: return visitNode(cbNode, node.initializer) || visitNode(cbNode, node.expression) || visitNode(cbNode, node.statement); - case 190 /* ContinueStatement */: - case 191 /* BreakStatement */: + case 192 /* ContinueStatement */: + case 193 /* BreakStatement */: return visitNode(cbNode, node.label); - case 192 /* ReturnStatement */: + case 194 /* ReturnStatement */: return visitNode(cbNode, node.expression); - case 193 /* WithStatement */: + case 195 /* WithStatement */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.statement); - case 194 /* SwitchStatement */: + case 196 /* SwitchStatement */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.caseBlock); - case 208 /* CaseBlock */: + case 210 /* CaseBlock */: return visitNodes(cbNodes, node.clauses); - case 221 /* CaseClause */: + case 223 /* CaseClause */: return visitNode(cbNode, node.expression) || visitNodes(cbNodes, node.statements); - case 222 /* DefaultClause */: + case 224 /* DefaultClause */: return visitNodes(cbNodes, node.statements); - case 195 /* LabeledStatement */: + case 197 /* LabeledStatement */: return visitNode(cbNode, node.label) || visitNode(cbNode, node.statement); - case 196 /* ThrowStatement */: + case 198 /* ThrowStatement */: return visitNode(cbNode, node.expression); - case 197 /* TryStatement */: + case 199 /* TryStatement */: return visitNode(cbNode, node.tryBlock) || visitNode(cbNode, node.catchClause) || visitNode(cbNode, node.finallyBlock); - case 224 /* CatchClause */: + case 226 /* CatchClause */: return visitNode(cbNode, node.variableDeclaration) || visitNode(cbNode, node.block); - case 131 /* Decorator */: + case 132 /* Decorator */: return visitNode(cbNode, node.expression); - case 202 /* ClassDeclaration */: - case 175 /* ClassExpression */: + case 204 /* ClassDeclaration */: + case 177 /* 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 203 /* InterfaceDeclaration */: + case 205 /* 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 204 /* TypeAliasDeclaration */: + case 206 /* TypeAliasDeclaration */: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.name) || + visitNodes(cbNodes, node.typeParameters) || visitNode(cbNode, node.type); - case 205 /* EnumDeclaration */: + case 207 /* EnumDeclaration */: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNodes, node.members); - case 227 /* EnumMember */: + case 229 /* EnumMember */: return visitNode(cbNode, node.name) || visitNode(cbNode, node.initializer); - case 206 /* ModuleDeclaration */: + case 208 /* ModuleDeclaration */: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.body); - case 209 /* ImportEqualsDeclaration */: + case 211 /* ImportEqualsDeclaration */: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.moduleReference); - case 210 /* ImportDeclaration */: + case 212 /* ImportDeclaration */: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.importClause) || visitNode(cbNode, node.moduleSpecifier); - case 211 /* ImportClause */: + case 213 /* ImportClause */: return visitNode(cbNode, node.name) || visitNode(cbNode, node.namedBindings); - case 212 /* NamespaceImport */: + case 214 /* NamespaceImport */: return visitNode(cbNode, node.name); - case 213 /* NamedImports */: - case 217 /* NamedExports */: + case 215 /* NamedImports */: + case 219 /* NamedExports */: return visitNodes(cbNodes, node.elements); - case 216 /* ExportDeclaration */: + case 218 /* ExportDeclaration */: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.exportClause) || visitNode(cbNode, node.moduleSpecifier); - case 214 /* ImportSpecifier */: - case 218 /* ExportSpecifier */: + case 216 /* ImportSpecifier */: + case 220 /* ExportSpecifier */: return visitNode(cbNode, node.propertyName) || visitNode(cbNode, node.name); - case 215 /* ExportAssignment */: + case 217 /* ExportAssignment */: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.expression); - case 172 /* TemplateExpression */: + case 174 /* TemplateExpression */: return visitNode(cbNode, node.head) || visitNodes(cbNodes, node.templateSpans); - case 178 /* TemplateSpan */: + case 180 /* TemplateSpan */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.literal); - case 128 /* ComputedPropertyName */: + case 129 /* ComputedPropertyName */: return visitNode(cbNode, node.expression); - case 223 /* HeritageClause */: + case 225 /* HeritageClause */: return visitNodes(cbNodes, node.types); - case 177 /* ExpressionWithTypeArguments */: + case 179 /* ExpressionWithTypeArguments */: return visitNode(cbNode, node.expression) || visitNodes(cbNodes, node.typeArguments); - case 220 /* ExternalModuleReference */: + case 222 /* ExternalModuleReference */: return visitNode(cbNode, node.expression); - case 219 /* MissingDeclaration */: + case 221 /* MissingDeclaration */: return visitNodes(cbNodes, node.decorators); + case 231 /* JSDocTypeExpression */: + return visitNode(cbNode, node.type); + case 235 /* JSDocUnionType */: + return visitNodes(cbNodes, node.types); + case 236 /* JSDocTupleType */: + return visitNodes(cbNodes, node.types); + case 234 /* JSDocArrayType */: + return visitNode(cbNode, node.elementType); + case 238 /* JSDocNonNullableType */: + return visitNode(cbNode, node.type); + case 237 /* JSDocNullableType */: + return visitNode(cbNode, node.type); + case 239 /* JSDocRecordType */: + return visitNodes(cbNodes, node.members); + case 241 /* JSDocTypeReference */: + return visitNode(cbNode, node.name) || + visitNodes(cbNodes, node.typeArguments); + case 242 /* JSDocOptionalType */: + return visitNode(cbNode, node.type); + case 243 /* JSDocFunctionType */: + return visitNodes(cbNodes, node.parameters) || + visitNode(cbNode, node.type); + case 244 /* JSDocVariadicType */: + return visitNode(cbNode, node.type); + case 245 /* JSDocConstructorType */: + return visitNode(cbNode, node.type); + case 246 /* JSDocThisType */: + return visitNode(cbNode, node.type); + case 240 /* JSDocRecordMember */: + return visitNode(cbNode, node.name) || + visitNode(cbNode, node.type); + case 247 /* JSDocComment */: + return visitNodes(cbNodes, node.tags); + case 249 /* JSDocParameterTag */: + return visitNode(cbNode, node.preParameterName) || + visitNode(cbNode, node.typeExpression) || + visitNode(cbNode, node.postParameterName); + case 250 /* JSDocReturnTag */: + return visitNode(cbNode, node.typeExpression); + case 251 /* JSDocTypeTag */: + return visitNode(cbNode, node.typeExpression); + case 252 /* JSDocTemplateTag */: + return visitNodes(cbNodes, node.typeParameters); } } ts.forEachChild = forEachChild; @@ -6359,6 +7152,17 @@ var ts; return IncrementalParser.updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks); } ts.updateSourceFile = updateSourceFile; + /* @internal */ + function parseIsolatedJSDocComment(content, start, length) { + return Parser.JSDocParser.parseIsolatedJSDocComment(content, start, length); + } + 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. @@ -6369,6 +7173,7 @@ var ts; var scanner = ts.createScanner(2 /* Latest */, true); var disallowInAndDecoratorContext = 2 /* DisallowIn */ | 16 /* Decorator */; var sourceFile; + var parseDiagnostics; var syntaxCursor; var token; var sourceText; @@ -6422,7 +7227,7 @@ var ts; // 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 = 0; + 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: @@ -6452,44 +7257,89 @@ var ts; // attached to the EOF token. var parseErrorBeforeNextFinishedNode = false; function parseSourceFile(fileName, _sourceText, languageVersion, _syntaxCursor, setParentNodes) { + initializeState(fileName, _sourceText, languageVersion, _syntaxCursor); + var result = parseSourceFileWorker(fileName, languageVersion, setParentNodes); + clearState(); + return result; + } + Parser.parseSourceFile = parseSourceFile; + function initializeState(fileName, _sourceText, languageVersion, _syntaxCursor) { sourceText = _sourceText; syntaxCursor = _syntaxCursor; + parseDiagnostics = []; parsingContext = 0; identifiers = {}; identifierCount = 0; nodeCount = 0; - contextFlags = 0; + contextFlags = ts.isJavaScript(fileName) ? 64 /* JavaScriptFile */ : 0 /* None */; parseErrorBeforeNextFinishedNode = false; - createSourceFile(fileName, languageVersion); // Initialize and prime the scanner before parsing the source elements. scanner.setText(sourceText); scanner.setOnError(scanError); scanner.setScriptTarget(languageVersion); + } + 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 accidently hold onto it for too long. + parseDiagnostics = undefined; + sourceFile = undefined; + identifiers = undefined; + syntaxCursor = undefined; + sourceText = undefined; + } + function parseSourceFileWorker(fileName, languageVersion, setParentNodes) { + sourceFile = createSourceFile(fileName, languageVersion); + // Prime the scanner. token = nextToken(); processReferenceComments(sourceFile); - sourceFile.statements = parseList(0 /* SourceElements */, true, parseSourceElement); + 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); } - syntaxCursor = undefined; - // Clear out the text the scanner is pointing at, so it doesn't keep anything alive unnecessarily. - scanner.setText(""); - scanner.setOnError(undefined); - var result = sourceFile; - // Clear any data. We don't want to accidently hold onto it for too long. - sourceFile = undefined; - identifiers = undefined; - syntaxCursor = undefined; - sourceText = undefined; - return result; + // If this is a javascript file, proactively see if we can get JSDoc comments for + // relevant nodes in the file. We'll use these to provide typing informaion if they're + // available. + if (ts.isJavaScript(fileName)) { + addJSDocComments(); + } + return sourceFile; + } + function addJSDocComments() { + forEachChild(sourceFile, visit); + return; + function visit(node) { + // Add additional cases as necessary depending on how we see JSDoc comments used + // in the wild. + switch (node.kind) { + case 183 /* VariableStatement */: + case 203 /* FunctionDeclaration */: + case 131 /* Parameter */: + addJSDocComment(node); + } + forEachChild(node, visit); + } + } + function addJSDocComment(node) { + var comments = ts.getLeadingCommentRangesOfNode(node, sourceFile); + if (comments) { + for (var _i = 0; _i < comments.length; _i++) { + var comment = comments[_i]; + var jsDocComment = JSDocParser.parseJSDocComment(node, comment.pos, comment.end - comment.pos); + if (jsDocComment) { + node.jsDocComment = jsDocComment; + } + } + } } - Parser.parseSourceFile = parseSourceFile; function fixupParentReferences(sourceFile) { // 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 @@ -6511,16 +7361,17 @@ var ts; } } } + Parser.fixupParentReferences = fixupParentReferences; function createSourceFile(fileName, languageVersion) { - sourceFile = createNode(228 /* SourceFile */, 0); + var sourceFile = createNode(230 /* SourceFile */, 0); sourceFile.pos = 0; sourceFile.end = sourceText.length; sourceFile.text = sourceText; - sourceFile.parseDiagnostics = []; sourceFile.bindDiagnostics = []; sourceFile.languageVersion = languageVersion; sourceFile.fileName = ts.normalizePath(fileName); sourceFile.flags = ts.fileExtensionIs(sourceFile.fileName, ".d.ts") ? 2048 /* DeclarationFile */ : 0; + return sourceFile; } function setContextFlag(val, flag) { if (val) { @@ -6530,9 +7381,6 @@ var ts; contextFlags &= ~flag; } } - function setStrictModeContext(val) { - setContextFlag(val, 1 /* StrictMode */); - } function setDisallowInContext(val) { setContextFlag(val, 2 /* DisallowIn */); } @@ -6609,9 +7457,6 @@ var ts; function inYieldContext() { return (contextFlags & 4 /* Yield */) !== 0; } - function inStrictModeContext() { - return (contextFlags & 1 /* StrictMode */) !== 0; - } function inGeneratorParameterContext() { return (contextFlags & 8 /* GeneratorParameter */) !== 0; } @@ -6628,9 +7473,9 @@ var ts; } 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(sourceFile.parseDiagnostics); + var lastError = ts.lastOrUndefined(parseDiagnostics); if (!lastError || start !== lastError.start) { - sourceFile.parseDiagnostics.push(ts.createFileDiagnostic(sourceFile, start, length, message, arg0)); + 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. @@ -6665,7 +7510,7 @@ var ts; // 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 = token; - var saveParseDiagnosticsLength = sourceFile.parseDiagnostics.length; + 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/restorating of these flags happens naturally through the recursive @@ -6683,7 +7528,7 @@ var ts; // then unconditionally restore us to where we were. if (!result || isLookAhead) { token = saveToken; - sourceFile.parseDiagnostics.length = saveParseDiagnosticsLength; + parseDiagnostics.length = saveParseDiagnosticsLength; parseErrorBeforeNextFinishedNode = saveParseErrorBeforeNextFinishedNode; } return result; @@ -6779,8 +7624,8 @@ var ts; node.end = pos; return node; } - function finishNode(node) { - node.end = scanner.getStartPos(); + function finishNode(node, end) { + node.end = end === undefined ? scanner.getStartPos() : end; if (contextFlags) { node.parserContextFlags = contextFlags; } @@ -6836,15 +7681,24 @@ var ts; token === 8 /* StringLiteral */ || token === 7 /* NumericLiteral */; } - function parsePropertyName() { + function parsePropertyNameWorker(allowComputedPropertyNames) { if (token === 8 /* StringLiteral */ || token === 7 /* NumericLiteral */) { return parseLiteralNode(true); } - if (token === 18 /* OpenBracketToken */) { + if (allowComputedPropertyNames && token === 18 /* OpenBracketToken */) { return parseComputedPropertyName(); } return parseIdentifierName(); } + function parsePropertyName() { + return parsePropertyNameWorker(true); + } + function parseSimplePropertyName() { + return parsePropertyNameWorker(false); + } + function isSimplePropertyName() { + return token === 8 /* StringLiteral */ || token === 7 /* NumericLiteral */ || isIdentifierOrKeyword(); + } function parseComputedPropertyName() { // PropertyName[Yield,GeneratorParameter] : // LiteralPropertyName @@ -6854,7 +7708,7 @@ var ts; // ComputedPropertyName[Yield] : // [ AssignmentExpression[In, ?Yield] ] // - var node = createNode(128 /* ComputedPropertyName */); + var node = createNode(129 /* ComputedPropertyName */); parseExpected(18 /* OpenBracketToken */); // We parse any expression (including a comma expression). But the grammar // says that only an assignment expression is allowed, so the grammar checker @@ -6912,30 +7766,34 @@ var ts; } switch (parsingContext) { case 0 /* SourceElements */: - case 1 /* ModuleElements */: - return isSourceElement(inErrorRecovery); - case 2 /* BlockStatements */: - case 4 /* SwitchClauseStatements */: - return isStartOfStatement(inErrorRecovery); - case 3 /* SwitchClauses */: + 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 === 22 /* SemicolonToken */ && inErrorRecovery) && isStartOfStatement(); + case 2 /* SwitchClauses */: return token === 67 /* CaseKeyword */ || token === 73 /* DefaultKeyword */; - case 5 /* TypeMembers */: + case 4 /* TypeMembers */: return isStartOfTypeMember(); - case 6 /* ClassMembers */: + 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 === 22 /* SemicolonToken */ && !inErrorRecovery); - case 7 /* EnumMembers */: + 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 === 18 /* OpenBracketToken */ || isLiteralPropertyName(); - case 13 /* ObjectLiteralMembers */: + case 12 /* ObjectLiteralMembers */: return token === 18 /* OpenBracketToken */ || token === 35 /* AsteriskToken */ || isLiteralPropertyName(); - case 10 /* ObjectBindingElements */: + case 9 /* ObjectBindingElements */: return isLiteralPropertyName(); - case 8 /* HeritageClauseElement */: + 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 === 14 /* OpenBraceToken */) { @@ -6950,24 +7808,30 @@ var ts; // element during recovery. return isIdentifier() && !isHeritageClauseExtendsOrImplementsKeyword(); } - case 9 /* VariableDeclarations */: + case 8 /* VariableDeclarations */: return isIdentifierOrPattern(); - case 11 /* ArrayBindingElements */: + case 10 /* ArrayBindingElements */: return token === 23 /* CommaToken */ || token === 21 /* DotDotDotToken */ || isIdentifierOrPattern(); - case 16 /* TypeParameters */: + case 15 /* TypeParameters */: return isIdentifier(); - case 12 /* ArgumentExpressions */: - case 14 /* ArrayLiteralMembers */: + case 11 /* ArgumentExpressions */: + case 13 /* ArrayLiteralMembers */: return token === 23 /* CommaToken */ || token === 21 /* DotDotDotToken */ || isStartOfExpression(); - case 15 /* Parameters */: + case 14 /* Parameters */: return isStartOfParameter(); - case 17 /* TypeArguments */: - case 18 /* TupleElementTypes */: + case 16 /* TypeArguments */: + case 17 /* TupleElementTypes */: return token === 23 /* CommaToken */ || isStartOfType(); - case 19 /* HeritageClauses */: + case 18 /* HeritageClauses */: return isHeritageClause(); - case 20 /* ImportOrExportSpecifiers */: + case 19 /* ImportOrExportSpecifiers */: return isIdentifierOrKeyword(); + case 20 /* JSDocFunctionParameters */: + case 21 /* JSDocTypeArguments */: + case 23 /* JSDocTupleTypes */: + return JSDocParser.isJSDocType(); + case 22 /* JSDocRecordMembers */: + return isSimplePropertyName(); } ts.Debug.fail("Non-exhaustive case in 'isListElement'."); } @@ -7008,40 +7872,47 @@ var ts; return true; } switch (kind) { - case 1 /* ModuleElements */: - case 2 /* BlockStatements */: - case 3 /* SwitchClauses */: - case 5 /* TypeMembers */: - case 6 /* ClassMembers */: - case 7 /* EnumMembers */: - case 13 /* ObjectLiteralMembers */: - case 10 /* ObjectBindingElements */: - case 20 /* ImportOrExportSpecifiers */: + case 1 /* BlockStatements */: + case 2 /* SwitchClauses */: + case 4 /* TypeMembers */: + case 5 /* ClassMembers */: + case 6 /* EnumMembers */: + case 12 /* ObjectLiteralMembers */: + case 9 /* ObjectBindingElements */: + case 19 /* ImportOrExportSpecifiers */: return token === 15 /* CloseBraceToken */; - case 4 /* SwitchClauseStatements */: + case 3 /* SwitchClauseStatements */: return token === 15 /* CloseBraceToken */ || token === 67 /* CaseKeyword */ || token === 73 /* DefaultKeyword */; - case 8 /* HeritageClauseElement */: + case 7 /* HeritageClauseElement */: return token === 14 /* OpenBraceToken */ || token === 79 /* ExtendsKeyword */ || token === 102 /* ImplementsKeyword */; - case 9 /* VariableDeclarations */: + case 8 /* VariableDeclarations */: return isVariableDeclaratorListTerminator(); - case 16 /* TypeParameters */: + case 15 /* TypeParameters */: // Tokens other than '>' are here for better error recovery return token === 25 /* GreaterThanToken */ || token === 16 /* OpenParenToken */ || token === 14 /* OpenBraceToken */ || token === 79 /* ExtendsKeyword */ || token === 102 /* ImplementsKeyword */; - case 12 /* ArgumentExpressions */: + case 11 /* ArgumentExpressions */: // Tokens other than ')' are here for better error recovery return token === 17 /* CloseParenToken */ || token === 22 /* SemicolonToken */; - case 14 /* ArrayLiteralMembers */: - case 18 /* TupleElementTypes */: - case 11 /* ArrayBindingElements */: + case 13 /* ArrayLiteralMembers */: + case 17 /* TupleElementTypes */: + case 10 /* ArrayBindingElements */: return token === 19 /* CloseBracketToken */; - case 15 /* Parameters */: + case 14 /* Parameters */: // Tokens other than ')' and ']' (the latter for index signatures) are here for better error recovery return token === 17 /* CloseParenToken */ || token === 19 /* CloseBracketToken */ /*|| token === SyntaxKind.OpenBraceToken*/; - case 17 /* TypeArguments */: + case 16 /* TypeArguments */: // Tokens other than '>' are here for better error recovery return token === 25 /* GreaterThanToken */ || token === 16 /* OpenParenToken */; - case 19 /* HeritageClauses */: + case 18 /* HeritageClauses */: return token === 14 /* OpenBraceToken */ || token === 15 /* CloseBraceToken */; + case 20 /* JSDocFunctionParameters */: + return token === 17 /* CloseParenToken */ || token === 51 /* ColonToken */ || token === 15 /* CloseBraceToken */; + case 21 /* JSDocTypeArguments */: + return token === 25 /* GreaterThanToken */ || token === 15 /* CloseBraceToken */; + case 23 /* JSDocTupleTypes */: + return token === 19 /* CloseBracketToken */ || token === 15 /* CloseBraceToken */; + case 22 /* JSDocRecordMembers */: + return token === 15 /* CloseBraceToken */; } } function isVariableDeclaratorListTerminator() { @@ -7067,7 +7938,7 @@ var ts; } // True if positioned at element or terminator of the current list or any enclosing list function isInSomeParsingContext() { - for (var kind = 0; kind < 21 /* Count */; kind++) { + for (var kind = 0; kind < 24 /* Count */; kind++) { if (parsingContext & (1 << kind)) { if (isListElement(kind, true) || isListTerminator(kind)) { return true; @@ -7077,47 +7948,25 @@ var ts; return false; } // Parses a list of elements - function parseList(kind, checkForStrictMode, parseElement) { + function parseList(kind, parseElement) { var saveParsingContext = parsingContext; parsingContext |= 1 << kind; var result = []; result.pos = getNodePos(); - var savedStrictModeContext = inStrictModeContext(); while (!isListTerminator(kind)) { if (isListElement(kind, false)) { var element = parseListElement(kind, parseElement); result.push(element); - // test elements only if we are not already in strict mode - if (checkForStrictMode && !inStrictModeContext()) { - if (ts.isPrologueDirective(element)) { - if (isUseStrictPrologueDirective(sourceFile, element)) { - setStrictModeContext(true); - checkForStrictMode = false; - } - } - else { - checkForStrictMode = false; - } - } continue; } if (abortParsingListOrMoveToNextToken(kind)) { break; } } - setStrictModeContext(savedStrictModeContext); result.end = getNodeEnd(); parsingContext = saveParsingContext; return result; } - /// Should be called only on prologue directives (isPrologueDirective(node) should be true) - function isUseStrictPrologueDirective(sourceFile, node) { - ts.Debug.assert(ts.isPrologueDirective(node)); - var nodeText = ts.getSourceTextOfNodeFromSourceFile(sourceFile, 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 parseListElement(parsingContext, parseElement) { var node = currentNode(parsingContext); if (node) { @@ -7165,7 +8014,7 @@ var ts; // differently depending on what mode it is in. // // This also applies to all our other context flags as well. - var nodeContextFlags = node.parserContextFlags & 63 /* ParserGeneratedFlags */; + var nodeContextFlags = node.parserContextFlags & 62 /* ParserGeneratedFlags */; if (nodeContextFlags !== contextFlags) { return undefined; } @@ -7184,37 +8033,36 @@ var ts; } function canReuseNode(node, parsingContext) { switch (parsingContext) { - case 1 /* ModuleElements */: - return isReusableModuleElement(node); - case 6 /* ClassMembers */: + case 5 /* ClassMembers */: return isReusableClassMember(node); - case 3 /* SwitchClauses */: + case 2 /* SwitchClauses */: return isReusableSwitchClause(node); - case 2 /* BlockStatements */: - case 4 /* SwitchClauseStatements */: + case 0 /* SourceElements */: + case 1 /* BlockStatements */: + case 3 /* SwitchClauseStatements */: return isReusableStatement(node); - case 7 /* EnumMembers */: + case 6 /* EnumMembers */: return isReusableEnumMember(node); - case 5 /* TypeMembers */: + case 4 /* TypeMembers */: return isReusableTypeMember(node); - case 9 /* VariableDeclarations */: + case 8 /* VariableDeclarations */: return isReusableVariableDeclaration(node); - case 15 /* Parameters */: + case 14 /* Parameters */: return isReusableParameter(node); // 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 19 /* HeritageClauses */: + case 18 /* HeritageClauses */: // This would probably be safe to reuse. There is no speculative parsing with // heritage clauses. - case 16 /* TypeParameters */: + case 15 /* 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 18 /* TupleElementTypes */: + case 17 /* 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 @@ -7222,51 +8070,41 @@ var ts; // 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 17 /* TypeArguments */: + case 16 /* 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 12 /* ArgumentExpressions */: + 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 13 /* ObjectLiteralMembers */: + 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 8 /* HeritageClauseElement */: - } - return false; - } - function isReusableModuleElement(node) { - if (node) { - switch (node.kind) { - case 210 /* ImportDeclaration */: - case 209 /* ImportEqualsDeclaration */: - case 216 /* ExportDeclaration */: - case 215 /* ExportAssignment */: - case 202 /* ClassDeclaration */: - case 203 /* InterfaceDeclaration */: - case 206 /* ModuleDeclaration */: - case 205 /* EnumDeclaration */: - return true; - } - return isReusableStatement(node); + case 7 /* HeritageClauseElement */: } return false; } function isReusableClassMember(node) { if (node) { switch (node.kind) { - case 136 /* Constructor */: - case 141 /* IndexSignature */: - case 135 /* MethodDeclaration */: - case 137 /* GetAccessor */: - case 138 /* SetAccessor */: - case 133 /* PropertyDeclaration */: - case 179 /* SemicolonClassElement */: + case 137 /* Constructor */: + case 142 /* IndexSignature */: + case 138 /* GetAccessor */: + case 139 /* SetAccessor */: + case 134 /* PropertyDeclaration */: + case 181 /* SemicolonClassElement */: return true; + case 136 /* 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 === 65 /* Identifier */ && + methodDeclaration.name.originalKeywordKind === 114 /* ConstructorKeyword */; + return !nameIsConstructor; } } return false; @@ -7274,8 +8112,8 @@ var ts; function isReusableSwitchClause(node) { if (node) { switch (node.kind) { - case 221 /* CaseClause */: - case 222 /* DefaultClause */: + case 223 /* CaseClause */: + case 224 /* DefaultClause */: return true; } } @@ -7284,49 +8122,58 @@ var ts; function isReusableStatement(node) { if (node) { switch (node.kind) { - case 201 /* FunctionDeclaration */: - case 181 /* VariableStatement */: - case 180 /* Block */: - case 184 /* IfStatement */: - case 183 /* ExpressionStatement */: - case 196 /* ThrowStatement */: - case 192 /* ReturnStatement */: - case 194 /* SwitchStatement */: - case 191 /* BreakStatement */: - case 190 /* ContinueStatement */: - case 188 /* ForInStatement */: - case 189 /* ForOfStatement */: - case 187 /* ForStatement */: - case 186 /* WhileStatement */: - case 193 /* WithStatement */: - case 182 /* EmptyStatement */: - case 197 /* TryStatement */: - case 195 /* LabeledStatement */: - case 185 /* DoStatement */: - case 198 /* DebuggerStatement */: + case 203 /* FunctionDeclaration */: + case 183 /* VariableStatement */: + case 182 /* Block */: + case 186 /* IfStatement */: + case 185 /* ExpressionStatement */: + case 198 /* ThrowStatement */: + case 194 /* ReturnStatement */: + case 196 /* SwitchStatement */: + case 193 /* BreakStatement */: + case 192 /* ContinueStatement */: + case 190 /* ForInStatement */: + case 191 /* ForOfStatement */: + case 189 /* ForStatement */: + case 188 /* WhileStatement */: + case 195 /* WithStatement */: + case 184 /* EmptyStatement */: + case 199 /* TryStatement */: + case 197 /* LabeledStatement */: + case 187 /* DoStatement */: + case 200 /* DebuggerStatement */: + case 212 /* ImportDeclaration */: + case 211 /* ImportEqualsDeclaration */: + case 218 /* ExportDeclaration */: + case 217 /* ExportAssignment */: + case 208 /* ModuleDeclaration */: + case 204 /* ClassDeclaration */: + case 205 /* InterfaceDeclaration */: + case 207 /* EnumDeclaration */: + case 206 /* TypeAliasDeclaration */: return true; } } return false; } function isReusableEnumMember(node) { - return node.kind === 227 /* EnumMember */; + return node.kind === 229 /* EnumMember */; } function isReusableTypeMember(node) { if (node) { switch (node.kind) { - case 140 /* ConstructSignature */: - case 134 /* MethodSignature */: - case 141 /* IndexSignature */: - case 132 /* PropertySignature */: - case 139 /* CallSignature */: + case 141 /* ConstructSignature */: + case 135 /* MethodSignature */: + case 142 /* IndexSignature */: + case 133 /* PropertySignature */: + case 140 /* CallSignature */: return true; } } return false; } function isReusableVariableDeclaration(node) { - if (node.kind !== 199 /* VariableDeclaration */) { + if (node.kind !== 201 /* VariableDeclaration */) { return false; } // Very subtle incremental parsing bug. Consider the following code: @@ -7347,7 +8194,7 @@ var ts; return variableDeclarator.initializer === undefined; } function isReusableParameter(node) { - if (node.kind !== 130 /* Parameter */) { + if (node.kind !== 131 /* Parameter */) { return false; } // See the comment in isReusableVariableDeclaration for why we do this. @@ -7366,26 +8213,29 @@ var ts; function parsingContextErrors(context) { switch (context) { case 0 /* SourceElements */: return ts.Diagnostics.Declaration_or_statement_expected; - case 1 /* ModuleElements */: return ts.Diagnostics.Declaration_or_statement_expected; - case 2 /* BlockStatements */: return ts.Diagnostics.Statement_expected; - case 3 /* SwitchClauses */: return ts.Diagnostics.case_or_default_expected; - case 4 /* SwitchClauseStatements */: return ts.Diagnostics.Statement_expected; - case 5 /* TypeMembers */: return ts.Diagnostics.Property_or_signature_expected; - case 6 /* ClassMembers */: return ts.Diagnostics.Unexpected_token_A_constructor_method_accessor_or_property_was_expected; - case 7 /* EnumMembers */: return ts.Diagnostics.Enum_member_expected; - case 8 /* HeritageClauseElement */: return ts.Diagnostics.Expression_expected; - case 9 /* VariableDeclarations */: return ts.Diagnostics.Variable_declaration_expected; - case 10 /* ObjectBindingElements */: return ts.Diagnostics.Property_destructuring_pattern_expected; - case 11 /* ArrayBindingElements */: return ts.Diagnostics.Array_element_destructuring_pattern_expected; - case 12 /* ArgumentExpressions */: return ts.Diagnostics.Argument_expression_expected; - case 13 /* ObjectLiteralMembers */: return ts.Diagnostics.Property_assignment_expected; - case 14 /* ArrayLiteralMembers */: return ts.Diagnostics.Expression_or_comma_expected; - case 15 /* Parameters */: return ts.Diagnostics.Parameter_declaration_expected; - case 16 /* TypeParameters */: return ts.Diagnostics.Type_parameter_declaration_expected; - case 17 /* TypeArguments */: return ts.Diagnostics.Type_argument_expected; - case 18 /* TupleElementTypes */: return ts.Diagnostics.Type_expected; - case 19 /* HeritageClauses */: return ts.Diagnostics.Unexpected_token_expected; - case 20 /* ImportOrExportSpecifiers */: return ts.Diagnostics.Identifier_expected; + case 1 /* BlockStatements */: return ts.Diagnostics.Declaration_or_statement_expected; + case 2 /* SwitchClauses */: return ts.Diagnostics.case_or_default_expected; + case 3 /* SwitchClauseStatements */: return ts.Diagnostics.Statement_expected; + case 4 /* TypeMembers */: return ts.Diagnostics.Property_or_signature_expected; + case 5 /* ClassMembers */: return ts.Diagnostics.Unexpected_token_A_constructor_method_accessor_or_property_was_expected; + case 6 /* EnumMembers */: return ts.Diagnostics.Enum_member_expected; + case 7 /* HeritageClauseElement */: return ts.Diagnostics.Expression_expected; + case 8 /* VariableDeclarations */: return ts.Diagnostics.Variable_declaration_expected; + case 9 /* ObjectBindingElements */: return ts.Diagnostics.Property_destructuring_pattern_expected; + case 10 /* ArrayBindingElements */: return ts.Diagnostics.Array_element_destructuring_pattern_expected; + case 11 /* ArgumentExpressions */: return ts.Diagnostics.Argument_expression_expected; + case 12 /* ObjectLiteralMembers */: return ts.Diagnostics.Property_assignment_expected; + case 13 /* ArrayLiteralMembers */: return ts.Diagnostics.Expression_or_comma_expected; + case 14 /* Parameters */: return ts.Diagnostics.Parameter_declaration_expected; + case 15 /* TypeParameters */: return ts.Diagnostics.Type_parameter_declaration_expected; + case 16 /* TypeArguments */: return ts.Diagnostics.Type_argument_expected; + case 17 /* TupleElementTypes */: return ts.Diagnostics.Type_expected; + case 18 /* HeritageClauses */: return ts.Diagnostics.Unexpected_token_expected; + case 19 /* ImportOrExportSpecifiers */: return ts.Diagnostics.Identifier_expected; + case 20 /* JSDocFunctionParameters */: return ts.Diagnostics.Parameter_declaration_expected; + case 21 /* JSDocTypeArguments */: return ts.Diagnostics.Type_argument_expected; + case 23 /* JSDocTupleTypes */: return ts.Diagnostics.Type_expected; + case 22 /* JSDocRecordMembers */: return ts.Diagnostics.Property_assignment_expected; } } ; @@ -7459,7 +8309,7 @@ var ts; function parseEntityName(allowReservedWords, diagnosticMessage) { var entity = parseIdentifier(diagnosticMessage); while (parseOptional(20 /* DotToken */)) { - var node = createNode(127 /* QualifiedName */, entity.pos); + var node = createNode(128 /* QualifiedName */, entity.pos); node.left = entity; node.right = parseRightSideOfDot(allowReservedWords); entity = finishNode(node); @@ -7467,38 +8317,38 @@ var ts; return entity; } function parseRightSideOfDot(allowIdentifierNames) { - // Technically a keyword is valid here as all keywords are identifier names. - // However, often we'll encounter this in error situations when the keyword + // 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. - // keyword identifierNameOrKeyword + // identifierOrKeyword identifierNameOrKeyword // // Note: the newlines are important here. For example, if that above code // were rewritten into: // - // name.keyword + // name.identifierOrKeyword // identifierNameOrKeyword // // Then we would consider it valid. That's because ASI would take effect and - // the code would be implicitly: "name.keyword; identifierNameOrKeyword". + // 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 keyword. - if (scanner.hasPrecedingLineBreak() && scanner.isReservedWord()) { + // line terminator after the identifier or keyword. + if (scanner.hasPrecedingLineBreak() && isIdentifierOrKeyword()) { 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 woudl be quite confusing. + // be an identifier and the error would be quite confusing. return createMissingNode(65 /* Identifier */, true, ts.Diagnostics.Identifier_expected); } } return allowIdentifierNames ? parseIdentifierName() : parseIdentifier(); } function parseTemplateExpression() { - var template = createNode(172 /* TemplateExpression */); + var template = createNode(174 /* TemplateExpression */); template.head = parseLiteralNode(); ts.Debug.assert(template.head.kind === 11 /* TemplateHead */, "Template head has wrong token kind"); var templateSpans = []; @@ -7511,7 +8361,7 @@ var ts; return finishNode(template); } function parseTemplateSpan() { - var span = createNode(178 /* TemplateSpan */); + var span = createNode(180 /* TemplateSpan */); span.expression = allowInAnd(parseExpression); var literal; if (token === 15 /* CloseBraceToken */) { @@ -7551,22 +8401,30 @@ var ts; return node; } // TYPES - function parseTypeReference() { - var node = createNode(142 /* TypeReference */); - node.typeName = parseEntityName(false, ts.Diagnostics.Type_expected); + function parseTypeReferenceOrTypePredicate() { + var typeName = parseEntityName(false, ts.Diagnostics.Type_expected); + if (typeName.kind === 65 /* Identifier */ && token === 117 /* IsKeyword */ && !scanner.hasPrecedingLineBreak()) { + nextToken(); + var node_1 = createNode(143 /* TypePredicate */, typeName.pos); + node_1.parameterName = typeName; + node_1.type = parseType(); + return finishNode(node_1); + } + var node = createNode(144 /* TypeReference */, typeName.pos); + node.typeName = typeName; if (!scanner.hasPrecedingLineBreak() && token === 24 /* LessThanToken */) { - node.typeArguments = parseBracketedList(17 /* TypeArguments */, parseType, 24 /* LessThanToken */, 25 /* GreaterThanToken */); + node.typeArguments = parseBracketedList(16 /* TypeArguments */, parseType, 24 /* LessThanToken */, 25 /* GreaterThanToken */); } return finishNode(node); } function parseTypeQuery() { - var node = createNode(145 /* TypeQuery */); + var node = createNode(147 /* TypeQuery */); parseExpected(97 /* TypeOfKeyword */); node.exprName = parseEntityName(true); return finishNode(node); } function parseTypeParameter() { - var node = createNode(129 /* TypeParameter */); + var node = createNode(130 /* TypeParameter */); node.name = parseIdentifier(); if (parseOptional(79 /* ExtendsKeyword */)) { // It's not uncommon for people to write improper constraints to a generic. If the @@ -7591,7 +8449,7 @@ var ts; } function parseTypeParameters() { if (token === 24 /* LessThanToken */) { - return parseBracketedList(16 /* TypeParameters */, parseTypeParameter, 24 /* LessThanToken */, 25 /* GreaterThanToken */); + return parseBracketedList(15 /* TypeParameters */, parseTypeParameter, 24 /* LessThanToken */, 25 /* GreaterThanToken */); } } function parseParameterType() { @@ -7612,7 +8470,7 @@ var ts; } } function parseParameter() { - var node = createNode(130 /* Parameter */); + var node = createNode(131 /* Parameter */); node.decorators = parseDecorators(); setModifiers(node, parseModifiers()); node.dotDotDotToken = parseOptionalToken(21 /* DotDotDotToken */); @@ -7683,7 +8541,7 @@ var ts; var savedGeneratorParameterContext = inGeneratorParameterContext(); setYieldContext(yieldAndGeneratorParameterContext); setGeneratorParameterContext(yieldAndGeneratorParameterContext); - var result = parseDelimitedList(15 /* Parameters */, parseParameter); + var result = parseDelimitedList(14 /* Parameters */, parseParameter); setYieldContext(savedYieldContext); setGeneratorParameterContext(savedGeneratorParameterContext); if (!parseExpected(17 /* CloseParenToken */) && requireCompleteParameterList) { @@ -7709,7 +8567,7 @@ var ts; } function parseSignatureMember(kind) { var node = createNode(kind); - if (kind === 140 /* ConstructSignature */) { + if (kind === 141 /* ConstructSignature */) { parseExpected(88 /* NewKeyword */); } fillSignature(51 /* ColonToken */, false, false, node); @@ -7773,10 +8631,10 @@ var ts; return token === 51 /* ColonToken */ || token === 23 /* CommaToken */ || token === 19 /* CloseBracketToken */; } function parseIndexSignatureDeclaration(fullStart, decorators, modifiers) { - var node = createNode(141 /* IndexSignature */, fullStart); + var node = createNode(142 /* IndexSignature */, fullStart); node.decorators = decorators; setModifiers(node, modifiers); - node.parameters = parseBracketedList(15 /* Parameters */, parseParameter, 18 /* OpenBracketToken */, 19 /* CloseBracketToken */); + node.parameters = parseBracketedList(14 /* Parameters */, parseParameter, 18 /* OpenBracketToken */, 19 /* CloseBracketToken */); node.type = parseTypeAnnotation(); parseTypeMemberSemicolon(); return finishNode(node); @@ -7786,7 +8644,7 @@ var ts; var name = parsePropertyName(); var questionToken = parseOptionalToken(50 /* QuestionToken */); if (token === 16 /* OpenParenToken */ || token === 24 /* LessThanToken */) { - var method = createNode(134 /* MethodSignature */, fullStart); + var method = createNode(135 /* MethodSignature */, fullStart); method.name = name; method.questionToken = questionToken; // Method signatues don't exist in expression contexts. So they have neither @@ -7796,7 +8654,7 @@ var ts; return finishNode(method); } else { - var property = createNode(132 /* PropertySignature */, fullStart); + var property = createNode(133 /* PropertySignature */, fullStart); property.name = name; property.questionToken = questionToken; property.type = parseTypeAnnotation(); @@ -7838,7 +8696,7 @@ var ts; switch (token) { case 16 /* OpenParenToken */: case 24 /* LessThanToken */: - return parseSignatureMember(139 /* CallSignature */); + return parseSignatureMember(140 /* CallSignature */); case 18 /* OpenBracketToken */: // Indexer or computed property return isIndexSignature() @@ -7846,7 +8704,7 @@ var ts; : parsePropertyOrMethodSignature(); case 88 /* NewKeyword */: if (lookAhead(isStartOfConstructSignature)) { - return parseSignatureMember(140 /* ConstructSignature */); + return parseSignatureMember(141 /* ConstructSignature */); } // fall through. case 8 /* StringLiteral */: @@ -7883,14 +8741,14 @@ var ts; return token === 16 /* OpenParenToken */ || token === 24 /* LessThanToken */; } function parseTypeLiteral() { - var node = createNode(146 /* TypeLiteral */); + var node = createNode(148 /* TypeLiteral */); node.members = parseObjectTypeMembers(); return finishNode(node); } function parseObjectTypeMembers() { var members; if (parseExpected(14 /* OpenBraceToken */)) { - members = parseList(5 /* TypeMembers */, false, parseTypeMember); + members = parseList(4 /* TypeMembers */, parseTypeMember); parseExpected(15 /* CloseBraceToken */); } else { @@ -7899,12 +8757,12 @@ var ts; return members; } function parseTupleType() { - var node = createNode(148 /* TupleType */); - node.elementTypes = parseBracketedList(18 /* TupleElementTypes */, parseType, 18 /* OpenBracketToken */, 19 /* CloseBracketToken */); + var node = createNode(150 /* TupleType */); + node.elementTypes = parseBracketedList(17 /* TupleElementTypes */, parseType, 18 /* OpenBracketToken */, 19 /* CloseBracketToken */); return finishNode(node); } function parseParenthesizedType() { - var node = createNode(150 /* ParenthesizedType */); + var node = createNode(152 /* ParenthesizedType */); parseExpected(16 /* OpenParenToken */); node.type = parseType(); parseExpected(17 /* CloseParenToken */); @@ -7912,7 +8770,7 @@ var ts; } function parseFunctionOrConstructorType(kind) { var node = createNode(kind); - if (kind === 144 /* ConstructorType */) { + if (kind === 146 /* ConstructorType */) { parseExpected(88 /* NewKeyword */); } fillSignature(32 /* EqualsGreaterThanToken */, false, false, node); @@ -7925,13 +8783,13 @@ var ts; function parseNonArrayType() { switch (token) { case 112 /* AnyKeyword */: - case 122 /* StringKeyword */: - case 120 /* NumberKeyword */: + case 123 /* StringKeyword */: + case 121 /* NumberKeyword */: case 113 /* BooleanKeyword */: - case 123 /* SymbolKeyword */: + case 124 /* SymbolKeyword */: // If these are followed by a dot, then parse these out as a dotted type reference instead. var node = tryParse(parseKeywordAndNoDot); - return node || parseTypeReference(); + return node || parseTypeReferenceOrTypePredicate(); case 99 /* VoidKeyword */: return parseTokenNode(); case 97 /* TypeOfKeyword */: @@ -7943,16 +8801,16 @@ var ts; case 16 /* OpenParenToken */: return parseParenthesizedType(); default: - return parseTypeReference(); + return parseTypeReferenceOrTypePredicate(); } } function isStartOfType() { switch (token) { case 112 /* AnyKeyword */: - case 122 /* StringKeyword */: - case 120 /* NumberKeyword */: + case 123 /* StringKeyword */: + case 121 /* NumberKeyword */: case 113 /* BooleanKeyword */: - case 123 /* SymbolKeyword */: + case 124 /* SymbolKeyword */: case 99 /* VoidKeyword */: case 97 /* TypeOfKeyword */: case 14 /* OpenBraceToken */: @@ -7976,7 +8834,7 @@ var ts; var type = parseNonArrayType(); while (!scanner.hasPrecedingLineBreak() && parseOptional(18 /* OpenBracketToken */)) { parseExpected(19 /* CloseBracketToken */); - var node = createNode(147 /* ArrayType */, type.pos); + var node = createNode(149 /* ArrayType */, type.pos); node.elementType = type; type = finishNode(node); } @@ -7991,7 +8849,7 @@ var ts; types.push(parseArrayTypeOrHigher()); } types.end = getNodeEnd(); - var node = createNode(149 /* UnionType */, type.pos); + var node = createNode(151 /* UnionType */, type.pos); node.types = types; type = finishNode(node); } @@ -8046,10 +8904,10 @@ var ts; } function parseTypeWorker() { if (isStartOfFunctionType()) { - return parseFunctionOrConstructorType(143 /* FunctionType */); + return parseFunctionOrConstructorType(145 /* FunctionType */); } if (token === 88 /* NewKeyword */) { - return parseFunctionOrConstructorType(144 /* ConstructorType */); + return parseFunctionOrConstructorType(146 /* ConstructorType */); } return parseUnionTypeOrHigher(); } @@ -8218,11 +9076,6 @@ var ts; if (inYieldContext()) { return true; } - if (inStrictModeContext()) { - // If we're in strict mode, then 'yield' is a keyword, could only ever start - // a yield expression. - 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 @@ -8237,7 +9090,7 @@ var ts; // 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 accidently consume something legal. - return lookAhead(nextTokenIsIdentifierOnSameLine); + return lookAhead(nextTokenIsIdentifierOrKeywordOrNumberOnSameLine); } return false; } @@ -8245,13 +9098,8 @@ var ts; nextToken(); return !scanner.hasPrecedingLineBreak() && isIdentifier(); } - function nextTokenIsIdentifierOrStartOfDestructuringOnTheSameLine() { - nextToken(); - return !scanner.hasPrecedingLineBreak() && - (isIdentifier() || token === 14 /* OpenBraceToken */ || token === 18 /* OpenBracketToken */); - } function parseYieldExpression() { - var node = createNode(173 /* YieldExpression */); + var node = createNode(175 /* YieldExpression */); // YieldExpression[In] : // yield // yield [no LineTerminator here] [Lexical goal InputElementRegExp]AssignmentExpression[?In, Yield] @@ -8271,8 +9119,8 @@ var ts; } function parseSimpleArrowFunctionExpression(identifier) { ts.Debug.assert(token === 32 /* EqualsGreaterThanToken */, "parseSimpleArrowFunctionExpression should only have been called if we had a =>"); - var node = createNode(164 /* ArrowFunction */, identifier.pos); - var parameter = createNode(130 /* Parameter */, identifier.pos); + var node = createNode(166 /* ArrowFunction */, identifier.pos); + var parameter = createNode(131 /* Parameter */, identifier.pos); parameter.name = identifier; finishNode(parameter); node.parameters = [parameter]; @@ -8390,7 +9238,7 @@ var ts; return parseParenthesizedArrowFunctionExpressionHead(false); } function parseParenthesizedArrowFunctionExpressionHead(allowAmbiguity) { - var node = createNode(164 /* ArrowFunction */); + var node = createNode(166 /* ArrowFunction */); // Arrow functions are never generators. // // If we're speculatively parsing a signature for a parenthesized arrow function, then @@ -8421,10 +9269,11 @@ var ts; if (token === 14 /* OpenBraceToken */) { return parseFunctionBlock(false, false); } - if (isStartOfStatement(true) && - !isStartOfExpressionStatement() && + if (token !== 22 /* SemicolonToken */ && token !== 83 /* FunctionKeyword */ && - token !== 69 /* ClassKeyword */) { + token !== 69 /* 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 @@ -8451,7 +9300,7 @@ var ts; } // Note: we explicitly 'allowIn' in the whenTrue part of the condition expression, and // we do not that for the 'whenFalse' part. - var node = createNode(171 /* ConditionalExpression */, leftOperand.pos); + var node = createNode(173 /* ConditionalExpression */, leftOperand.pos); node.condition = leftOperand; node.questionToken = questionToken; node.whenTrue = doOutsideOfContext(disallowInAndDecoratorContext, parseAssignmentExpressionOrHigher); @@ -8464,7 +9313,7 @@ var ts; return parseBinaryExpressionRest(precedence, leftOperand); } function isInOrOfKeyword(t) { - return t === 86 /* InKeyword */ || t === 126 /* OfKeyword */; + return t === 86 /* InKeyword */ || t === 127 /* OfKeyword */; } function parseBinaryExpressionRest(precedence, leftOperand) { while (true) { @@ -8530,33 +9379,33 @@ var ts; return -1; } function makeBinaryExpression(left, operatorToken, right) { - var node = createNode(170 /* BinaryExpression */, left.pos); + var node = createNode(172 /* BinaryExpression */, left.pos); node.left = left; node.operatorToken = operatorToken; node.right = right; return finishNode(node); } function parsePrefixUnaryExpression() { - var node = createNode(168 /* PrefixUnaryExpression */); + var node = createNode(170 /* PrefixUnaryExpression */); node.operator = token; nextToken(); node.operand = parseUnaryExpressionOrHigher(); return finishNode(node); } function parseDeleteExpression() { - var node = createNode(165 /* DeleteExpression */); + var node = createNode(167 /* DeleteExpression */); nextToken(); node.expression = parseUnaryExpressionOrHigher(); return finishNode(node); } function parseTypeOfExpression() { - var node = createNode(166 /* TypeOfExpression */); + var node = createNode(168 /* TypeOfExpression */); nextToken(); node.expression = parseUnaryExpressionOrHigher(); return finishNode(node); } function parseVoidExpression() { - var node = createNode(167 /* VoidExpression */); + var node = createNode(169 /* VoidExpression */); nextToken(); node.expression = parseUnaryExpressionOrHigher(); return finishNode(node); @@ -8586,7 +9435,7 @@ var ts; var expression = parseLeftHandSideExpressionOrHigher(); ts.Debug.assert(ts.isLeftHandSideExpression(expression)); if ((token === 38 /* PlusPlusToken */ || token === 39 /* MinusMinusToken */) && !scanner.hasPrecedingLineBreak()) { - var node = createNode(169 /* PostfixUnaryExpression */, expression.pos); + var node = createNode(171 /* PostfixUnaryExpression */, expression.pos); node.operand = expression; node.operator = token; nextToken(); @@ -8690,14 +9539,14 @@ var ts; } // 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(156 /* PropertyAccessExpression */, expression.pos); + var node = createNode(158 /* PropertyAccessExpression */, expression.pos); node.expression = expression; node.dotToken = parseExpectedToken(20 /* DotToken */, false, ts.Diagnostics.super_must_be_followed_by_an_argument_list_or_member_access); node.name = parseRightSideOfDot(true); return finishNode(node); } function parseTypeAssertion() { - var node = createNode(161 /* TypeAssertionExpression */); + var node = createNode(163 /* TypeAssertionExpression */); parseExpected(24 /* LessThanToken */); node.type = parseType(); parseExpected(25 /* GreaterThanToken */); @@ -8708,7 +9557,7 @@ var ts; while (true) { var dotToken = parseOptionalToken(20 /* DotToken */); if (dotToken) { - var propertyAccess = createNode(156 /* PropertyAccessExpression */, expression.pos); + var propertyAccess = createNode(158 /* PropertyAccessExpression */, expression.pos); propertyAccess.expression = expression; propertyAccess.dotToken = dotToken; propertyAccess.name = parseRightSideOfDot(true); @@ -8717,7 +9566,7 @@ var ts; } // when in the [Decorator] context, we do not parse ElementAccess as it could be part of a ComputedPropertyName if (!inDecoratorContext() && parseOptional(18 /* OpenBracketToken */)) { - var indexedAccess = createNode(157 /* ElementAccessExpression */, expression.pos); + var indexedAccess = createNode(159 /* 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. @@ -8733,7 +9582,7 @@ var ts; continue; } if (token === 10 /* NoSubstitutionTemplateLiteral */ || token === 11 /* TemplateHead */) { - var tagExpression = createNode(160 /* TaggedTemplateExpression */, expression.pos); + var tagExpression = createNode(162 /* TaggedTemplateExpression */, expression.pos); tagExpression.tag = expression; tagExpression.template = token === 10 /* NoSubstitutionTemplateLiteral */ ? parseLiteralNode() @@ -8756,7 +9605,7 @@ var ts; if (!typeArguments) { return expression; } - var callExpr = createNode(158 /* CallExpression */, expression.pos); + var callExpr = createNode(160 /* CallExpression */, expression.pos); callExpr.expression = expression; callExpr.typeArguments = typeArguments; callExpr.arguments = parseArgumentList(); @@ -8764,7 +9613,7 @@ var ts; continue; } else if (token === 16 /* OpenParenToken */) { - var callExpr = createNode(158 /* CallExpression */, expression.pos); + var callExpr = createNode(160 /* CallExpression */, expression.pos); callExpr.expression = expression; callExpr.arguments = parseArgumentList(); expression = finishNode(callExpr); @@ -8775,7 +9624,7 @@ var ts; } function parseArgumentList() { parseExpected(16 /* OpenParenToken */); - var result = parseDelimitedList(12 /* ArgumentExpressions */, parseArgumentExpression); + var result = parseDelimitedList(11 /* ArgumentExpressions */, parseArgumentExpression); parseExpected(17 /* CloseParenToken */); return result; } @@ -8783,7 +9632,7 @@ var ts; if (!parseOptional(24 /* LessThanToken */)) { return undefined; } - var typeArguments = parseDelimitedList(17 /* TypeArguments */, parseType); + var typeArguments = parseDelimitedList(16 /* TypeArguments */, parseType); if (!parseExpected(25 /* GreaterThanToken */)) { // If it doesn't have the closing > then it's definitely not an type argument list. return undefined; @@ -8866,41 +9715,41 @@ var ts; return parseIdentifier(ts.Diagnostics.Expression_expected); } function parseParenthesizedExpression() { - var node = createNode(162 /* ParenthesizedExpression */); + var node = createNode(164 /* ParenthesizedExpression */); parseExpected(16 /* OpenParenToken */); node.expression = allowInAnd(parseExpression); parseExpected(17 /* CloseParenToken */); return finishNode(node); } function parseSpreadElement() { - var node = createNode(174 /* SpreadElementExpression */); + var node = createNode(176 /* SpreadElementExpression */); parseExpected(21 /* DotDotDotToken */); node.expression = parseAssignmentExpressionOrHigher(); return finishNode(node); } function parseArgumentOrArrayLiteralElement() { return token === 21 /* DotDotDotToken */ ? parseSpreadElement() : - token === 23 /* CommaToken */ ? createNode(176 /* OmittedExpression */) : + token === 23 /* CommaToken */ ? createNode(178 /* OmittedExpression */) : parseAssignmentExpressionOrHigher(); } function parseArgumentExpression() { return doOutsideOfContext(disallowInAndDecoratorContext, parseArgumentOrArrayLiteralElement); } function parseArrayLiteralExpression() { - var node = createNode(154 /* ArrayLiteralExpression */); + var node = createNode(156 /* ArrayLiteralExpression */); parseExpected(18 /* OpenBracketToken */); if (scanner.hasPrecedingLineBreak()) node.flags |= 512 /* MultiLine */; - node.elements = parseDelimitedList(14 /* ArrayLiteralMembers */, parseArgumentOrArrayLiteralElement); + node.elements = parseDelimitedList(13 /* ArrayLiteralMembers */, parseArgumentOrArrayLiteralElement); parseExpected(19 /* CloseBracketToken */); return finishNode(node); } function tryParseAccessorDeclaration(fullStart, decorators, modifiers) { if (parseContextualModifier(116 /* GetKeyword */)) { - return parseAccessorDeclaration(137 /* GetAccessor */, fullStart, decorators, modifiers); + return parseAccessorDeclaration(138 /* GetAccessor */, fullStart, decorators, modifiers); } - else if (parseContextualModifier(121 /* SetKeyword */)) { - return parseAccessorDeclaration(138 /* SetAccessor */, fullStart, decorators, modifiers); + else if (parseContextualModifier(122 /* SetKeyword */)) { + return parseAccessorDeclaration(139 /* SetAccessor */, fullStart, decorators, modifiers); } return undefined; } @@ -8923,13 +9772,13 @@ var ts; } // Parse to check if it is short-hand property assignment or normal property assignment if ((token === 23 /* CommaToken */ || token === 15 /* CloseBraceToken */) && tokenIsIdentifier) { - var shorthandDeclaration = createNode(226 /* ShorthandPropertyAssignment */, fullStart); + var shorthandDeclaration = createNode(228 /* ShorthandPropertyAssignment */, fullStart); shorthandDeclaration.name = propertyName; shorthandDeclaration.questionToken = questionToken; return finishNode(shorthandDeclaration); } else { - var propertyAssignment = createNode(225 /* PropertyAssignment */, fullStart); + var propertyAssignment = createNode(227 /* PropertyAssignment */, fullStart); propertyAssignment.name = propertyName; propertyAssignment.questionToken = questionToken; parseExpected(51 /* ColonToken */); @@ -8938,12 +9787,12 @@ var ts; } } function parseObjectLiteralExpression() { - var node = createNode(155 /* ObjectLiteralExpression */); + var node = createNode(157 /* ObjectLiteralExpression */); parseExpected(14 /* OpenBraceToken */); if (scanner.hasPrecedingLineBreak()) { node.flags |= 512 /* MultiLine */; } - node.properties = parseDelimitedList(13 /* ObjectLiteralMembers */, parseObjectLiteralElement, true); + node.properties = parseDelimitedList(12 /* ObjectLiteralMembers */, parseObjectLiteralElement, true); parseExpected(15 /* CloseBraceToken */); return finishNode(node); } @@ -8956,7 +9805,7 @@ var ts; if (saveDecoratorContext) { setDecoratorContext(false); } - var node = createNode(163 /* FunctionExpression */); + var node = createNode(165 /* FunctionExpression */); parseExpected(83 /* FunctionKeyword */); node.asteriskToken = parseOptionalToken(35 /* AsteriskToken */); node.name = node.asteriskToken ? doInYieldContext(parseOptionalIdentifier) : parseOptionalIdentifier(); @@ -8971,7 +9820,7 @@ var ts; return isIdentifier() ? parseIdentifier() : undefined; } function parseNewExpression() { - var node = createNode(159 /* NewExpression */); + var node = createNode(161 /* NewExpression */); parseExpected(88 /* NewKeyword */); node.expression = parseMemberExpressionOrHigher(); node.typeArguments = tryParse(parseTypeArgumentsInExpression); @@ -8981,10 +9830,10 @@ var ts; return finishNode(node); } // STATEMENTS - function parseBlock(ignoreMissingOpenBrace, checkForStrictMode, diagnosticMessage) { - var node = createNode(180 /* Block */); + function parseBlock(ignoreMissingOpenBrace, diagnosticMessage) { + var node = createNode(182 /* Block */); if (parseExpected(14 /* OpenBraceToken */, diagnosticMessage) || ignoreMissingOpenBrace) { - node.statements = parseList(2 /* BlockStatements */, checkForStrictMode, parseStatement); + node.statements = parseList(1 /* BlockStatements */, parseStatement); parseExpected(15 /* CloseBraceToken */); } else { @@ -9001,7 +9850,7 @@ var ts; if (saveDecoratorContext) { setDecoratorContext(false); } - var block = parseBlock(ignoreMissingOpenBrace, true, diagnosticMessage); + var block = parseBlock(ignoreMissingOpenBrace, diagnosticMessage); if (saveDecoratorContext) { setDecoratorContext(true); } @@ -9009,12 +9858,12 @@ var ts; return block; } function parseEmptyStatement() { - var node = createNode(182 /* EmptyStatement */); + var node = createNode(184 /* EmptyStatement */); parseExpected(22 /* SemicolonToken */); return finishNode(node); } function parseIfStatement() { - var node = createNode(184 /* IfStatement */); + var node = createNode(186 /* IfStatement */); parseExpected(84 /* IfKeyword */); parseExpected(16 /* OpenParenToken */); node.expression = allowInAnd(parseExpression); @@ -9024,7 +9873,7 @@ var ts; return finishNode(node); } function parseDoStatement() { - var node = createNode(185 /* DoStatement */); + var node = createNode(187 /* DoStatement */); parseExpected(75 /* DoKeyword */); node.statement = parseStatement(); parseExpected(100 /* WhileKeyword */); @@ -9039,7 +9888,7 @@ var ts; return finishNode(node); } function parseWhileStatement() { - var node = createNode(186 /* WhileStatement */); + var node = createNode(188 /* WhileStatement */); parseExpected(100 /* WhileKeyword */); parseExpected(16 /* OpenParenToken */); node.expression = allowInAnd(parseExpression); @@ -9062,21 +9911,21 @@ var ts; } var forOrForInOrForOfStatement; if (parseOptional(86 /* InKeyword */)) { - var forInStatement = createNode(188 /* ForInStatement */, pos); + var forInStatement = createNode(190 /* ForInStatement */, pos); forInStatement.initializer = initializer; forInStatement.expression = allowInAnd(parseExpression); parseExpected(17 /* CloseParenToken */); forOrForInOrForOfStatement = forInStatement; } - else if (parseOptional(126 /* OfKeyword */)) { - var forOfStatement = createNode(189 /* ForOfStatement */, pos); + else if (parseOptional(127 /* OfKeyword */)) { + var forOfStatement = createNode(191 /* ForOfStatement */, pos); forOfStatement.initializer = initializer; forOfStatement.expression = allowInAnd(parseAssignmentExpressionOrHigher); parseExpected(17 /* CloseParenToken */); forOrForInOrForOfStatement = forOfStatement; } else { - var forStatement = createNode(187 /* ForStatement */, pos); + var forStatement = createNode(189 /* ForStatement */, pos); forStatement.initializer = initializer; parseExpected(22 /* SemicolonToken */); if (token !== 22 /* SemicolonToken */ && token !== 17 /* CloseParenToken */) { @@ -9094,7 +9943,7 @@ var ts; } function parseBreakOrContinueStatement(kind) { var node = createNode(kind); - parseExpected(kind === 191 /* BreakStatement */ ? 66 /* BreakKeyword */ : 71 /* ContinueKeyword */); + parseExpected(kind === 193 /* BreakStatement */ ? 66 /* BreakKeyword */ : 71 /* ContinueKeyword */); if (!canParseSemicolon()) { node.label = parseIdentifier(); } @@ -9102,7 +9951,7 @@ var ts; return finishNode(node); } function parseReturnStatement() { - var node = createNode(192 /* ReturnStatement */); + var node = createNode(194 /* ReturnStatement */); parseExpected(90 /* ReturnKeyword */); if (!canParseSemicolon()) { node.expression = allowInAnd(parseExpression); @@ -9111,7 +9960,7 @@ var ts; return finishNode(node); } function parseWithStatement() { - var node = createNode(193 /* WithStatement */); + var node = createNode(195 /* WithStatement */); parseExpected(101 /* WithKeyword */); parseExpected(16 /* OpenParenToken */); node.expression = allowInAnd(parseExpression); @@ -9120,32 +9969,32 @@ var ts; return finishNode(node); } function parseCaseClause() { - var node = createNode(221 /* CaseClause */); + var node = createNode(223 /* CaseClause */); parseExpected(67 /* CaseKeyword */); node.expression = allowInAnd(parseExpression); parseExpected(51 /* ColonToken */); - node.statements = parseList(4 /* SwitchClauseStatements */, false, parseStatement); + node.statements = parseList(3 /* SwitchClauseStatements */, parseStatement); return finishNode(node); } function parseDefaultClause() { - var node = createNode(222 /* DefaultClause */); + var node = createNode(224 /* DefaultClause */); parseExpected(73 /* DefaultKeyword */); parseExpected(51 /* ColonToken */); - node.statements = parseList(4 /* SwitchClauseStatements */, false, parseStatement); + node.statements = parseList(3 /* SwitchClauseStatements */, parseStatement); return finishNode(node); } function parseCaseOrDefaultClause() { return token === 67 /* CaseKeyword */ ? parseCaseClause() : parseDefaultClause(); } function parseSwitchStatement() { - var node = createNode(194 /* SwitchStatement */); + var node = createNode(196 /* SwitchStatement */); parseExpected(92 /* SwitchKeyword */); parseExpected(16 /* OpenParenToken */); node.expression = allowInAnd(parseExpression); parseExpected(17 /* CloseParenToken */); - var caseBlock = createNode(208 /* CaseBlock */, scanner.getStartPos()); + var caseBlock = createNode(210 /* CaseBlock */, scanner.getStartPos()); parseExpected(14 /* OpenBraceToken */); - caseBlock.clauses = parseList(3 /* SwitchClauses */, false, parseCaseOrDefaultClause); + caseBlock.clauses = parseList(2 /* SwitchClauses */, parseCaseOrDefaultClause); parseExpected(15 /* CloseBraceToken */); node.caseBlock = finishNode(caseBlock); return finishNode(node); @@ -9158,7 +10007,7 @@ var ts; // 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(196 /* ThrowStatement */); + var node = createNode(198 /* ThrowStatement */); parseExpected(94 /* ThrowKeyword */); node.expression = scanner.hasPrecedingLineBreak() ? undefined : allowInAnd(parseExpression); parseSemicolon(); @@ -9166,30 +10015,30 @@ var ts; } // TODO: Review for error recovery function parseTryStatement() { - var node = createNode(197 /* TryStatement */); + var node = createNode(199 /* TryStatement */); parseExpected(96 /* TryKeyword */); - node.tryBlock = parseBlock(false, false); + node.tryBlock = parseBlock(false); node.catchClause = token === 68 /* 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 === 81 /* FinallyKeyword */) { parseExpected(81 /* FinallyKeyword */); - node.finallyBlock = parseBlock(false, false); + node.finallyBlock = parseBlock(false); } return finishNode(node); } function parseCatchClause() { - var result = createNode(224 /* CatchClause */); + var result = createNode(226 /* CatchClause */); parseExpected(68 /* CatchKeyword */); if (parseExpected(16 /* OpenParenToken */)) { result.variableDeclaration = parseVariableDeclaration(); } parseExpected(17 /* CloseParenToken */); - result.block = parseBlock(false, false); + result.block = parseBlock(false); return finishNode(result); } function parseDebuggerStatement() { - var node = createNode(198 /* DebuggerStatement */); + var node = createNode(200 /* DebuggerStatement */); parseExpected(72 /* DebuggerKeyword */); parseSemicolon(); return finishNode(node); @@ -9201,45 +10050,108 @@ var ts; var fullStart = scanner.getStartPos(); var expression = allowInAnd(parseExpression); if (expression.kind === 65 /* Identifier */ && parseOptional(51 /* ColonToken */)) { - var labeledStatement = createNode(195 /* LabeledStatement */, fullStart); + var labeledStatement = createNode(197 /* LabeledStatement */, fullStart); labeledStatement.label = expression; labeledStatement.statement = parseStatement(); return finishNode(labeledStatement); } else { - var expressionStatement = createNode(183 /* ExpressionStatement */, fullStart); + var expressionStatement = createNode(185 /* ExpressionStatement */, fullStart); expressionStatement.expression = expression; parseSemicolon(); return finishNode(expressionStatement); } } - function isStartOfStatement(inErrorRecovery) { - // Functions, variable statements and classes are allowed as a statement. But as per - // the grammar, they also allow modifiers. So we have to check for those statements - // that might be following modifiers.This ensures that things work properly when - // incrementally parsing as the parser will produce the same FunctionDeclaraiton, - // VariableStatement or ClassDeclaration, if it has the same text regardless of whether - // it is inside a block or not. - if (ts.isModifier(token)) { - var result = lookAhead(parseVariableStatementOrFunctionDeclarationOrClassDeclarationWithDecoratorsOrModifiers); - if (result) { - return true; + function isIdentifierOrKeyword() { + return token >= 65 /* Identifier */; + } + function nextTokenIsIdentifierOrKeywordOnSameLine() { + nextToken(); + return isIdentifierOrKeyword() && !scanner.hasPrecedingLineBreak(); + } + function nextTokenIsIdentifierOrKeywordOrNumberOnSameLine() { + nextToken(); + return (isIdentifierOrKeyword() || token === 7 /* NumericLiteral */) && !scanner.hasPrecedingLineBreak(); + } + function isDeclaration() { + while (true) { + switch (token) { + case 98 /* VarKeyword */: + case 104 /* LetKeyword */: + case 70 /* ConstKeyword */: + case 83 /* FunctionKeyword */: + case 69 /* ClassKeyword */: + case 77 /* 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 103 /* InterfaceKeyword */: + case 125 /* TypeKeyword */: + return nextTokenIsIdentifierOnSameLine(); + case 118 /* ModuleKeyword */: + case 119 /* NamespaceKeyword */: + return nextTokenIsIdentifierOrStringLiteralOnSameLine(); + case 115 /* DeclareKeyword */: + nextToken(); + // ASI takes effect for this modifier. + if (scanner.hasPrecedingLineBreak()) { + return false; + } + continue; + case 85 /* ImportKeyword */: + nextToken(); + return token === 8 /* StringLiteral */ || token === 35 /* AsteriskToken */ || + token === 14 /* OpenBraceToken */ || isIdentifierOrKeyword(); + case 78 /* ExportKeyword */: + nextToken(); + if (token === 53 /* EqualsToken */ || token === 35 /* AsteriskToken */ || + token === 14 /* OpenBraceToken */ || token === 73 /* DefaultKeyword */) { + return true; + } + continue; + case 108 /* PublicKeyword */: + case 106 /* PrivateKeyword */: + case 107 /* ProtectedKeyword */: + case 109 /* StaticKeyword */: + nextToken(); + continue; + default: + return false; } } + } + function isStartOfDeclaration() { + return lookAhead(isDeclaration); + } + function isStartOfStatement() { switch (token) { + case 52 /* AtToken */: case 22 /* SemicolonToken */: - // 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 !inErrorRecovery; case 14 /* OpenBraceToken */: case 98 /* VarKeyword */: case 104 /* LetKeyword */: case 83 /* FunctionKeyword */: case 69 /* ClassKeyword */: + case 77 /* EnumKeyword */: case 84 /* IfKeyword */: case 75 /* DoKeyword */: case 100 /* WhileKeyword */: @@ -9258,56 +10170,53 @@ var ts; case 81 /* FinallyKeyword */: return true; case 70 /* ConstKeyword */: - // const keyword can precede enum keyword when defining constant enums - // 'const enum' do not start statement. - // In ES 6 'enum' is a future reserved keyword, so it should not be used as identifier - var isConstEnum = lookAhead(nextTokenIsEnumKeyword); - return !isConstEnum; + case 78 /* ExportKeyword */: + case 85 /* ImportKeyword */: + return isStartOfDeclaration(); + case 115 /* DeclareKeyword */: case 103 /* InterfaceKeyword */: - case 117 /* ModuleKeyword */: - case 118 /* NamespaceKeyword */: - case 77 /* EnumKeyword */: - case 124 /* TypeKeyword */: - // When followed by an identifier, these do not start a statement but might - // instead be following declarations - if (isDeclarationStart()) { - return false; - } + case 118 /* ModuleKeyword */: + case 119 /* NamespaceKeyword */: + case 125 /* TypeKeyword */: + // When these don't start a declaration, they're an identifier in an expression statement + return true; case 108 /* PublicKeyword */: case 106 /* PrivateKeyword */: case 107 /* ProtectedKeyword */: case 109 /* StaticKeyword */: - // When followed by an identifier or keyword, these do not start a statement but - // might instead be following type members - if (lookAhead(nextTokenIsIdentifierOrKeywordOnSameLine)) { - return false; - } + // 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 nextTokenIsEnumKeyword() { + function nextTokenIsIdentifierOrStartOfDestructuring() { nextToken(); - return token === 77 /* EnumKeyword */; + return isIdentifier() || token === 14 /* OpenBraceToken */ || token === 18 /* OpenBracketToken */; } - function nextTokenIsIdentifierOrKeywordOnSameLine() { - nextToken(); - return isIdentifierOrKeyword() && !scanner.hasPrecedingLineBreak(); + 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 22 /* SemicolonToken */: + return parseEmptyStatement(); case 14 /* OpenBraceToken */: - return parseBlock(false, false); + return parseBlock(false); case 98 /* VarKeyword */: - case 70 /* ConstKeyword */: - // const here should always be parsed as const declaration because of check in 'isStatement' return parseVariableStatement(scanner.getStartPos(), undefined, undefined); + case 104 /* LetKeyword */: + if (isLetDeclaration()) { + return parseVariableStatement(scanner.getStartPos(), undefined, undefined); + } + break; case 83 /* FunctionKeyword */: return parseFunctionDeclaration(scanner.getStartPos(), undefined, undefined); case 69 /* ClassKeyword */: return parseClassDeclaration(scanner.getStartPos(), undefined, undefined); - case 22 /* SemicolonToken */: - return parseEmptyStatement(); case 84 /* IfKeyword */: return parseIfStatement(); case 75 /* DoKeyword */: @@ -9317,9 +10226,9 @@ var ts; case 82 /* ForKeyword */: return parseForOrForInOrForOfStatement(); case 71 /* ContinueKeyword */: - return parseBreakOrContinueStatement(190 /* ContinueStatement */); + return parseBreakOrContinueStatement(192 /* ContinueStatement */); case 66 /* BreakKeyword */: - return parseBreakOrContinueStatement(191 /* BreakStatement */); + return parseBreakOrContinueStatement(193 /* BreakStatement */); case 90 /* ReturnKeyword */: return parseReturnStatement(); case 101 /* WithKeyword */: @@ -9329,60 +10238,78 @@ var ts; case 94 /* ThrowKeyword */: return parseThrowStatement(); case 96 /* TryKeyword */: - // Include the next two for error recovery. + // Include 'catch' and 'finally' for error recovery. case 68 /* CatchKeyword */: case 81 /* FinallyKeyword */: return parseTryStatement(); case 72 /* DebuggerKeyword */: return parseDebuggerStatement(); - case 104 /* LetKeyword */: - // If let follows identifier on the same line, it is declaration parse it as variable statement - if (isLetDeclaration()) { - return parseVariableStatement(scanner.getStartPos(), undefined, undefined); + case 52 /* AtToken */: + return parseDeclaration(); + case 103 /* InterfaceKeyword */: + case 125 /* TypeKeyword */: + case 118 /* ModuleKeyword */: + case 119 /* NamespaceKeyword */: + case 115 /* DeclareKeyword */: + case 70 /* ConstKeyword */: + case 77 /* EnumKeyword */: + case 78 /* ExportKeyword */: + case 85 /* ImportKeyword */: + case 106 /* PrivateKeyword */: + case 107 /* ProtectedKeyword */: + case 108 /* PublicKeyword */: + case 109 /* StaticKeyword */: + if (isStartOfDeclaration()) { + return parseDeclaration(); } - // Else parse it like identifier - fall through - default: - // Functions and variable statements are allowed as a statement. But as per - // the grammar, they also allow modifiers. So we have to check for those - // statements that might be following modifiers. This ensures that things - // work properly when incrementally parsing as the parser will produce the - // same FunctionDeclaraiton or VariableStatement if it has the same text - // regardless of whether it is inside a block or not. - // Even though variable statements and function declarations cannot have decorators, - // we parse them here to provide better error recovery. - if (ts.isModifier(token) || token === 52 /* AtToken */) { - var result = tryParse(parseVariableStatementOrFunctionDeclarationOrClassDeclarationWithDecoratorsOrModifiers); - if (result) { - return result; - } - } - return parseExpressionOrLabeledStatement(); + break; } + return parseExpressionOrLabeledStatement(); } - function parseVariableStatementOrFunctionDeclarationOrClassDeclarationWithDecoratorsOrModifiers() { - var start = scanner.getStartPos(); + function parseDeclaration() { + var fullStart = getNodePos(); var decorators = parseDecorators(); var modifiers = parseModifiers(); switch (token) { - case 70 /* ConstKeyword */: - var nextTokenIsEnum = lookAhead(nextTokenIsEnumKeyword); - if (nextTokenIsEnum) { - return undefined; - } - return parseVariableStatement(start, decorators, modifiers); - case 104 /* LetKeyword */: - if (!isLetDeclaration()) { - return undefined; - } - return parseVariableStatement(start, decorators, modifiers); case 98 /* VarKeyword */: - return parseVariableStatement(start, decorators, modifiers); + case 104 /* LetKeyword */: + case 70 /* ConstKeyword */: + return parseVariableStatement(fullStart, decorators, modifiers); case 83 /* FunctionKeyword */: - return parseFunctionDeclaration(start, decorators, modifiers); + return parseFunctionDeclaration(fullStart, decorators, modifiers); case 69 /* ClassKeyword */: - return parseClassDeclaration(start, decorators, modifiers); + return parseClassDeclaration(fullStart, decorators, modifiers); + case 103 /* InterfaceKeyword */: + return parseInterfaceDeclaration(fullStart, decorators, modifiers); + case 125 /* TypeKeyword */: + return parseTypeAliasDeclaration(fullStart, decorators, modifiers); + case 77 /* EnumKeyword */: + return parseEnumDeclaration(fullStart, decorators, modifiers); + case 118 /* ModuleKeyword */: + case 119 /* NamespaceKeyword */: + return parseModuleDeclaration(fullStart, decorators, modifiers); + case 85 /* ImportKeyword */: + return parseImportDeclarationOrImportEqualsDeclaration(fullStart, decorators, modifiers); + case 78 /* ExportKeyword */: + nextToken(); + return token === 73 /* DefaultKeyword */ || token === 53 /* EqualsToken */ ? + parseExportAssignment(fullStart, decorators, modifiers) : + 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(221 /* MissingDeclaration */, true, ts.Diagnostics.Declaration_expected); + node.pos = fullStart; + node.decorators = decorators; + setModifiers(node, modifiers); + return finishNode(node); + } } - return undefined; + } + function nextTokenIsIdentifierOrStringLiteralOnSameLine() { + nextToken(); + return !scanner.hasPrecedingLineBreak() && (isIdentifier() || token === 8 /* StringLiteral */); } function parseFunctionBlockOrSemicolon(isGenerator, diagnosticMessage) { if (token !== 14 /* OpenBraceToken */ && canParseSemicolon()) { @@ -9394,16 +10321,16 @@ var ts; // DECLARATIONS function parseArrayBindingElement() { if (token === 23 /* CommaToken */) { - return createNode(176 /* OmittedExpression */); + return createNode(178 /* OmittedExpression */); } - var node = createNode(153 /* BindingElement */); + var node = createNode(155 /* BindingElement */); node.dotDotDotToken = parseOptionalToken(21 /* DotDotDotToken */); node.name = parseIdentifierOrPattern(); node.initializer = parseInitializer(false); return finishNode(node); } function parseObjectBindingElement() { - var node = createNode(153 /* BindingElement */); + var node = createNode(155 /* BindingElement */); // TODO(andersh): Handle computed properties var tokenIsIdentifier = isIdentifier(); var propertyName = parsePropertyName(); @@ -9419,16 +10346,16 @@ var ts; return finishNode(node); } function parseObjectBindingPattern() { - var node = createNode(151 /* ObjectBindingPattern */); + var node = createNode(153 /* ObjectBindingPattern */); parseExpected(14 /* OpenBraceToken */); - node.elements = parseDelimitedList(10 /* ObjectBindingElements */, parseObjectBindingElement); + node.elements = parseDelimitedList(9 /* ObjectBindingElements */, parseObjectBindingElement); parseExpected(15 /* CloseBraceToken */); return finishNode(node); } function parseArrayBindingPattern() { - var node = createNode(152 /* ArrayBindingPattern */); + var node = createNode(154 /* ArrayBindingPattern */); parseExpected(18 /* OpenBracketToken */); - node.elements = parseDelimitedList(11 /* ArrayBindingElements */, parseArrayBindingElement); + node.elements = parseDelimitedList(10 /* ArrayBindingElements */, parseArrayBindingElement); parseExpected(19 /* CloseBracketToken */); return finishNode(node); } @@ -9445,7 +10372,7 @@ var ts; return parseIdentifier(); } function parseVariableDeclaration() { - var node = createNode(199 /* VariableDeclaration */); + var node = createNode(201 /* VariableDeclaration */); node.name = parseIdentifierOrPattern(); node.type = parseTypeAnnotation(); if (!isInOrOfKeyword(token)) { @@ -9454,7 +10381,7 @@ var ts; return finishNode(node); } function parseVariableDeclarationList(inForStatementInitializer) { - var node = createNode(200 /* VariableDeclarationList */); + var node = createNode(202 /* VariableDeclarationList */); switch (token) { case 98 /* VarKeyword */: break; @@ -9477,13 +10404,13 @@ var ts; // 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 === 126 /* OfKeyword */ && lookAhead(canFollowContextualOfKeyword)) { + if (token === 127 /* OfKeyword */ && lookAhead(canFollowContextualOfKeyword)) { node.declarations = createMissingList(); } else { var savedDisallowIn = inDisallowInContext(); setDisallowInContext(inForStatementInitializer); - node.declarations = parseDelimitedList(9 /* VariableDeclarations */, parseVariableDeclaration); + node.declarations = parseDelimitedList(8 /* VariableDeclarations */, parseVariableDeclaration); setDisallowInContext(savedDisallowIn); } return finishNode(node); @@ -9492,7 +10419,7 @@ var ts; return nextTokenIsIdentifier() && nextToken() === 17 /* CloseParenToken */; } function parseVariableStatement(fullStart, decorators, modifiers) { - var node = createNode(181 /* VariableStatement */, fullStart); + var node = createNode(183 /* VariableStatement */, fullStart); node.decorators = decorators; setModifiers(node, modifiers); node.declarationList = parseVariableDeclarationList(false); @@ -9500,7 +10427,7 @@ var ts; return finishNode(node); } function parseFunctionDeclaration(fullStart, decorators, modifiers) { - var node = createNode(201 /* FunctionDeclaration */, fullStart); + var node = createNode(203 /* FunctionDeclaration */, fullStart); node.decorators = decorators; setModifiers(node, modifiers); parseExpected(83 /* FunctionKeyword */); @@ -9511,7 +10438,7 @@ var ts; return finishNode(node); } function parseConstructorDeclaration(pos, decorators, modifiers) { - var node = createNode(136 /* Constructor */, pos); + var node = createNode(137 /* Constructor */, pos); node.decorators = decorators; setModifiers(node, modifiers); parseExpected(114 /* ConstructorKeyword */); @@ -9520,7 +10447,7 @@ var ts; return finishNode(node); } function parseMethodDeclaration(fullStart, decorators, modifiers, asteriskToken, name, questionToken, diagnosticMessage) { - var method = createNode(135 /* MethodDeclaration */, fullStart); + var method = createNode(136 /* MethodDeclaration */, fullStart); method.decorators = decorators; setModifiers(method, modifiers); method.asteriskToken = asteriskToken; @@ -9531,13 +10458,24 @@ var ts; return finishNode(method); } function parsePropertyDeclaration(fullStart, decorators, modifiers, name, questionToken) { - var property = createNode(133 /* PropertyDeclaration */, fullStart); + var property = createNode(134 /* PropertyDeclaration */, fullStart); property.decorators = decorators; setModifiers(property, modifiers); property.name = name; property.questionToken = questionToken; property.type = parseTypeAnnotation(); - property.initializer = allowInAnd(parseNonParameterInitializer); + // 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 Initialiser_opt[In]; + // AccessibilityModifier_opt static_opt PropertyName TypeAnnotation_opt Initialiser_opt[In, ?Yield]; + // + // The checker may still error in the static case to explicitly disallow the yield expression. + property.initializer = modifiers && modifiers.flags & 128 /* Static */ + ? allowInAnd(parseNonParameterInitializer) + : doOutsideOfContext(4 /* Yield */ | 2 /* DisallowIn */, parseNonParameterInitializer); parseSemicolon(); return finishNode(property); } @@ -9612,7 +10550,7 @@ var ts; // 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 === 121 /* SetKeyword */ || idToken === 116 /* GetKeyword */) { + if (!ts.isKeyword(idToken) || idToken === 122 /* SetKeyword */ || idToken === 116 /* GetKeyword */) { return true; } // If it *is* a keyword, but not an accessor, check a little farther along @@ -9646,7 +10584,7 @@ var ts; decorators = []; decorators.pos = scanner.getStartPos(); } - var decorator = createNode(131 /* Decorator */, decoratorStart); + var decorator = createNode(132 /* Decorator */, decoratorStart); decorator.expression = doInDecoratorContext(parseLeftHandSideExpressionOrHigher); decorators.push(finishNode(decorator)); } @@ -9679,7 +10617,7 @@ var ts; } function parseClassElement() { if (token === 22 /* SemicolonToken */) { - var result = createNode(179 /* SemicolonClassElement */); + var result = createNode(181 /* SemicolonClassElement */); nextToken(); return finishNode(result); } @@ -9705,27 +10643,24 @@ var ts; token === 18 /* OpenBracketToken */) { return parsePropertyOrMethodDeclaration(fullStart, decorators, modifiers); } - if (decorators) { + if (decorators || modifiers) { // treat this as a property declaration with a missing name. - var name_3 = createMissingNode(65 /* Identifier */, true, ts.Diagnostics.Declaration_expected); - return parsePropertyDeclaration(fullStart, decorators, modifiers, name_3, undefined); + var name_6 = createMissingNode(65 /* Identifier */, true, ts.Diagnostics.Declaration_expected); + return parsePropertyDeclaration(fullStart, decorators, modifiers, name_6, 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, 175 /* ClassExpression */); + /*fullStart*/ scanner.getStartPos(), + /*decorators*/ undefined, + /*modifiers*/ undefined, 177 /* ClassExpression */); } function parseClassDeclaration(fullStart, decorators, modifiers) { - return parseClassDeclarationOrExpression(fullStart, decorators, modifiers, 202 /* ClassDeclaration */); + return parseClassDeclarationOrExpression(fullStart, decorators, modifiers, 204 /* ClassDeclaration */); } function parseClassDeclarationOrExpression(fullStart, decorators, modifiers, kind) { - // In ES6 specification, All parts of a ClassDeclaration or a ClassExpression are strict mode code - var savedStrictModeContext = inStrictModeContext(); - setStrictModeContext(true); var node = createNode(kind, fullStart); node.decorators = decorators; setModifiers(node, modifiers); @@ -9745,9 +10680,7 @@ var ts; else { node.members = createMissingList(); } - var finishedNode = finishNode(node); - setStrictModeContext(savedStrictModeContext); - return finishedNode; + return finishNode(node); } function parseHeritageClauses(isClassHeritageClause) { // ClassTail[Yield,GeneratorParameter] : See 14.5 @@ -9761,23 +10694,23 @@ var ts; return undefined; } function parseHeritageClausesWorker() { - return parseList(19 /* HeritageClauses */, false, parseHeritageClause); + return parseList(18 /* HeritageClauses */, parseHeritageClause); } function parseHeritageClause() { if (token === 79 /* ExtendsKeyword */ || token === 102 /* ImplementsKeyword */) { - var node = createNode(223 /* HeritageClause */); + var node = createNode(225 /* HeritageClause */); node.token = token; nextToken(); - node.types = parseDelimitedList(8 /* HeritageClauseElement */, parseExpressionWithTypeArguments); + node.types = parseDelimitedList(7 /* HeritageClauseElement */, parseExpressionWithTypeArguments); return finishNode(node); } return undefined; } function parseExpressionWithTypeArguments() { - var node = createNode(177 /* ExpressionWithTypeArguments */); + var node = createNode(179 /* ExpressionWithTypeArguments */); node.expression = parseLeftHandSideExpressionOrHigher(); if (token === 24 /* LessThanToken */) { - node.typeArguments = parseBracketedList(17 /* TypeArguments */, parseType, 24 /* LessThanToken */, 25 /* GreaterThanToken */); + node.typeArguments = parseBracketedList(16 /* TypeArguments */, parseType, 24 /* LessThanToken */, 25 /* GreaterThanToken */); } return finishNode(node); } @@ -9785,10 +10718,10 @@ var ts; return token === 79 /* ExtendsKeyword */ || token === 102 /* ImplementsKeyword */; } function parseClassMembers() { - return parseList(6 /* ClassMembers */, false, parseClassElement); + return parseList(5 /* ClassMembers */, parseClassElement); } function parseInterfaceDeclaration(fullStart, decorators, modifiers) { - var node = createNode(203 /* InterfaceDeclaration */, fullStart); + var node = createNode(205 /* InterfaceDeclaration */, fullStart); node.decorators = decorators; setModifiers(node, modifiers); parseExpected(103 /* InterfaceKeyword */); @@ -9799,11 +10732,12 @@ var ts; return finishNode(node); } function parseTypeAliasDeclaration(fullStart, decorators, modifiers) { - var node = createNode(204 /* TypeAliasDeclaration */, fullStart); + var node = createNode(206 /* TypeAliasDeclaration */, fullStart); node.decorators = decorators; setModifiers(node, modifiers); - parseExpected(124 /* TypeKeyword */); + parseExpected(125 /* TypeKeyword */); node.name = parseIdentifier(); + node.typeParameters = parseTypeParameters(); parseExpected(53 /* EqualsToken */); node.type = parseType(); parseSemicolon(); @@ -9814,19 +10748,19 @@ var ts; // ConstantEnumMemberSection, which starts at the beginning of an enum declaration // or any time an integer literal initializer is encountered. function parseEnumMember() { - var node = createNode(227 /* EnumMember */, scanner.getStartPos()); + var node = createNode(229 /* EnumMember */, scanner.getStartPos()); node.name = parsePropertyName(); node.initializer = allowInAnd(parseNonParameterInitializer); return finishNode(node); } function parseEnumDeclaration(fullStart, decorators, modifiers) { - var node = createNode(205 /* EnumDeclaration */, fullStart); + var node = createNode(207 /* EnumDeclaration */, fullStart); node.decorators = decorators; setModifiers(node, modifiers); parseExpected(77 /* EnumKeyword */); node.name = parseIdentifier(); if (parseExpected(14 /* OpenBraceToken */)) { - node.members = parseDelimitedList(7 /* EnumMembers */, parseEnumMember); + node.members = parseDelimitedList(6 /* EnumMembers */, parseEnumMember); parseExpected(15 /* CloseBraceToken */); } else { @@ -9835,9 +10769,9 @@ var ts; return finishNode(node); } function parseModuleBlock() { - var node = createNode(207 /* ModuleBlock */, scanner.getStartPos()); + var node = createNode(209 /* ModuleBlock */, scanner.getStartPos()); if (parseExpected(14 /* OpenBraceToken */)) { - node.statements = parseList(1 /* ModuleElements */, false, parseModuleElement); + node.statements = parseList(1 /* BlockStatements */, parseStatement); parseExpected(15 /* CloseBraceToken */); } else { @@ -9846,7 +10780,7 @@ var ts; return finishNode(node); } function parseModuleOrNamespaceDeclaration(fullStart, decorators, modifiers, flags) { - var node = createNode(206 /* ModuleDeclaration */, fullStart); + var node = createNode(208 /* ModuleDeclaration */, fullStart); node.decorators = decorators; setModifiers(node, modifiers); node.flags |= flags; @@ -9857,7 +10791,7 @@ var ts; return finishNode(node); } function parseAmbientExternalModuleDeclaration(fullStart, decorators, modifiers) { - var node = createNode(206 /* ModuleDeclaration */, fullStart); + var node = createNode(208 /* ModuleDeclaration */, fullStart); node.decorators = decorators; setModifiers(node, modifiers); node.name = parseLiteralNode(true); @@ -9866,11 +10800,11 @@ var ts; } function parseModuleDeclaration(fullStart, decorators, modifiers) { var flags = modifiers ? modifiers.flags : 0; - if (parseOptional(118 /* NamespaceKeyword */)) { + if (parseOptional(119 /* NamespaceKeyword */)) { flags |= 32768 /* Namespace */; } else { - parseExpected(117 /* ModuleKeyword */); + parseExpected(118 /* ModuleKeyword */); if (token === 8 /* StringLiteral */) { return parseAmbientExternalModuleDeclaration(fullStart, decorators, modifiers); } @@ -9878,7 +10812,7 @@ var ts; return parseModuleOrNamespaceDeclaration(fullStart, decorators, modifiers, flags); } function isExternalModuleReference() { - return token === 119 /* RequireKeyword */ && + return token === 120 /* RequireKeyword */ && lookAhead(nextTokenIsOpenParen); } function nextTokenIsOpenParen() { @@ -9887,7 +10821,7 @@ var ts; function nextTokenIsCommaOrFromKeyword() { nextToken(); return token === 23 /* CommaToken */ || - token === 125 /* FromKeyword */; + token === 126 /* FromKeyword */; } function parseImportDeclarationOrImportEqualsDeclaration(fullStart, decorators, modifiers) { parseExpected(85 /* ImportKeyword */); @@ -9895,11 +10829,11 @@ var ts; var identifier; if (isIdentifier()) { identifier = parseIdentifier(); - if (token !== 23 /* CommaToken */ && token !== 125 /* FromKeyword */) { + if (token !== 23 /* CommaToken */ && token !== 126 /* FromKeyword */) { // ImportEquals declaration of type: // import x = require("mod"); or // import x = M.x; - var importEqualsDeclaration = createNode(209 /* ImportEqualsDeclaration */, fullStart); + var importEqualsDeclaration = createNode(211 /* ImportEqualsDeclaration */, fullStart); importEqualsDeclaration.decorators = decorators; setModifiers(importEqualsDeclaration, modifiers); importEqualsDeclaration.name = identifier; @@ -9910,7 +10844,7 @@ var ts; } } // Import statement - var importDeclaration = createNode(210 /* ImportDeclaration */, fullStart); + var importDeclaration = createNode(212 /* ImportDeclaration */, fullStart); importDeclaration.decorators = decorators; setModifiers(importDeclaration, modifiers); // ImportDeclaration: @@ -9920,7 +10854,7 @@ var ts; token === 35 /* AsteriskToken */ || token === 14 /* OpenBraceToken */) { importDeclaration.importClause = parseImportClause(identifier, afterImportPos); - parseExpected(125 /* FromKeyword */); + parseExpected(126 /* FromKeyword */); } importDeclaration.moduleSpecifier = parseModuleSpecifier(); parseSemicolon(); @@ -9933,7 +10867,7 @@ var ts; // NamedImports // ImportedDefaultBinding, NameSpaceImport // ImportedDefaultBinding, NamedImports - var importClause = createNode(211 /* ImportClause */, fullStart); + var importClause = createNode(213 /* ImportClause */, fullStart); if (identifier) { // ImportedDefaultBinding: // ImportedBinding @@ -9943,7 +10877,7 @@ var ts; // parse namespace or named imports if (!importClause.name || parseOptional(23 /* CommaToken */)) { - importClause.namedBindings = token === 35 /* AsteriskToken */ ? parseNamespaceImport() : parseNamedImportsOrExports(213 /* NamedImports */); + importClause.namedBindings = token === 35 /* AsteriskToken */ ? parseNamespaceImport() : parseNamedImportsOrExports(215 /* NamedImports */); } return finishNode(importClause); } @@ -9953,8 +10887,8 @@ var ts; : parseEntityName(false); } function parseExternalModuleReference() { - var node = createNode(220 /* ExternalModuleReference */); - parseExpected(119 /* RequireKeyword */); + var node = createNode(222 /* ExternalModuleReference */); + parseExpected(120 /* RequireKeyword */); parseExpected(16 /* OpenParenToken */); node.expression = parseModuleSpecifier(); parseExpected(17 /* CloseParenToken */); @@ -9975,7 +10909,7 @@ var ts; function parseNamespaceImport() { // NameSpaceImport: // * as ImportedBinding - var namespaceImport = createNode(212 /* NamespaceImport */); + var namespaceImport = createNode(214 /* NamespaceImport */); parseExpected(35 /* AsteriskToken */); parseExpected(111 /* AsKeyword */); namespaceImport.name = parseIdentifier(); @@ -9990,14 +10924,14 @@ var ts; // ImportsList: // ImportSpecifier // ImportsList, ImportSpecifier - node.elements = parseBracketedList(20 /* ImportOrExportSpecifiers */, kind === 213 /* NamedImports */ ? parseImportSpecifier : parseExportSpecifier, 14 /* OpenBraceToken */, 15 /* CloseBraceToken */); + node.elements = parseBracketedList(19 /* ImportOrExportSpecifiers */, kind === 215 /* NamedImports */ ? parseImportSpecifier : parseExportSpecifier, 14 /* OpenBraceToken */, 15 /* CloseBraceToken */); return finishNode(node); } function parseExportSpecifier() { - return parseImportOrExportSpecifier(218 /* ExportSpecifier */); + return parseImportOrExportSpecifier(220 /* ExportSpecifier */); } function parseImportSpecifier() { - return parseImportOrExportSpecifier(214 /* ImportSpecifier */); + return parseImportOrExportSpecifier(216 /* ImportSpecifier */); } function parseImportOrExportSpecifier(kind) { var node = createNode(kind); @@ -10022,23 +10956,23 @@ var ts; else { node.name = identifierName; } - if (kind === 214 /* ImportSpecifier */ && checkIdentifierIsKeyword) { + if (kind === 216 /* 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(216 /* ExportDeclaration */, fullStart); + var node = createNode(218 /* ExportDeclaration */, fullStart); node.decorators = decorators; setModifiers(node, modifiers); if (parseOptional(35 /* AsteriskToken */)) { - parseExpected(125 /* FromKeyword */); + parseExpected(126 /* FromKeyword */); node.moduleSpecifier = parseModuleSpecifier(); } else { - node.exportClause = parseNamedImportsOrExports(217 /* NamedExports */); - if (parseOptional(125 /* FromKeyword */)) { + node.exportClause = parseNamedImportsOrExports(219 /* NamedExports */); + if (parseOptional(126 /* FromKeyword */)) { node.moduleSpecifier = parseModuleSpecifier(); } } @@ -10046,7 +10980,7 @@ var ts; return finishNode(node); } function parseExportAssignment(fullStart, decorators, modifiers) { - var node = createNode(215 /* ExportAssignment */, fullStart); + var node = createNode(217 /* ExportAssignment */, fullStart); node.decorators = decorators; setModifiers(node, modifiers); if (parseOptional(53 /* EqualsToken */)) { @@ -10059,136 +10993,6 @@ var ts; parseSemicolon(); return finishNode(node); } - function isLetDeclaration() { - // It is let declaration if in strict mode or next token is identifier\open bracket\open curly on same line. - // otherwise it needs to be treated like identifier - return inStrictModeContext() || lookAhead(nextTokenIsIdentifierOrStartOfDestructuringOnTheSameLine); - } - function isDeclarationStart(followsModifier) { - switch (token) { - case 98 /* VarKeyword */: - case 70 /* ConstKeyword */: - case 83 /* FunctionKeyword */: - return true; - case 104 /* LetKeyword */: - return isLetDeclaration(); - case 69 /* ClassKeyword */: - case 103 /* InterfaceKeyword */: - case 77 /* EnumKeyword */: - case 124 /* TypeKeyword */: - // Not true keywords so ensure an identifier follows - return lookAhead(nextTokenIsIdentifierOrKeyword); - case 85 /* ImportKeyword */: - // Not true keywords so ensure an identifier follows or is string literal or asterisk or open brace - return lookAhead(nextTokenCanFollowImportKeyword); - case 117 /* ModuleKeyword */: - case 118 /* NamespaceKeyword */: - // Not a true keyword so ensure an identifier or string literal follows - return lookAhead(nextTokenIsIdentifierOrKeywordOrStringLiteral); - case 78 /* ExportKeyword */: - // Check for export assignment or modifier on source element - return lookAhead(nextTokenCanFollowExportKeyword); - case 115 /* DeclareKeyword */: - case 108 /* PublicKeyword */: - case 106 /* PrivateKeyword */: - case 107 /* ProtectedKeyword */: - case 109 /* StaticKeyword */: - // Check for modifier on source element - return lookAhead(nextTokenIsDeclarationStart); - case 52 /* AtToken */: - // a lookahead here is too costly, and decorators are only valid on a declaration. - // We will assume we are parsing a declaration here and report an error later - return !followsModifier; - } - } - function isIdentifierOrKeyword() { - return token >= 65 /* Identifier */; - } - function nextTokenIsIdentifierOrKeyword() { - nextToken(); - return isIdentifierOrKeyword(); - } - function nextTokenIsIdentifierOrKeywordOrStringLiteral() { - nextToken(); - return isIdentifierOrKeyword() || token === 8 /* StringLiteral */; - } - function nextTokenCanFollowImportKeyword() { - nextToken(); - return isIdentifierOrKeyword() || token === 8 /* StringLiteral */ || - token === 35 /* AsteriskToken */ || token === 14 /* OpenBraceToken */; - } - function nextTokenCanFollowExportKeyword() { - nextToken(); - return token === 53 /* EqualsToken */ || token === 35 /* AsteriskToken */ || - token === 14 /* OpenBraceToken */ || token === 73 /* DefaultKeyword */ || isDeclarationStart(true); - } - function nextTokenIsDeclarationStart() { - nextToken(); - return isDeclarationStart(true); - } - function nextTokenIsAsKeyword() { - return nextToken() === 111 /* AsKeyword */; - } - function parseDeclaration() { - var fullStart = getNodePos(); - var decorators = parseDecorators(); - var modifiers = parseModifiers(); - if (token === 78 /* ExportKeyword */) { - nextToken(); - if (token === 73 /* DefaultKeyword */ || token === 53 /* EqualsToken */) { - return parseExportAssignment(fullStart, decorators, modifiers); - } - if (token === 35 /* AsteriskToken */ || token === 14 /* OpenBraceToken */) { - return parseExportDeclaration(fullStart, decorators, modifiers); - } - } - switch (token) { - case 98 /* VarKeyword */: - case 104 /* LetKeyword */: - case 70 /* ConstKeyword */: - return parseVariableStatement(fullStart, decorators, modifiers); - case 83 /* FunctionKeyword */: - return parseFunctionDeclaration(fullStart, decorators, modifiers); - case 69 /* ClassKeyword */: - return parseClassDeclaration(fullStart, decorators, modifiers); - case 103 /* InterfaceKeyword */: - return parseInterfaceDeclaration(fullStart, decorators, modifiers); - case 124 /* TypeKeyword */: - return parseTypeAliasDeclaration(fullStart, decorators, modifiers); - case 77 /* EnumKeyword */: - return parseEnumDeclaration(fullStart, decorators, modifiers); - case 117 /* ModuleKeyword */: - case 118 /* NamespaceKeyword */: - return parseModuleDeclaration(fullStart, decorators, modifiers); - case 85 /* ImportKeyword */: - return parseImportDeclarationOrImportEqualsDeclaration(fullStart, decorators, modifiers); - default: - if (decorators) { - // We reached this point because we encountered an AtToken and assumed a declaration would - // follow. For recovery and error reporting purposes, return an incomplete declaration. - var node = createMissingNode(219 /* MissingDeclaration */, true, ts.Diagnostics.Declaration_expected); - node.pos = fullStart; - node.decorators = decorators; - setModifiers(node, modifiers); - return finishNode(node); - } - ts.Debug.fail("Mismatch between isDeclarationStart and parseDeclaration"); - } - } - function isSourceElement(inErrorRecovery) { - return isDeclarationStart() || isStartOfStatement(inErrorRecovery); - } - function parseSourceElement() { - return parseSourceElementOrModuleElement(); - } - function parseModuleElement() { - return parseSourceElementOrModuleElement(); - } - function parseSourceElementOrModuleElement() { - return isDeclarationStart() - ? parseDeclaration() - : parseStatement(); - } function processReferenceComments(sourceFile) { var triviaScanner = ts.createScanner(sourceFile.languageVersion, false, sourceText); var referencedFiles = []; @@ -10216,7 +11020,7 @@ var ts; referencedFiles.push(fileReference); } if (diagnosticMessage) { - sourceFile.parseDiagnostics.push(ts.createFileDiagnostic(sourceFile, range.pos, range.end - range.pos, diagnosticMessage)); + parseDiagnostics.push(ts.createFileDiagnostic(sourceFile, range.pos, range.end - range.pos, diagnosticMessage)); } } else { @@ -10224,7 +11028,7 @@ var ts; var amdModuleNameMatchResult = amdModuleNameRegEx.exec(comment); if (amdModuleNameMatchResult) { if (amdModuleName) { - sourceFile.parseDiagnostics.push(ts.createFileDiagnostic(sourceFile, range.pos, range.end - range.pos, ts.Diagnostics.An_AMD_module_cannot_have_multiple_name_assignments)); + parseDiagnostics.push(ts.createFileDiagnostic(sourceFile, range.pos, range.end - range.pos, ts.Diagnostics.An_AMD_module_cannot_have_multiple_name_assignments)); } amdModuleName = amdModuleNameMatchResult[2]; } @@ -10244,15 +11048,15 @@ var ts; } sourceFile.referencedFiles = referencedFiles; sourceFile.amdDependencies = amdDependencies; - sourceFile.amdModuleName = amdModuleName; + sourceFile.moduleName = amdModuleName; } function setExternalModuleIndicator(sourceFile) { sourceFile.externalModuleIndicator = ts.forEach(sourceFile.statements, function (node) { return node.flags & 1 /* Export */ - || node.kind === 209 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 220 /* ExternalModuleReference */ - || node.kind === 210 /* ImportDeclaration */ - || node.kind === 215 /* ExportAssignment */ - || node.kind === 216 /* ExportDeclaration */ + || node.kind === 211 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 222 /* ExternalModuleReference */ + || node.kind === 212 /* ImportDeclaration */ + || node.kind === 217 /* ExportAssignment */ + || node.kind === 218 /* ExportDeclaration */ ? node : undefined; }); @@ -10260,27 +11064,30 @@ var ts; var ParsingContext; (function (ParsingContext) { ParsingContext[ParsingContext["SourceElements"] = 0] = "SourceElements"; - ParsingContext[ParsingContext["ModuleElements"] = 1] = "ModuleElements"; - ParsingContext[ParsingContext["BlockStatements"] = 2] = "BlockStatements"; - ParsingContext[ParsingContext["SwitchClauses"] = 3] = "SwitchClauses"; - ParsingContext[ParsingContext["SwitchClauseStatements"] = 4] = "SwitchClauseStatements"; - ParsingContext[ParsingContext["TypeMembers"] = 5] = "TypeMembers"; - ParsingContext[ParsingContext["ClassMembers"] = 6] = "ClassMembers"; - ParsingContext[ParsingContext["EnumMembers"] = 7] = "EnumMembers"; - ParsingContext[ParsingContext["HeritageClauseElement"] = 8] = "HeritageClauseElement"; - ParsingContext[ParsingContext["VariableDeclarations"] = 9] = "VariableDeclarations"; - ParsingContext[ParsingContext["ObjectBindingElements"] = 10] = "ObjectBindingElements"; - ParsingContext[ParsingContext["ArrayBindingElements"] = 11] = "ArrayBindingElements"; - ParsingContext[ParsingContext["ArgumentExpressions"] = 12] = "ArgumentExpressions"; - ParsingContext[ParsingContext["ObjectLiteralMembers"] = 13] = "ObjectLiteralMembers"; - ParsingContext[ParsingContext["ArrayLiteralMembers"] = 14] = "ArrayLiteralMembers"; - ParsingContext[ParsingContext["Parameters"] = 15] = "Parameters"; - ParsingContext[ParsingContext["TypeParameters"] = 16] = "TypeParameters"; - ParsingContext[ParsingContext["TypeArguments"] = 17] = "TypeArguments"; - ParsingContext[ParsingContext["TupleElementTypes"] = 18] = "TupleElementTypes"; - ParsingContext[ParsingContext["HeritageClauses"] = 19] = "HeritageClauses"; - ParsingContext[ParsingContext["ImportOrExportSpecifiers"] = 20] = "ImportOrExportSpecifiers"; - ParsingContext[ParsingContext["Count"] = 21] = "Count"; // Number of parsing contexts + ParsingContext[ParsingContext["BlockStatements"] = 1] = "BlockStatements"; + ParsingContext[ParsingContext["SwitchClauses"] = 2] = "SwitchClauses"; + ParsingContext[ParsingContext["SwitchClauseStatements"] = 3] = "SwitchClauseStatements"; + ParsingContext[ParsingContext["TypeMembers"] = 4] = "TypeMembers"; + ParsingContext[ParsingContext["ClassMembers"] = 5] = "ClassMembers"; + ParsingContext[ParsingContext["EnumMembers"] = 6] = "EnumMembers"; + ParsingContext[ParsingContext["HeritageClauseElement"] = 7] = "HeritageClauseElement"; + ParsingContext[ParsingContext["VariableDeclarations"] = 8] = "VariableDeclarations"; + ParsingContext[ParsingContext["ObjectBindingElements"] = 9] = "ObjectBindingElements"; + ParsingContext[ParsingContext["ArrayBindingElements"] = 10] = "ArrayBindingElements"; + ParsingContext[ParsingContext["ArgumentExpressions"] = 11] = "ArgumentExpressions"; + ParsingContext[ParsingContext["ObjectLiteralMembers"] = 12] = "ObjectLiteralMembers"; + ParsingContext[ParsingContext["ArrayLiteralMembers"] = 13] = "ArrayLiteralMembers"; + ParsingContext[ParsingContext["Parameters"] = 14] = "Parameters"; + ParsingContext[ParsingContext["TypeParameters"] = 15] = "TypeParameters"; + ParsingContext[ParsingContext["TypeArguments"] = 16] = "TypeArguments"; + ParsingContext[ParsingContext["TupleElementTypes"] = 17] = "TupleElementTypes"; + ParsingContext[ParsingContext["HeritageClauses"] = 18] = "HeritageClauses"; + ParsingContext[ParsingContext["ImportOrExportSpecifiers"] = 19] = "ImportOrExportSpecifiers"; + ParsingContext[ParsingContext["JSDocFunctionParameters"] = 20] = "JSDocFunctionParameters"; + ParsingContext[ParsingContext["JSDocTypeArguments"] = 21] = "JSDocTypeArguments"; + ParsingContext[ParsingContext["JSDocRecordMembers"] = 22] = "JSDocRecordMembers"; + ParsingContext[ParsingContext["JSDocTupleTypes"] = 23] = "JSDocTupleTypes"; + ParsingContext[ParsingContext["Count"] = 24] = "Count"; // Number of parsing contexts })(ParsingContext || (ParsingContext = {})); var Tristate; (function (Tristate) { @@ -10288,6 +11095,546 @@ var ts; Tristate[Tristate["True"] = 1] = "True"; Tristate[Tristate["Unknown"] = 2] = "Unknown"; })(Tristate || (Tristate = {})); + var JSDocParser; + (function (JSDocParser) { + function isJSDocType() { + switch (token) { + case 35 /* AsteriskToken */: + case 50 /* QuestionToken */: + case 16 /* OpenParenToken */: + case 18 /* OpenBracketToken */: + case 46 /* ExclamationToken */: + case 14 /* OpenBraceToken */: + case 83 /* FunctionKeyword */: + case 21 /* DotDotDotToken */: + case 88 /* NewKeyword */: + case 93 /* ThisKeyword */: + return true; + } + return isIdentifierOrKeyword(); + } + JSDocParser.isJSDocType = isJSDocType; + function parseJSDocTypeExpressionForTests(content, start, length) { + initializeState("file.js", content, 2 /* Latest */, undefined); + var jsDocTypeExpression = parseJSDocTypeExpression(start, length); + var diagnostics = parseDiagnostics; + clearState(); + return jsDocTypeExpression ? { jsDocTypeExpression: jsDocTypeExpression, diagnostics: diagnostics } : undefined; + } + JSDocParser.parseJSDocTypeExpressionForTests = parseJSDocTypeExpressionForTests; + // Parses out a JSDoc type expression. The starting position should be right at the open + // curly in the type expression. Returns 'undefined' if it encounters any errors while parsing. + /* @internal */ + function parseJSDocTypeExpression(start, length) { + scanner.setText(sourceText, start, length); + // Prime the first token for us to start processing. + token = nextToken(); + var result = createNode(231 /* JSDocTypeExpression */); + parseExpected(14 /* OpenBraceToken */); + result.type = parseJSDocTopLevelType(); + parseExpected(15 /* CloseBraceToken */); + fixupParentReferences(result); + return finishNode(result); + } + JSDocParser.parseJSDocTypeExpression = parseJSDocTypeExpression; + function parseJSDocTopLevelType() { + var type = parseJSDocType(); + if (token === 44 /* BarToken */) { + var unionType = createNode(235 /* JSDocUnionType */, type.pos); + unionType.types = parseJSDocTypeList(type); + type = finishNode(unionType); + } + if (token === 53 /* EqualsToken */) { + var optionalType = createNode(242 /* JSDocOptionalType */, type.pos); + nextToken(); + optionalType.type = type; + type = finishNode(optionalType); + } + return type; + } + function parseJSDocType() { + var type = parseBasicTypeExpression(); + while (true) { + if (token === 18 /* OpenBracketToken */) { + var arrayType = createNode(234 /* JSDocArrayType */, type.pos); + arrayType.elementType = type; + nextToken(); + parseExpected(19 /* CloseBracketToken */); + type = finishNode(arrayType); + } + else if (token === 50 /* QuestionToken */) { + var nullableType = createNode(237 /* JSDocNullableType */, type.pos); + nullableType.type = type; + nextToken(); + type = finishNode(nullableType); + } + else if (token === 46 /* ExclamationToken */) { + var nonNullableType = createNode(238 /* JSDocNonNullableType */, type.pos); + nonNullableType.type = type; + nextToken(); + type = finishNode(nonNullableType); + } + else { + break; + } + } + return type; + } + function parseBasicTypeExpression() { + switch (token) { + case 35 /* AsteriskToken */: + return parseJSDocAllType(); + case 50 /* QuestionToken */: + return parseJSDocUnknownOrNullableType(); + case 16 /* OpenParenToken */: + return parseJSDocUnionType(); + case 18 /* OpenBracketToken */: + return parseJSDocTupleType(); + case 46 /* ExclamationToken */: + return parseJSDocNonNullableType(); + case 14 /* OpenBraceToken */: + return parseJSDocRecordType(); + case 83 /* FunctionKeyword */: + return parseJSDocFunctionType(); + case 21 /* DotDotDotToken */: + return parseJSDocVariadicType(); + case 88 /* NewKeyword */: + return parseJSDocConstructorType(); + case 93 /* ThisKeyword */: + return parseJSDocThisType(); + case 112 /* AnyKeyword */: + case 123 /* StringKeyword */: + case 121 /* NumberKeyword */: + case 113 /* BooleanKeyword */: + case 124 /* SymbolKeyword */: + case 99 /* VoidKeyword */: + return parseTokenNode(); + } + return parseJSDocTypeReference(); + } + function parseJSDocThisType() { + var result = createNode(246 /* JSDocThisType */); + nextToken(); + parseExpected(51 /* ColonToken */); + result.type = parseJSDocType(); + return finishNode(result); + } + function parseJSDocConstructorType() { + var result = createNode(245 /* JSDocConstructorType */); + nextToken(); + parseExpected(51 /* ColonToken */); + result.type = parseJSDocType(); + return finishNode(result); + } + function parseJSDocVariadicType() { + var result = createNode(244 /* JSDocVariadicType */); + nextToken(); + result.type = parseJSDocType(); + return finishNode(result); + } + function parseJSDocFunctionType() { + var result = createNode(243 /* JSDocFunctionType */); + nextToken(); + parseExpected(16 /* OpenParenToken */); + result.parameters = parseDelimitedList(20 /* JSDocFunctionParameters */, parseJSDocParameter); + checkForTrailingComma(result.parameters); + parseExpected(17 /* CloseParenToken */); + if (token === 51 /* ColonToken */) { + nextToken(); + result.type = parseJSDocType(); + } + return finishNode(result); + } + function parseJSDocParameter() { + var parameter = createNode(131 /* Parameter */); + parameter.type = parseJSDocType(); + return finishNode(parameter); + } + function parseJSDocOptionalType(type) { + var result = createNode(242 /* JSDocOptionalType */, type.pos); + nextToken(); + result.type = type; + return finishNode(result); + } + function parseJSDocTypeReference() { + var result = createNode(241 /* JSDocTypeReference */); + result.name = parseSimplePropertyName(); + while (parseOptional(20 /* DotToken */)) { + if (token === 24 /* LessThanToken */) { + result.typeArguments = parseTypeArguments(); + break; + } + else { + result.name = parseQualifiedName(result.name); + } + } + return finishNode(result); + } + function parseTypeArguments() { + // Move past the < + nextToken(); + var typeArguments = parseDelimitedList(21 /* JSDocTypeArguments */, parseJSDocType); + checkForTrailingComma(typeArguments); + checkForEmptyTypeArgumentList(typeArguments); + parseExpected(25 /* GreaterThanToken */); + return typeArguments; + } + function checkForEmptyTypeArgumentList(typeArguments) { + if (parseDiagnostics.length === 0 && typeArguments && typeArguments.length === 0) { + var start = typeArguments.pos - "<".length; + var end = ts.skipTrivia(sourceText, typeArguments.end) + ">".length; + return parseErrorAtPosition(start, end - start, ts.Diagnostics.Type_argument_list_cannot_be_empty); + } + } + function parseQualifiedName(left) { + var result = createNode(128 /* QualifiedName */, left.pos); + result.left = left; + result.right = parseIdentifierName(); + return finishNode(result); + } + function parseJSDocRecordType() { + var result = createNode(239 /* JSDocRecordType */); + nextToken(); + result.members = parseDelimitedList(22 /* JSDocRecordMembers */, parseJSDocRecordMember); + checkForTrailingComma(result.members); + parseExpected(15 /* CloseBraceToken */); + return finishNode(result); + } + function parseJSDocRecordMember() { + var result = createNode(240 /* JSDocRecordMember */); + result.name = parseSimplePropertyName(); + if (token === 51 /* ColonToken */) { + nextToken(); + result.type = parseJSDocType(); + } + return finishNode(result); + } + function parseJSDocNonNullableType() { + var result = createNode(238 /* JSDocNonNullableType */); + nextToken(); + result.type = parseJSDocType(); + return finishNode(result); + } + function parseJSDocTupleType() { + var result = createNode(236 /* JSDocTupleType */); + nextToken(); + result.types = parseDelimitedList(23 /* JSDocTupleTypes */, parseJSDocType); + checkForTrailingComma(result.types); + parseExpected(19 /* 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(235 /* JSDocUnionType */); + nextToken(); + result.types = parseJSDocTypeList(parseJSDocType()); + parseExpected(17 /* CloseParenToken */); + return finishNode(result); + } + function parseJSDocTypeList(firstType) { + ts.Debug.assert(!!firstType); + var types = []; + types.pos = firstType.pos; + types.push(firstType); + while (parseOptional(44 /* BarToken */)) { + types.push(parseJSDocType()); + } + types.end = scanner.getStartPos(); + return types; + } + function parseJSDocAllType() { + var result = createNode(232 /* 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 === 23 /* CommaToken */ || + token === 15 /* CloseBraceToken */ || + token === 17 /* CloseParenToken */ || + token === 25 /* GreaterThanToken */ || + token === 53 /* EqualsToken */ || + token === 44 /* BarToken */) { + var result = createNode(233 /* JSDocUnknownType */, pos); + return finishNode(result); + } + else { + var result = createNode(237 /* JSDocNullableType */, pos); + result.type = parseJSDocType(); + return finishNode(result); + } + } + function parseIsolatedJSDocComment(content, start, length) { + initializeState("file.js", content, 2 /* Latest */, undefined); + var jsDocComment = parseJSDocComment(undefined, start, length); + var diagnostics = parseDiagnostics; + clearState(); + return jsDocComment ? { jsDocComment: jsDocComment, diagnostics: diagnostics } : undefined; + } + JSDocParser.parseIsolatedJSDocComment = parseIsolatedJSDocComment; + function parseJSDocComment(parent, start, length) { + var comment = parseJSDocCommentWorker(start, length); + if (comment) { + fixupParentReferences(comment); + comment.parent = parent; + } + return comment; + } + JSDocParser.parseJSDocComment = parseJSDocComment; + 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 pos; + // NOTE(cyrusn): This is essentially a handwritten scanner for JSDocComments. I + // considered using an actual Scanner, but this would complicate things. The + // scanner would need to know it was in a Doc Comment. Otherwise, it would then + // produce comments *inside* the doc comment. In the end it was just easier to + // write a simple scanner rather than go that route. + if (length >= "/** */".length) { + if (content.charCodeAt(start) === 47 /* slash */ && + content.charCodeAt(start + 1) === 42 /* asterisk */ && + content.charCodeAt(start + 2) === 42 /* asterisk */ && + content.charCodeAt(start + 3) !== 42 /* asterisk */) { + // Initially we can parse out a tag. We also have seen a starting asterisk. + // This is so that /** * @type */ doesn't parse. + var canParseTag = true; + var seenAsterisk = true; + for (pos = start + "/**".length; pos < end;) { + var ch = content.charCodeAt(pos); + pos++; + if (ch === 64 /* at */ && canParseTag) { + parseTag(); + // Once we parse out a tag, we cannot keep parsing out tags on this line. + canParseTag = false; + continue; + } + if (ts.isLineBreak(ch)) { + // After a line break, we can parse a tag, and we haven't seen as asterisk + // on the next line yet. + canParseTag = true; + seenAsterisk = false; + continue; + } + if (ts.isWhiteSpace(ch)) { + // Whitespace doesn't affect any of our parsing. + continue; + } + // Ignore the first asterisk on a line. + if (ch === 42 /* asterisk */) { + if (seenAsterisk) { + // If we've already seen an asterisk, then we can no longer parse a tag + // on this line. + canParseTag = false; + } + seenAsterisk = true; + continue; + } + // Anything else is doc comment text. We can't do anything with it. Because it + // wasn't a tag, we can no longer parse a tag on this line until we hit the next + // line break. + canParseTag = false; + } + } + } + return createJSDocComment(); + function createJSDocComment() { + if (!tags) { + return undefined; + } + var result = createNode(247 /* JSDocComment */, start); + result.tags = tags; + return finishNode(result, end); + } + function skipWhitespace() { + while (pos < end && ts.isWhiteSpace(content.charCodeAt(pos))) { + pos++; + } + } + function parseTag() { + ts.Debug.assert(content.charCodeAt(pos - 1) === 64 /* at */); + var atToken = createNode(52 /* AtToken */, pos - 1); + atToken.end = pos; + var startPos = pos; + var tagName = scanIdentifier(); + if (!tagName) { + return; + } + var tag = handleTag(atToken, tagName) || handleUnknownTag(atToken, tagName); + addTag(tag); + } + function handleTag(atToken, tagName) { + if (tagName) { + switch (tagName.text) { + case "param": + return handleParamTag(atToken, tagName); + case "return": + case "returns": + return handleReturnTag(atToken, tagName); + case "template": + return handleTemplateTag(atToken, tagName); + case "type": + return handleTypeTag(atToken, tagName); + } + } + return undefined; + } + function handleUnknownTag(atToken, tagName) { + var result = createNode(248 /* JSDocTag */, atToken.pos); + result.atToken = atToken; + result.tagName = tagName; + return finishNode(result, pos); + } + function addTag(tag) { + if (tag) { + if (!tags) { + tags = []; + tags.pos = tag.pos; + } + tags.push(tag); + tags.end = tag.end; + } + } + function tryParseTypeExpression() { + skipWhitespace(); + if (content.charCodeAt(pos) !== 123 /* openBrace */) { + return undefined; + } + var typeExpression = parseJSDocTypeExpression(pos, end - pos); + pos = typeExpression.end; + return typeExpression; + } + function handleParamTag(atToken, tagName) { + var typeExpression = tryParseTypeExpression(); + skipWhitespace(); + var name; + var isBracketed; + if (content.charCodeAt(pos) === 91 /* openBracket */) { + pos++; + skipWhitespace(); + name = scanIdentifier(); + isBracketed = true; + } + else { + name = scanIdentifier(); + } + if (!name) { + parseErrorAtPosition(pos, 0, ts.Diagnostics.Identifier_expected); + return undefined; + } + var preName, postName; + if (typeExpression) { + postName = name; + } + else { + preName = name; + } + if (!typeExpression) { + typeExpression = tryParseTypeExpression(); + } + var result = createNode(249 /* JSDocParameterTag */, atToken.pos); + result.atToken = atToken; + result.tagName = tagName; + result.preParameterName = preName; + result.typeExpression = typeExpression; + result.postParameterName = postName; + result.isBracketed = isBracketed; + return finishNode(result, pos); + } + function handleReturnTag(atToken, tagName) { + if (ts.forEach(tags, function (t) { return t.kind === 250 /* JSDocReturnTag */; })) { + parseErrorAtPosition(tagName.pos, pos - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.text); + } + var result = createNode(250 /* JSDocReturnTag */, atToken.pos); + result.atToken = atToken; + result.tagName = tagName; + result.typeExpression = tryParseTypeExpression(); + return finishNode(result, pos); + } + function handleTypeTag(atToken, tagName) { + if (ts.forEach(tags, function (t) { return t.kind === 251 /* JSDocTypeTag */; })) { + parseErrorAtPosition(tagName.pos, pos - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.text); + } + var result = createNode(251 /* JSDocTypeTag */, atToken.pos); + result.atToken = atToken; + result.tagName = tagName; + result.typeExpression = tryParseTypeExpression(); + return finishNode(result, pos); + } + function handleTemplateTag(atToken, tagName) { + if (ts.forEach(tags, function (t) { return t.kind === 252 /* JSDocTemplateTag */; })) { + parseErrorAtPosition(tagName.pos, pos - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.text); + } + var typeParameters = []; + typeParameters.pos = pos; + while (true) { + skipWhitespace(); + var startPos = pos; + var name_7 = scanIdentifier(); + if (!name_7) { + parseErrorAtPosition(startPos, 0, ts.Diagnostics.Identifier_expected); + return undefined; + } + var typeParameter = createNode(130 /* TypeParameter */, name_7.pos); + typeParameter.name = name_7; + finishNode(typeParameter, pos); + typeParameters.push(typeParameter); + skipWhitespace(); + if (content.charCodeAt(pos) !== 44 /* comma */) { + break; + } + pos++; + } + typeParameters.end = pos; + var result = createNode(252 /* JSDocTemplateTag */, atToken.pos); + result.atToken = atToken; + result.tagName = tagName; + result.typeParameters = typeParameters; + return finishNode(result, pos); + } + function scanIdentifier() { + var startPos = pos; + for (; pos < end; pos++) { + var ch = content.charCodeAt(pos); + if (pos === startPos && ts.isIdentifierStart(ch, 2 /* Latest */)) { + continue; + } + else if (pos > startPos && ts.isIdentifierPart(ch, 2 /* Latest */)) { + continue; + } + break; + } + if (startPos === pos) { + return undefined; + } + var result = createNode(65 /* Identifier */, startPos); + result.text = content.substring(startPos, pos); + return finishNode(result, pos); + } + } + JSDocParser.parseJSDocCommentWorker = parseJSDocCommentWorker; + })(JSDocParser = Parser.JSDocParser || (Parser.JSDocParser = {})); })(Parser || (Parser = {})); var IncrementalParser; (function (IncrementalParser) { @@ -10375,7 +11722,12 @@ var ts; } // Ditch any existing LS children we may have created. This way we can avoid // moving them forward. - node._children = undefined; + if (node._children) { + node._children = undefined; + } + if (node.jsDocComment) { + node.jsDocComment = undefined; + } node.pos += delta; node.end += delta; if (aggressiveChecks && shouldCheckNode(node)) { @@ -10830,18 +12182,20 @@ var ts; var stringType = createIntrinsicType(2 /* String */, "string"); var numberType = createIntrinsicType(4 /* Number */, "number"); var booleanType = createIntrinsicType(8 /* Boolean */, "boolean"); - var esSymbolType = createIntrinsicType(1048576 /* ESSymbol */, "symbol"); + var esSymbolType = createIntrinsicType(2097152 /* ESSymbol */, "symbol"); var voidType = createIntrinsicType(16 /* Void */, "void"); - var undefinedType = createIntrinsicType(32 /* Undefined */ | 262144 /* ContainsUndefinedOrNull */, "undefined"); - var nullType = createIntrinsicType(64 /* Null */ | 262144 /* ContainsUndefinedOrNull */, "null"); + var undefinedType = createIntrinsicType(32 /* Undefined */ | 524288 /* ContainsUndefinedOrNull */, "undefined"); + var nullType = createIntrinsicType(64 /* Null */ | 524288 /* ContainsUndefinedOrNull */, "null"); var unknownType = createIntrinsicType(1 /* Any */, "unknown"); + var circularType = createIntrinsicType(1 /* Any */, "__circular__"); var emptyObjectType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); + var emptyGenericType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); + emptyGenericType.instantiations = {}; var anyFunctionType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); var noConstraintType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); - var anySignature = createSignature(undefined, undefined, emptyArray, anyType, 0, false, false); - var unknownSignature = createSignature(undefined, undefined, emptyArray, unknownType, 0, false, false); + var anySignature = createSignature(undefined, undefined, emptyArray, anyType, undefined, 0, false, false); + var unknownSignature = createSignature(undefined, undefined, emptyArray, unknownType, undefined, 0, false, false); var globals = {}; - var globalArraySymbol; var globalESSymbolConstructorSymbol; var globalObjectType; var globalFunctionType; @@ -10853,6 +12207,8 @@ var ts; var globalTemplateStringsArrayType; var globalESSymbolType; var globalIterableType; + var globalIteratorType; + var globalIterableIteratorType; var anyArrayType; var getGlobalClassDecoratorType; var getGlobalParameterDecoratorType; @@ -10886,9 +12242,14 @@ var ts; }, "symbol": { type: esSymbolType, - flags: 1048576 /* ESSymbol */ + flags: 2097152 /* ESSymbol */ } }; + var subtypeRelation = {}; + var assignableRelation = {}; + var identityRelation = {}; + initializeTypeChecker(); + return checker; function getEmitResolver(sourceFile) { // 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. @@ -11031,10 +12392,10 @@ var ts; return nodeLinks[nodeId] || (nodeLinks[nodeId] = {}); } function getSourceFile(node) { - return ts.getAncestor(node, 228 /* SourceFile */); + return ts.getAncestor(node, 230 /* SourceFile */); } function isGlobalSourceFile(node) { - return node.kind === 228 /* SourceFile */ && !ts.isExternalModule(node); + return node.kind === 230 /* SourceFile */ && !ts.isExternalModule(node); } function getSymbol(symbols, name, meaning) { if (meaning && ts.hasProperty(symbols, name)) { @@ -11079,44 +12440,66 @@ var ts; // Locals of a source file are not in scope (because they get merged into the global symbol table) if (location.locals && !isGlobalSourceFile(location)) { if (result = getSymbol(location.locals, name, meaning)) { - break loop; + // 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. + if (!(meaning & 793056 /* Type */) || + !(result.flags & (793056 /* Type */ & ~262144 /* TypeParameter */)) || + !ts.isFunctionLike(location) || + lastLocation === location.body) { + break loop; + } + result = undefined; } } switch (location.kind) { - case 228 /* SourceFile */: + case 230 /* SourceFile */: if (!ts.isExternalModule(location)) break; - case 206 /* ModuleDeclaration */: - if (result = getSymbol(getSymbolOfNode(location).exports, name, meaning & 8914931 /* ModuleMember */)) { - if (result.flags & meaning || !(result.flags & 8388608 /* Alias */ && getDeclarationOfAliasSymbol(result).kind === 218 /* ExportSpecifier */)) { - break loop; + case 208 /* ModuleDeclaration */: + var moduleExports = getSymbolOfNode(location).exports; + if (location.kind === 230 /* SourceFile */ || + (location.kind === 208 /* ModuleDeclaration */ && location.name.kind === 8 /* StringLiteral */)) { + // It's an external module. 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. + if (ts.hasProperty(moduleExports, name) && + moduleExports[name].flags === 8388608 /* Alias */ && + ts.getDeclarationOfKind(moduleExports[name], 220 /* ExportSpecifier */)) { + break; } - result = undefined; - } - else if (location.kind === 228 /* SourceFile */ || - (location.kind === 206 /* ModuleDeclaration */ && location.name.kind === 8 /* StringLiteral */)) { - result = getSymbolOfNode(location).exports["default"]; + result = moduleExports["default"]; var localSymbol = ts.getLocalSymbolForExportDefault(result); if (result && localSymbol && (result.flags & meaning) && localSymbol.name === name) { break loop; } result = undefined; } + if (result = getSymbol(moduleExports, name, meaning & 8914931 /* ModuleMember */)) { + break loop; + } break; - case 205 /* EnumDeclaration */: + case 207 /* EnumDeclaration */: if (result = getSymbol(getSymbolOfNode(location).exports, name, meaning & 8 /* EnumMember */)) { break loop; } break; - case 133 /* PropertyDeclaration */: - case 132 /* PropertySignature */: + case 134 /* PropertyDeclaration */: + case 133 /* 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 (location.parent.kind === 202 /* ClassDeclaration */ && !(location.flags & 128 /* Static */)) { + if (location.parent.kind === 204 /* ClassDeclaration */ && !(location.flags & 128 /* Static */)) { var ctor = findConstructorDeclaration(location.parent); if (ctor && ctor.locals) { if (getSymbol(ctor.locals, name, meaning & 107455 /* Value */)) { @@ -11126,8 +12509,8 @@ var ts; } } break; - case 202 /* ClassDeclaration */: - case 203 /* InterfaceDeclaration */: + case 204 /* ClassDeclaration */: + case 205 /* InterfaceDeclaration */: if (result = getSymbol(getSymbolOfNode(location).members, name, meaning & 793056 /* Type */)) { if (lastLocation && lastLocation.flags & 128 /* Static */) { // TypeScript 1.0 spec (April 2014): 3.4.1 @@ -11147,9 +12530,9 @@ var ts; // [foo()]() { } // <-- Reference to T from class's own computed property // } // - case 128 /* ComputedPropertyName */: + case 129 /* ComputedPropertyName */: grandparent = location.parent.parent; - if (grandparent.kind === 202 /* ClassDeclaration */ || grandparent.kind === 203 /* InterfaceDeclaration */) { + if (grandparent.kind === 204 /* ClassDeclaration */ || grandparent.kind === 205 /* InterfaceDeclaration */) { // A reference to this grandparent's type parameters would be an error if (result = getSymbol(getSymbolOfNode(grandparent).members, name, meaning & 793056 /* Type */)) { error(errorLocation, ts.Diagnostics.A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type); @@ -11157,37 +12540,41 @@ var ts; } } break; - case 135 /* MethodDeclaration */: - case 134 /* MethodSignature */: - case 136 /* Constructor */: - case 137 /* GetAccessor */: - case 138 /* SetAccessor */: - case 201 /* FunctionDeclaration */: - case 164 /* ArrowFunction */: - if (name === "arguments") { + case 136 /* MethodDeclaration */: + case 135 /* MethodSignature */: + case 137 /* Constructor */: + case 138 /* GetAccessor */: + case 139 /* SetAccessor */: + case 203 /* FunctionDeclaration */: + case 166 /* ArrowFunction */: + if (meaning & 3 /* Variable */ && name === "arguments") { result = argumentsSymbol; break loop; } break; - case 163 /* FunctionExpression */: - if (name === "arguments") { + case 165 /* FunctionExpression */: + if (meaning & 3 /* Variable */ && name === "arguments") { result = argumentsSymbol; break loop; } - var functionName = location.name; - if (functionName && name === functionName.text) { - result = location.symbol; - break loop; + if (meaning & 16 /* Function */) { + var functionName = location.name; + if (functionName && name === functionName.text) { + result = location.symbol; + break loop; + } } break; - case 175 /* ClassExpression */: - var className = location.name; - if (className && name === className.text) { - result = location.symbol; - break loop; + case 177 /* ClassExpression */: + if (meaning & 32 /* Class */) { + var className = location.name; + if (className && name === className.text) { + result = location.symbol; + break loop; + } } break; - case 131 /* Decorator */: + case 132 /* Decorator */: // Decorators are resolved at the class declaration. Resolving at the parameter // or member would result in looking up locals in the method. // @@ -11196,7 +12583,7 @@ var ts; // method(@y x, y) {} // <-- decorator y should be resolved at the class declaration, not the parameter. // } // - if (location.parent && location.parent.kind === 130 /* Parameter */) { + if (location.parent && location.parent.kind === 131 /* Parameter */) { location = location.parent; } // @@ -11252,16 +12639,16 @@ var ts; // for (let x in x) // for (let x of x) // climb up to the variable declaration skipping binding patterns - var variableDeclaration = ts.getAncestor(declaration, 199 /* VariableDeclaration */); + var variableDeclaration = ts.getAncestor(declaration, 201 /* VariableDeclaration */); var container = ts.getEnclosingBlockScopeContainer(variableDeclaration); - if (variableDeclaration.parent.parent.kind === 181 /* VariableStatement */ || - variableDeclaration.parent.parent.kind === 187 /* ForStatement */) { + if (variableDeclaration.parent.parent.kind === 183 /* VariableStatement */ || + variableDeclaration.parent.parent.kind === 189 /* ForStatement */) { // variable statement/for statement case, // use site should not be inside variable declaration (initializer of declaration or binding element) isUsedBeforeDeclaration = isSameScopeDescendentOf(errorLocation, variableDeclaration, container); } - else if (variableDeclaration.parent.parent.kind === 189 /* ForOfStatement */ || - variableDeclaration.parent.parent.kind === 188 /* ForInStatement */) { + else if (variableDeclaration.parent.parent.kind === 191 /* ForOfStatement */ || + variableDeclaration.parent.parent.kind === 190 /* ForInStatement */) { // ForIn/ForOf case - use site should not be used in expression part var expression = variableDeclaration.parent.parent.expression; isUsedBeforeDeclaration = isSameScopeDescendentOf(errorLocation, expression, container); @@ -11288,10 +12675,10 @@ var ts; } function getAnyImportSyntax(node) { if (ts.isAliasSymbolDeclaration(node)) { - if (node.kind === 209 /* ImportEqualsDeclaration */) { + if (node.kind === 211 /* ImportEqualsDeclaration */) { return node; } - while (node && node.kind !== 210 /* ImportDeclaration */) { + while (node && node.kind !== 212 /* ImportDeclaration */) { node = node.parent; } return node; @@ -11301,7 +12688,7 @@ var ts; return ts.forEach(symbol.declarations, function (d) { return ts.isAliasSymbolDeclaration(d) ? d : undefined; }); } function getTargetOfImportEqualsDeclaration(node) { - if (node.moduleReference.kind === 220 /* ExternalModuleReference */) { + if (node.moduleReference.kind === 222 /* ExternalModuleReference */) { return resolveExternalModuleSymbol(resolveExternalModuleName(node, ts.getExternalModuleImportEqualsDeclarationExpression(node))); } return getSymbolOfPartOfRightHandSideOfImportEquals(node.moduleReference, node); @@ -11381,15 +12768,15 @@ var ts; var moduleSymbol = resolveExternalModuleName(node, node.moduleSpecifier); var targetSymbol = resolveESModuleSymbol(moduleSymbol, node.moduleSpecifier); if (targetSymbol) { - var name_4 = specifier.propertyName || specifier.name; - if (name_4.text) { - var symbolFromModule = getExportOfModule(targetSymbol, name_4.text); - var symbolFromVariable = getPropertyOfVariable(targetSymbol, name_4.text); + var name_8 = specifier.propertyName || specifier.name; + if (name_8.text) { + var symbolFromModule = getExportOfModule(targetSymbol, name_8.text); + var symbolFromVariable = getPropertyOfVariable(targetSymbol, name_8.text); var symbol = symbolFromModule && symbolFromVariable ? combineValueAndTypeSymbols(symbolFromVariable, symbolFromModule) : symbolFromModule || symbolFromVariable; if (!symbol) { - error(name_4, ts.Diagnostics.Module_0_has_no_exported_member_1, getFullyQualifiedName(moduleSymbol), ts.declarationNameToString(name_4)); + error(name_8, ts.Diagnostics.Module_0_has_no_exported_member_1, getFullyQualifiedName(moduleSymbol), ts.declarationNameToString(name_8)); } return symbol; } @@ -11408,17 +12795,17 @@ var ts; } function getTargetOfAliasDeclaration(node) { switch (node.kind) { - case 209 /* ImportEqualsDeclaration */: + case 211 /* ImportEqualsDeclaration */: return getTargetOfImportEqualsDeclaration(node); - case 211 /* ImportClause */: + case 213 /* ImportClause */: return getTargetOfImportClause(node); - case 212 /* NamespaceImport */: + case 214 /* NamespaceImport */: return getTargetOfNamespaceImport(node); - case 214 /* ImportSpecifier */: + case 216 /* ImportSpecifier */: return getTargetOfImportSpecifier(node); - case 218 /* ExportSpecifier */: + case 220 /* ExportSpecifier */: return getTargetOfExportSpecifier(node); - case 215 /* ExportAssignment */: + case 217 /* ExportAssignment */: return getTargetOfExportAssignment(node); } } @@ -11448,7 +12835,7 @@ var ts; var symbol = getSymbolOfNode(node); var target = resolveAlias(symbol); if (target) { - var markAlias = (target === unknownSymbol && compilerOptions.separateCompilation) || + var markAlias = (target === unknownSymbol && compilerOptions.isolatedModules) || (target !== unknownSymbol && (target.flags & 107455 /* Value */) && !isConstEnumOrConstEnumOnlyModule(target)); if (markAlias) { markAliasSymbolAsReferenced(symbol); @@ -11463,11 +12850,11 @@ var ts; if (!links.referenced) { links.referenced = true; var node = getDeclarationOfAliasSymbol(symbol); - if (node.kind === 215 /* ExportAssignment */) { + if (node.kind === 217 /* ExportAssignment */) { // export default checkExpressionCached(node.expression); } - else if (node.kind === 218 /* ExportSpecifier */) { + else if (node.kind === 220 /* ExportSpecifier */) { // export { } or export { as foo } checkExpressionCached(node.propertyName || node.name); } @@ -11480,7 +12867,7 @@ var ts; // This function is only for imports with entity names function getSymbolOfPartOfRightHandSideOfImportEquals(entityName, importDeclaration) { if (!importDeclaration) { - importDeclaration = ts.getAncestor(entityName, 209 /* ImportEqualsDeclaration */); + importDeclaration = ts.getAncestor(entityName, 211 /* ImportEqualsDeclaration */); ts.Debug.assert(importDeclaration !== undefined); } // There are three things we might try to look for. In the following examples, @@ -11493,13 +12880,13 @@ var ts; entityName = entityName.parent; } // Check for case 1 and 3 in the above example - if (entityName.kind === 65 /* Identifier */ || entityName.parent.kind === 127 /* QualifiedName */) { + if (entityName.kind === 65 /* Identifier */ || entityName.parent.kind === 128 /* QualifiedName */) { return resolveEntityName(entityName, 1536 /* Namespace */); } else { // Case 2 in above example // entityName.kind could be a QualifiedName or a Missing identifier - ts.Debug.assert(entityName.parent.kind === 209 /* ImportEqualsDeclaration */); + ts.Debug.assert(entityName.parent.kind === 211 /* ImportEqualsDeclaration */); return resolveEntityName(entityName, 107455 /* Value */ | 793056 /* Type */ | 1536 /* Namespace */); } } @@ -11519,9 +12906,9 @@ var ts; return undefined; } } - else if (name.kind === 127 /* QualifiedName */ || name.kind === 156 /* PropertyAccessExpression */) { - var left = name.kind === 127 /* QualifiedName */ ? name.left : name.expression; - var right = name.kind === 127 /* QualifiedName */ ? name.right : name.name; + else if (name.kind === 128 /* QualifiedName */ || name.kind === 158 /* PropertyAccessExpression */) { + var left = name.kind === 128 /* QualifiedName */ ? name.left : name.expression; + var right = name.kind === 128 /* QualifiedName */ ? name.right : name.name; var namespace = resolveEntityName(left, 1536 /* Namespace */); if (!namespace || namespace === unknownSymbol || ts.nodeIsMissing(right)) { return undefined; @@ -11682,7 +13069,7 @@ var ts; var members = node.members; for (var _i = 0; _i < members.length; _i++) { var member = members[_i]; - if (member.kind === 136 /* Constructor */ && ts.nodeIsPresent(member.body)) { + if (member.kind === 137 /* Constructor */ && ts.nodeIsPresent(member.body)) { return member; } } @@ -11752,17 +13139,17 @@ var ts; } } switch (location_1.kind) { - case 228 /* SourceFile */: + case 230 /* SourceFile */: if (!ts.isExternalModule(location_1)) { break; } - case 206 /* ModuleDeclaration */: + case 208 /* ModuleDeclaration */: if (result = callback(getSymbolOfNode(location_1).exports)) { return result; } break; - case 202 /* ClassDeclaration */: - case 203 /* InterfaceDeclaration */: + case 204 /* ClassDeclaration */: + case 205 /* InterfaceDeclaration */: if (result = callback(getSymbolOfNode(location_1).members)) { return result; } @@ -11911,8 +13298,8 @@ var ts; } } function hasExternalModuleSymbol(declaration) { - return (declaration.kind === 206 /* ModuleDeclaration */ && declaration.name.kind === 8 /* StringLiteral */) || - (declaration.kind === 228 /* SourceFile */ && ts.isExternalModule(declaration)); + return (declaration.kind === 208 /* ModuleDeclaration */ && declaration.name.kind === 8 /* StringLiteral */) || + (declaration.kind === 230 /* SourceFile */ && ts.isExternalModule(declaration)); } function hasVisibleDeclarations(symbol) { var aliasesToMakeVisible; @@ -11948,12 +13335,12 @@ var ts; function isEntityNameVisible(entityName, enclosingDeclaration) { // get symbol of the first identifier of the entityName var meaning; - if (entityName.parent.kind === 145 /* TypeQuery */) { + if (entityName.parent.kind === 147 /* TypeQuery */) { // Typeof value meaning = 107455 /* Value */ | 1048576 /* ExportValue */; } - else if (entityName.kind === 127 /* QualifiedName */ || entityName.kind === 156 /* PropertyAccessExpression */ || - entityName.parent.kind === 209 /* ImportEqualsDeclaration */) { + else if (entityName.kind === 128 /* QualifiedName */ || entityName.kind === 158 /* PropertyAccessExpression */ || + entityName.parent.kind === 211 /* ImportEqualsDeclaration */) { // Left identifier from type reference or TypeAlias // Entity name of the import declaration meaning = 1536 /* Namespace */; @@ -11987,6 +13374,13 @@ var ts; ts.releaseStringWriter(writer); return result; } + function signatureToString(signature, enclosingDeclaration, flags) { + var writer = ts.getSingleLineStringWriter(); + getSymbolDisplayBuilder().buildSignatureDisplay(signature, writer, enclosingDeclaration, flags); + var result = writer.string(); + ts.releaseStringWriter(writer); + return result; + } function typeToString(type, enclosingDeclaration, flags) { var writer = ts.getSingleLineStringWriter(); getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); @@ -12001,10 +13395,10 @@ var ts; function getTypeAliasForTypeLiteral(type) { if (type.symbol && type.symbol.flags & 2048 /* TypeLiteral */) { var node = type.symbol.declarations[0].parent; - while (node.kind === 150 /* ParenthesizedType */) { + while (node.kind === 152 /* ParenthesizedType */) { node = node.parent; } - if (node.kind === 204 /* TypeAliasDeclaration */) { + if (node.kind === 206 /* TypeAliasDeclaration */) { return getSymbolOfNode(node); } } @@ -12095,15 +13489,16 @@ var ts; } return appendParentTypeArgumentsAndSymbolName(symbol); } - function buildTypeDisplay(type, writer, enclosingDeclaration, globalFlags, typeStack) { + function buildTypeDisplay(type, writer, enclosingDeclaration, globalFlags, symbolStack) { var globalFlagsToPass = globalFlags & 16 /* WriteOwnNameForAnyLike */; return writeType(type, globalFlags); function writeType(type, flags) { // Write undefined/null type as any - if (type.flags & 1048703 /* Intrinsic */) { + if (type.flags & 2097279 /* Intrinsic */) { // Special handling for unknown / resolving types, they should show up as any and not unknown or __resolving - writer.writeKeyword(!(globalFlags & 16 /* WriteOwnNameForAnyLike */) && - (type.flags & 1 /* Any */) ? "any" : type.intrinsicName); + writer.writeKeyword(!(globalFlags & 16 /* WriteOwnNameForAnyLike */) && isTypeAny(type) + ? "any" + : type.intrinsicName); } else if (type.flags & 4096 /* Reference */) { writeTypeReference(type, flags); @@ -12146,17 +13541,54 @@ var ts; writeType(types[i], union ? 64 /* InElementType */ : 0 /* None */); } } + function writeSymbolTypeReference(symbol, typeArguments, pos, end) { + // Unnamed function expressions, arrow functions, and unnamed class expressions have reserved names that + // we don't want to display + if (!isReservedMemberName(symbol.name)) { + buildSymbolDisplay(symbol, writer, enclosingDeclaration, 793056 /* Type */); + } + if (pos < end) { + writePunctuation(writer, 24 /* LessThanToken */); + writeType(typeArguments[pos++], 0 /* None */); + while (pos < end) { + writePunctuation(writer, 23 /* CommaToken */); + writeSpace(writer); + writeType(typeArguments[pos++], 0 /* None */); + } + writePunctuation(writer, 25 /* GreaterThanToken */); + } + } function writeTypeReference(type, flags) { + var typeArguments = type.typeArguments; if (type.target === globalArrayType && !(flags & 1 /* WriteArrayAsGenericType */)) { - writeType(type.typeArguments[0], 64 /* InElementType */); + writeType(typeArguments[0], 64 /* InElementType */); writePunctuation(writer, 18 /* OpenBracketToken */); writePunctuation(writer, 19 /* CloseBracketToken */); } else { - buildSymbolDisplay(type.target.symbol, writer, enclosingDeclaration, 793056 /* Type */); - writePunctuation(writer, 24 /* LessThanToken */); - writeTypeList(type.typeArguments, false); - writePunctuation(writer, 25 /* GreaterThanToken */); + // 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_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_3 = getParentSymbolOfTypeParameter(outerTypeParameters[i]); + do { + i++; + } while (i < length_1 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent_3); + // 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_3, typeArguments, start, i); + writePunctuation(writer, 20 /* DotToken */); + } + } + } + writeSymbolTypeReference(type.symbol, typeArguments, i, typeArguments.length); } } function writeTupleType(type) { @@ -12174,47 +13606,54 @@ var ts; } } function writeAnonymousType(type, flags) { - // Always use 'typeof T' for type of class, enum, and module objects - if (type.symbol && type.symbol.flags & (32 /* Class */ | 384 /* Enum */ | 512 /* ValueModule */)) { - writeTypeofSymbol(type, flags); - } - else if (shouldWriteTypeOfFunctionSymbol()) { - writeTypeofSymbol(type, flags); - } - else if (typeStack && ts.contains(typeStack, type)) { - // 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, 793056 /* Type */, 0 /* None */, flags); + var symbol = type.symbol; + if (symbol) { + // Always use 'typeof T' for type of class, enum, and module objects + if (symbol.flags & (32 /* Class */ | 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, 793056 /* Type */, 0 /* None */, flags); + } + else { + // Recursive usage, use any + writeKeyword(writer, 112 /* AnyKeyword */); + } } else { - // Recursive usage, use any - writeKeyword(writer, 112 /* AnyKeyword */); + // 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 { - if (!typeStack) { - typeStack = []; - } - typeStack.push(type); + // Anonymous types with no symbol are never circular writeLiteralType(type, flags); - typeStack.pop(); } function shouldWriteTypeOfFunctionSymbol() { - if (type.symbol) { - var isStaticMethodSymbol = !!(type.symbol.flags & 8192 /* Method */ && - ts.forEach(type.symbol.declarations, function (declaration) { return declaration.flags & 128 /* Static */; })); - var isNonLocalFunctionSymbol = !!(type.symbol.flags & 16 /* Function */) && - (type.symbol.parent || - ts.forEach(type.symbol.declarations, function (declaration) { - return declaration.parent.kind === 228 /* SourceFile */ || declaration.parent.kind === 207 /* ModuleBlock */; - })); - if (isStaticMethodSymbol || isNonLocalFunctionSymbol) { - // typeof is allowed only for static/non local functions - return !!(flags & 2 /* UseTypeOfFunction */) || - (typeStack && ts.contains(typeStack, type)); // it is type of the symbol uses itself recursively - } + var isStaticMethodSymbol = !!(symbol.flags & 8192 /* Method */ && + ts.forEach(symbol.declarations, function (declaration) { return declaration.flags & 128 /* Static */; })); + var isNonLocalFunctionSymbol = !!(symbol.flags & 16 /* Function */) && + (symbol.parent || + ts.forEach(symbol.declarations, function (declaration) { + return declaration.parent.kind === 230 /* SourceFile */ || declaration.parent.kind === 209 /* 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 } } } @@ -12245,7 +13684,7 @@ var ts; if (flags & 64 /* InElementType */) { writePunctuation(writer, 16 /* OpenParenToken */); } - buildSignatureDisplay(resolved.callSignatures[0], writer, enclosingDeclaration, globalFlagsToPass | 8 /* WriteArrowStyleSignature */, typeStack); + buildSignatureDisplay(resolved.callSignatures[0], writer, enclosingDeclaration, globalFlagsToPass | 8 /* WriteArrowStyleSignature */, symbolStack); if (flags & 64 /* InElementType */) { writePunctuation(writer, 17 /* CloseParenToken */); } @@ -12257,7 +13696,7 @@ var ts; } writeKeyword(writer, 88 /* NewKeyword */); writeSpace(writer); - buildSignatureDisplay(resolved.constructSignatures[0], writer, enclosingDeclaration, globalFlagsToPass | 8 /* WriteArrowStyleSignature */, typeStack); + buildSignatureDisplay(resolved.constructSignatures[0], writer, enclosingDeclaration, globalFlagsToPass | 8 /* WriteArrowStyleSignature */, symbolStack); if (flags & 64 /* InElementType */) { writePunctuation(writer, 17 /* CloseParenToken */); } @@ -12269,7 +13708,7 @@ var ts; writer.increaseIndent(); for (var _i = 0, _a = resolved.callSignatures; _i < _a.length; _i++) { var signature = _a[_i]; - buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, typeStack); + buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, symbolStack); writePunctuation(writer, 22 /* SemicolonToken */); writer.writeLine(); } @@ -12277,7 +13716,7 @@ var ts; var signature = _c[_b]; writeKeyword(writer, 88 /* NewKeyword */); writeSpace(writer); - buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, typeStack); + buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, symbolStack); writePunctuation(writer, 22 /* SemicolonToken */); writer.writeLine(); } @@ -12287,7 +13726,7 @@ var ts; writer.writeParameter(getIndexerParameterName(resolved, 0 /* String */, "x")); writePunctuation(writer, 51 /* ColonToken */); writeSpace(writer); - writeKeyword(writer, 122 /* StringKeyword */); + writeKeyword(writer, 123 /* StringKeyword */); writePunctuation(writer, 19 /* CloseBracketToken */); writePunctuation(writer, 51 /* ColonToken */); writeSpace(writer); @@ -12301,7 +13740,7 @@ var ts; writer.writeParameter(getIndexerParameterName(resolved, 1 /* Number */, "x")); writePunctuation(writer, 51 /* ColonToken */); writeSpace(writer); - writeKeyword(writer, 120 /* NumberKeyword */); + writeKeyword(writer, 121 /* NumberKeyword */); writePunctuation(writer, 19 /* CloseBracketToken */); writePunctuation(writer, 51 /* ColonToken */); writeSpace(writer); @@ -12320,7 +13759,7 @@ var ts; if (p.flags & 536870912 /* Optional */) { writePunctuation(writer, 50 /* QuestionToken */); } - buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, typeStack); + buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, symbolStack); writePunctuation(writer, 22 /* SemicolonToken */); writer.writeLine(); } @@ -12344,32 +13783,33 @@ var ts; function buildTypeParameterDisplayFromSymbol(symbol, writer, enclosingDeclaraiton, flags) { var targetSymbol = getTargetSymbol(symbol); if (targetSymbol.flags & 32 /* Class */ || targetSymbol.flags & 64 /* Interface */) { - buildDisplayForTypeParametersAndDelimiters(getTypeParametersOfClassOrInterface(symbol), writer, enclosingDeclaraiton, flags); + buildDisplayForTypeParametersAndDelimiters(getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol), writer, enclosingDeclaraiton, flags); } } - function buildTypeParameterDisplay(tp, writer, enclosingDeclaration, flags, typeStack) { + function buildTypeParameterDisplay(tp, writer, enclosingDeclaration, flags, symbolStack) { appendSymbolNameOnly(tp.symbol, writer); var constraint = getConstraintOfTypeParameter(tp); if (constraint) { writeSpace(writer); writeKeyword(writer, 79 /* ExtendsKeyword */); writeSpace(writer); - buildTypeDisplay(constraint, writer, enclosingDeclaration, flags, typeStack); + buildTypeDisplay(constraint, writer, enclosingDeclaration, flags, symbolStack); } } - function buildParameterDisplay(p, writer, enclosingDeclaration, flags, typeStack) { - if (ts.hasDotDotDotToken(p.valueDeclaration)) { + function buildParameterDisplay(p, writer, enclosingDeclaration, flags, symbolStack) { + var parameterNode = p.valueDeclaration; + if (ts.isRestParameter(parameterNode)) { writePunctuation(writer, 21 /* DotDotDotToken */); } appendSymbolNameOnly(p, writer); - if (ts.hasQuestionToken(p.valueDeclaration) || p.valueDeclaration.initializer) { + if (isOptionalParameter(parameterNode)) { writePunctuation(writer, 50 /* QuestionToken */); } writePunctuation(writer, 51 /* ColonToken */); writeSpace(writer); - buildTypeDisplay(getTypeOfSymbol(p), writer, enclosingDeclaration, flags, typeStack); + buildTypeDisplay(getTypeOfSymbol(p), writer, enclosingDeclaration, flags, symbolStack); } - function buildDisplayForTypeParametersAndDelimiters(typeParameters, writer, enclosingDeclaration, flags, typeStack) { + function buildDisplayForTypeParametersAndDelimiters(typeParameters, writer, enclosingDeclaration, flags, symbolStack) { if (typeParameters && typeParameters.length) { writePunctuation(writer, 24 /* LessThanToken */); for (var i = 0; i < typeParameters.length; i++) { @@ -12377,12 +13817,12 @@ var ts; writePunctuation(writer, 23 /* CommaToken */); writeSpace(writer); } - buildTypeParameterDisplay(typeParameters[i], writer, enclosingDeclaration, flags, typeStack); + buildTypeParameterDisplay(typeParameters[i], writer, enclosingDeclaration, flags, symbolStack); } writePunctuation(writer, 25 /* GreaterThanToken */); } } - function buildDisplayForTypeArgumentsAndDelimiters(typeParameters, mapper, writer, enclosingDeclaration, flags, typeStack) { + function buildDisplayForTypeArgumentsAndDelimiters(typeParameters, mapper, writer, enclosingDeclaration, flags, symbolStack) { if (typeParameters && typeParameters.length) { writePunctuation(writer, 24 /* LessThanToken */); for (var i = 0; i < typeParameters.length; i++) { @@ -12395,18 +13835,18 @@ var ts; writePunctuation(writer, 25 /* GreaterThanToken */); } } - function buildDisplayForParametersAndDelimiters(parameters, writer, enclosingDeclaration, flags, typeStack) { + function buildDisplayForParametersAndDelimiters(parameters, writer, enclosingDeclaration, flags, symbolStack) { writePunctuation(writer, 16 /* OpenParenToken */); for (var i = 0; i < parameters.length; i++) { if (i > 0) { writePunctuation(writer, 23 /* CommaToken */); writeSpace(writer); } - buildParameterDisplay(parameters[i], writer, enclosingDeclaration, flags, typeStack); + buildParameterDisplay(parameters[i], writer, enclosingDeclaration, flags, symbolStack); } writePunctuation(writer, 17 /* CloseParenToken */); } - function buildReturnTypeDisplay(signature, writer, enclosingDeclaration, flags, typeStack) { + function buildReturnTypeDisplay(signature, writer, enclosingDeclaration, flags, symbolStack) { if (flags & 8 /* WriteArrowStyleSignature */) { writeSpace(writer); writePunctuation(writer, 32 /* EqualsGreaterThanToken */); @@ -12415,19 +13855,19 @@ var ts; writePunctuation(writer, 51 /* ColonToken */); } writeSpace(writer); - buildTypeDisplay(getReturnTypeOfSignature(signature), writer, enclosingDeclaration, flags, typeStack); + buildTypeDisplay(getReturnTypeOfSignature(signature), writer, enclosingDeclaration, flags, symbolStack); } - function buildSignatureDisplay(signature, writer, enclosingDeclaration, flags, typeStack) { + function buildSignatureDisplay(signature, writer, enclosingDeclaration, flags, symbolStack) { 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, typeStack); + buildDisplayForTypeParametersAndDelimiters(signature.typeParameters, writer, enclosingDeclaration, flags, symbolStack); } - buildDisplayForParametersAndDelimiters(signature.parameters, writer, enclosingDeclaration, flags, typeStack); - buildReturnTypeDisplay(signature, writer, enclosingDeclaration, flags, typeStack); + buildDisplayForParametersAndDelimiters(signature.parameters, writer, enclosingDeclaration, flags, symbolStack); + buildReturnTypeDisplay(signature, writer, enclosingDeclaration, flags, symbolStack); } return _displayBuilder || (_displayBuilder = { symbolToString: symbolToString, @@ -12447,12 +13887,12 @@ var ts; function isDeclarationVisible(node) { function getContainingExternalModule(node) { for (; node; node = node.parent) { - if (node.kind === 206 /* ModuleDeclaration */) { + if (node.kind === 208 /* ModuleDeclaration */) { if (node.name.kind === 8 /* StringLiteral */) { return node; } } - else if (node.kind === 228 /* SourceFile */) { + else if (node.kind === 230 /* SourceFile */) { return ts.isExternalModule(node) ? node : undefined; } } @@ -12501,69 +13941,69 @@ var ts; } function determineIfDeclarationIsVisible() { switch (node.kind) { - case 153 /* BindingElement */: + case 155 /* BindingElement */: return isDeclarationVisible(node.parent.parent); - case 199 /* VariableDeclaration */: + case 201 /* VariableDeclaration */: if (ts.isBindingPattern(node.name) && !node.name.elements.length) { // If the binding pattern is empty, this variable declaration is not visible return false; } // Otherwise fall through - case 206 /* ModuleDeclaration */: - case 202 /* ClassDeclaration */: - case 203 /* InterfaceDeclaration */: - case 204 /* TypeAliasDeclaration */: - case 201 /* FunctionDeclaration */: - case 205 /* EnumDeclaration */: - case 209 /* ImportEqualsDeclaration */: - var parent_2 = getDeclarationContainer(node); + case 208 /* ModuleDeclaration */: + case 204 /* ClassDeclaration */: + case 205 /* InterfaceDeclaration */: + case 206 /* TypeAliasDeclaration */: + case 203 /* FunctionDeclaration */: + case 207 /* EnumDeclaration */: + case 211 /* ImportEqualsDeclaration */: + var parent_4 = getDeclarationContainer(node); // If the node is not exported or it is not ambient module element (except import declaration) if (!(ts.getCombinedNodeFlags(node) & 1 /* Export */) && - !(node.kind !== 209 /* ImportEqualsDeclaration */ && parent_2.kind !== 228 /* SourceFile */ && ts.isInAmbientContext(parent_2))) { - return isGlobalSourceFile(parent_2); + !(node.kind !== 211 /* ImportEqualsDeclaration */ && parent_4.kind !== 230 /* SourceFile */ && ts.isInAmbientContext(parent_4))) { + return isGlobalSourceFile(parent_4); } // Exported members/ambient module elements (exception import declaration) are visible if parent is visible - return isDeclarationVisible(parent_2); - case 133 /* PropertyDeclaration */: - case 132 /* PropertySignature */: - case 137 /* GetAccessor */: - case 138 /* SetAccessor */: - case 135 /* MethodDeclaration */: - case 134 /* MethodSignature */: + return isDeclarationVisible(parent_4); + case 134 /* PropertyDeclaration */: + case 133 /* PropertySignature */: + case 138 /* GetAccessor */: + case 139 /* SetAccessor */: + case 136 /* MethodDeclaration */: + case 135 /* MethodSignature */: if (node.flags & (32 /* Private */ | 64 /* Protected */)) { // Private/protected properties/methods are not visible return false; } // Public properties/methods are visible if its parents are visible, so let it fall into next case statement - case 136 /* Constructor */: - case 140 /* ConstructSignature */: - case 139 /* CallSignature */: - case 141 /* IndexSignature */: - case 130 /* Parameter */: - case 207 /* ModuleBlock */: - case 143 /* FunctionType */: - case 144 /* ConstructorType */: - case 146 /* TypeLiteral */: - case 142 /* TypeReference */: - case 147 /* ArrayType */: - case 148 /* TupleType */: - case 149 /* UnionType */: - case 150 /* ParenthesizedType */: + case 137 /* Constructor */: + case 141 /* ConstructSignature */: + case 140 /* CallSignature */: + case 142 /* IndexSignature */: + case 131 /* Parameter */: + case 209 /* ModuleBlock */: + case 145 /* FunctionType */: + case 146 /* ConstructorType */: + case 148 /* TypeLiteral */: + case 144 /* TypeReference */: + case 149 /* ArrayType */: + case 150 /* TupleType */: + case 151 /* UnionType */: + case 152 /* 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 211 /* ImportClause */: - case 212 /* NamespaceImport */: - case 214 /* ImportSpecifier */: + case 213 /* ImportClause */: + case 214 /* NamespaceImport */: + case 216 /* ImportSpecifier */: return false; // Type parameters are always visible - case 129 /* TypeParameter */: + case 130 /* TypeParameter */: // Source file is always visible - case 228 /* SourceFile */: + case 230 /* SourceFile */: return true; // Export assignements do not create name bindings outside the module - case 215 /* ExportAssignment */: + case 217 /* ExportAssignment */: return false; default: ts.Debug.fail("isDeclarationVisible unknown: SyntaxKind: " + node.kind); @@ -12579,10 +14019,10 @@ var ts; } function collectLinkedAliases(node) { var exportSymbol; - if (node.parent && node.parent.kind === 215 /* ExportAssignment */) { + if (node.parent && node.parent.kind === 217 /* ExportAssignment */) { exportSymbol = resolveName(node.parent, node.text, 107455 /* Value */ | 793056 /* Type */ | 1536 /* Namespace */, ts.Diagnostics.Cannot_find_name_0, node); } - else if (node.parent.kind === 218 /* ExportSpecifier */) { + else if (node.parent.kind === 220 /* ExportSpecifier */) { exportSymbol = getTargetOfExportSpecifier(node.parent); } var result = []; @@ -12640,7 +14080,7 @@ var ts; node = ts.getRootDeclaration(node); // Parent chain: // VaribleDeclaration -> VariableDeclarationList -> VariableStatement -> 'Declaration Container' - return node.kind === 199 /* VariableDeclaration */ ? node.parent.parent.parent : node.parent; + return node.kind === 201 /* VariableDeclaration */ ? node.parent.parent.parent : node.parent; } function getTypeOfPrototypeProperty(prototype) { // TypeScript 1.0 spec (April 2014): 8.4 @@ -12655,6 +14095,9 @@ var ts; var prop = getPropertyOfType(type, name); return prop ? getTypeOfSymbol(prop) : undefined; } + function isTypeAny(type) { + return type && (type.flags & 1 /* Any */) !== 0; + } // Return the inferred type for a binding element function getTypeForBindingElement(declaration) { var pattern = declaration.parent; @@ -12666,23 +14109,23 @@ var ts; // 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 || parentType === anyType) { + if (!parentType || isTypeAny(parentType)) { if (declaration.initializer) { return checkExpressionCached(declaration.initializer); } return parentType; } var type; - if (pattern.kind === 151 /* ObjectBindingPattern */) { + if (pattern.kind === 153 /* ObjectBindingPattern */) { // Use explicitly specified property name ({ p: xxx } form), or otherwise the implied name ({ p } form) - var name_5 = declaration.propertyName || declaration.name; + var name_9 = declaration.propertyName || declaration.name; // 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. - type = getTypeOfPropertyOfType(parentType, name_5.text) || - isNumericLiteralName(name_5.text) && getIndexTypeOfType(parentType, 1 /* Number */) || + type = getTypeOfPropertyOfType(parentType, name_9.text) || + isNumericLiteralName(name_9.text) && getIndexTypeOfType(parentType, 1 /* Number */) || getIndexTypeOfType(parentType, 0 /* String */); if (!type) { - error(name_5, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(parentType), ts.declarationNameToString(name_5)); + error(name_9, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(parentType), ts.declarationNameToString(name_9)); return unknownType; } } @@ -12692,7 +14135,7 @@ var ts; // fact an iterable or array (depending on target language). var elementType = checkIteratedTypeOrElementType(parentType, pattern, false); if (!declaration.dotDotDotToken) { - if (elementType.flags & 1 /* Any */) { + if (isTypeAny(elementType)) { return elementType; } // Use specific property type when parent is a tuple or numeric index type when parent is an array @@ -12720,14 +14163,14 @@ var ts; // Return the inferred type for a variable, parameter, or property declaration function getTypeForVariableLikeDeclaration(declaration) { // A variable declared in a for..in statement is always of type any - if (declaration.parent.parent.kind === 188 /* ForInStatement */) { + if (declaration.parent.parent.kind === 190 /* ForInStatement */) { return anyType; } - if (declaration.parent.parent.kind === 189 /* ForOfStatement */) { + if (declaration.parent.parent.kind === 191 /* 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 getIteratedType. + // or it may have led to an error inside getElementTypeOfIterable. return checkRightHandSideOfForOf(declaration.parent.parent.expression) || anyType; } if (ts.isBindingPattern(declaration.parent)) { @@ -12737,11 +14180,11 @@ var ts; if (declaration.type) { return getTypeFromTypeNode(declaration.type); } - if (declaration.kind === 130 /* Parameter */) { + if (declaration.kind === 131 /* 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 === 138 /* SetAccessor */ && !ts.hasDynamicName(func)) { - var getter = ts.getDeclarationOfKind(declaration.parent.symbol, 137 /* GetAccessor */); + if (func.kind === 139 /* SetAccessor */ && !ts.hasDynamicName(func)) { + var getter = ts.getDeclarationOfKind(declaration.parent.symbol, 138 /* GetAccessor */); if (getter) { return getReturnTypeOfSignature(getSignatureFromDeclaration(getter)); } @@ -12757,7 +14200,7 @@ var ts; return checkExpressionCached(declaration.initializer); } // If it is a short-hand property assignment, use the type of the identifier - if (declaration.kind === 226 /* ShorthandPropertyAssignment */) { + if (declaration.kind === 228 /* ShorthandPropertyAssignment */) { return checkIdentifier(declaration.name); } // No type specified and nothing can be inferred @@ -12792,7 +14235,7 @@ var ts; var hasSpreadElement = false; var elementTypes = []; ts.forEach(pattern.elements, function (e) { - elementTypes.push(e.kind === 176 /* OmittedExpression */ || e.dotDotDotToken ? anyType : getTypeFromBindingElement(e)); + elementTypes.push(e.kind === 178 /* OmittedExpression */ || e.dotDotDotToken ? anyType : getTypeFromBindingElement(e)); if (e.dotDotDotToken) { hasSpreadElement = true; } @@ -12815,7 +14258,7 @@ var ts; // parameter with no type annotation or initializer, the type implied by the binding pattern becomes the type of // the parameter. function getTypeFromBindingPattern(pattern) { - return pattern.kind === 151 /* ObjectBindingPattern */ + return pattern.kind === 153 /* ObjectBindingPattern */ ? getTypeFromObjectBindingPattern(pattern) : getTypeFromArrayBindingPattern(pattern); } @@ -12837,7 +14280,7 @@ var ts; // 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. - return declaration.kind !== 225 /* PropertyAssignment */ ? getWidenedType(type) : type; + return declaration.kind !== 227 /* PropertyAssignment */ ? getWidenedType(type) : type; } // If no type was specified and nothing could be inferred, and if the declaration specifies a binding pattern, use // the type implied by the binding pattern @@ -12849,7 +14292,7 @@ var ts; // Report implicit any errors unless this is a private property within an ambient declaration if (reportErrors && compilerOptions.noImplicitAny) { var root = ts.getRootDeclaration(declaration); - if (!isPrivateWithinAmbient(root) && !(root.kind === 130 /* Parameter */ && isPrivateWithinAmbient(root.parent))) { + if (!isPrivateWithinAmbient(root) && !(root.kind === 131 /* Parameter */ && isPrivateWithinAmbient(root.parent))) { reportImplicitAnyError(declaration, type); } } @@ -12864,11 +14307,11 @@ var ts; } // Handle catch clause variables var declaration = symbol.valueDeclaration; - if (declaration.parent.kind === 224 /* CatchClause */) { + if (declaration.parent.kind === 226 /* CatchClause */) { return links.type = anyType; } // Handle export default expressions - if (declaration.kind === 215 /* ExportAssignment */) { + if (declaration.kind === 217 /* ExportAssignment */) { return links.type = checkExpression(declaration.expression); } // Handle variable, parameter or property @@ -12886,7 +14329,7 @@ var ts; // Variable has initializer that circularly references the variable itself type = anyType; if (compilerOptions.noImplicitAny) { - error(symbol.valueDeclaration, ts.Diagnostics._0_implicitly_has_type_any_because_it_is_does_not_have_a_type_annotation_and_is_referenced_directly_or_indirectly_in_its_own_initializer, symbolToString(symbol)); + 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)); } } } @@ -12899,7 +14342,7 @@ var ts; } function getAnnotatedAccessorType(accessor) { if (accessor) { - if (accessor.kind === 137 /* GetAccessor */) { + if (accessor.kind === 138 /* GetAccessor */) { return accessor.type && getTypeFromTypeNode(accessor.type); } else { @@ -12915,8 +14358,8 @@ var ts; if (!pushTypeResolution(symbol)) { return unknownType; } - var getter = ts.getDeclarationOfKind(symbol, 137 /* GetAccessor */); - var setter = ts.getDeclarationOfKind(symbol, 138 /* SetAccessor */); + var getter = ts.getDeclarationOfKind(symbol, 138 /* GetAccessor */); + var setter = ts.getDeclarationOfKind(symbol, 139 /* SetAccessor */); var type; // First try to see if the user specified a return type on the get-accessor. var getterReturnType = getAnnotatedAccessorType(getter); @@ -12945,7 +14388,7 @@ var ts; if (!popTypeResolution()) { type = anyType; if (compilerOptions.noImplicitAny) { - var getter_1 = ts.getDeclarationOfKind(symbol, 137 /* GetAccessor */); + var getter_1 = ts.getDeclarationOfKind(symbol, 138 /* 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)); } } @@ -13020,77 +14463,180 @@ var ts; return target === checkBase || ts.forEach(getBaseTypes(target), check); } } - // Return combined list of type parameters from all declarations of a class or interface. Elsewhere we check they're all - // the same, but even if they're not we still need the complete list to ensure instantiations supply type arguments - // for all type parameters. - function getTypeParametersOfClassOrInterface(symbol) { - var result; - ts.forEach(symbol.declarations, function (node) { - if (node.kind === 203 /* InterfaceDeclaration */ || node.kind === 202 /* ClassDeclaration */) { - var declaration = node; - if (declaration.typeParameters && declaration.typeParameters.length) { - ts.forEach(declaration.typeParameters, function (node) { - var tp = getDeclaredTypeOfTypeParameter(getSymbolOfNode(node)); - if (!result) { - result = [tp]; - } - else if (!ts.contains(result, tp)) { - result.push(tp); - } - }); + // 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; _i < declarations.length; _i++) { + var declaration = declarations[_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 === 204 /* ClassDeclaration */ || node.kind === 203 /* FunctionDeclaration */ || + node.kind === 165 /* FunctionExpression */ || node.kind === 136 /* MethodDeclaration */ || + node.kind === 166 /* 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 kind = symbol.flags & 32 /* Class */ ? 204 /* ClassDeclaration */ : 205 /* InterfaceDeclaration */; + return appendOuterTypeParameters(undefined, ts.getDeclarationOfKind(symbol, kind)); + } + // 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 === 205 /* InterfaceDeclaration */ || node.kind === 204 /* ClassDeclaration */ || node.kind === 206 /* 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)); + } + function isConstructorType(type) { + return type.flags & 48128 /* ObjectType */ && getSignaturesOfType(type, 1 /* Construct */).length > 0; + } + function getBaseTypeNodeOfClass(type) { + return ts.getClassExtendsHeritageClauseElement(type.symbol.valueDeclaration); + } + function getConstructorsForTypeArguments(type, typeArgumentNodes) { + var typeArgCount = typeArgumentNodes ? typeArgumentNodes.length : 0; + return ts.filter(getSignaturesOfType(type, 1 /* Construct */), function (sig) { return (sig.typeParameters ? sig.typeParameters.length : 0) === typeArgCount; }); + } + function getInstantiatedConstructorsForTypeArguments(type, typeArgumentNodes) { + var signatures = getConstructorsForTypeArguments(type, typeArgumentNodes); + if (typeArgumentNodes) { + var typeArguments = ts.map(typeArgumentNodes, getTypeFromTypeNode); + signatures = ts.map(signatures, function (sig) { return getSignatureInstantiation(sig, typeArguments); }); + } + 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, 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)) { + return unknownType; + } + var baseConstructorType = checkExpression(baseTypeNode.expression); + if (baseConstructorType.flags & 48128 /* ObjectType */) { + // 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. + resolveObjectOrUnionTypeMembers(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 !== unknownType && baseConstructorType !== nullType && !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) { - var typeWithBaseTypes = type; - if (!typeWithBaseTypes.baseTypes) { + if (!type.resolvedBaseTypes) { if (type.symbol.flags & 32 /* Class */) { - resolveBaseTypesOfClass(typeWithBaseTypes); + resolveBaseTypesOfClass(type); } else if (type.symbol.flags & 64 /* Interface */) { - resolveBaseTypesOfInterface(typeWithBaseTypes); + resolveBaseTypesOfInterface(type); } else { ts.Debug.fail("type must be class or interface"); } } - return typeWithBaseTypes.baseTypes; + return type.resolvedBaseTypes; } function resolveBaseTypesOfClass(type) { - type.baseTypes = []; - var declaration = ts.getDeclarationOfKind(type.symbol, 202 /* ClassDeclaration */); - var baseTypeNode = ts.getClassExtendsHeritageClauseElement(declaration); - if (baseTypeNode) { - var baseType = getTypeFromTypeNode(baseTypeNode); - if (baseType !== unknownType) { - if (getTargetType(baseType).flags & 1024 /* Class */) { - if (type !== baseType && !hasBaseType(baseType, type)) { - type.baseTypes.push(baseType); - } - else { - error(declaration, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, undefined, 1 /* WriteArrayAsGenericType */)); - } - } - else { - error(baseTypeNode, ts.Diagnostics.A_class_may_only_extend_another_class); - } - } + type.resolvedBaseTypes = emptyArray; + var baseContructorType = getBaseConstructorTypeOfClass(type); + if (!(baseContructorType.flags & 48128 /* ObjectType */)) { + return; } + var baseTypeNode = getBaseTypeNodeOfClass(type); + var baseType; + if (baseContructorType.symbol && baseContructorType.symbol.flags & 32 /* Class */) { + // When base constructor type is a class 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, baseContructorType.symbol); + } + 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(baseContructorType, baseTypeNode.typeArguments); + if (!constructors.length) { + error(baseTypeNode.expression, ts.Diagnostics.No_base_constructor_has_the_specified_number_of_type_arguments); + return; + } + baseType = getReturnTypeOfSignature(constructors[0]); + } + if (baseType === unknownType) { + return; + } + if (!(getTargetType(baseType).flags & (1024 /* Class */ | 2048 /* Interface */))) { + 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(type.symbol.valueDeclaration, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, undefined, 1 /* WriteArrayAsGenericType */)); + return; + } + type.resolvedBaseTypes = [baseType]; } function resolveBaseTypesOfInterface(type) { - type.baseTypes = []; + type.resolvedBaseTypes = []; for (var _i = 0, _a = type.symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (declaration.kind === 203 /* InterfaceDeclaration */ && ts.getInterfaceBaseTypeNodes(declaration)) { + if (declaration.kind === 205 /* 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 (getTargetType(baseType).flags & (1024 /* Class */ | 2048 /* Interface */)) { if (type !== baseType && !hasBaseType(baseType, type)) { - type.baseTypes.push(baseType); + type.resolvedBaseTypes.push(baseType); } else { error(declaration, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, undefined, 1 /* WriteArrayAsGenericType */)); @@ -13109,10 +14655,13 @@ var ts; if (!links.declaredType) { var kind = symbol.flags & 32 /* Class */ ? 1024 /* Class */ : 2048 /* Interface */; var type = links.declaredType = createObjectType(kind, symbol); - var typeParameters = getTypeParametersOfClassOrInterface(symbol); - if (typeParameters) { + var outerTypeParameters = getOuterTypeParametersOfClassOrInterface(symbol); + var localTypeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); + if (outerTypeParameters || localTypeParameters) { type.flags |= 4096 /* Reference */; - type.typeParameters = typeParameters; + type.typeParameters = ts.concatenate(outerTypeParameters, localTypeParameters); + type.outerTypeParameters = outerTypeParameters; + type.localTypeParameters = localTypeParameters; type.instantiations = {}; type.instantiations[getTypeListId(type.typeParameters)] = type; type.target = type; @@ -13129,9 +14678,18 @@ var ts; if (!pushTypeResolution(links)) { return unknownType; } - var declaration = ts.getDeclarationOfKind(symbol, 204 /* TypeAliasDeclaration */); + var declaration = ts.getDeclarationOfKind(symbol, 206 /* TypeAliasDeclaration */); var type = getTypeFromTypeNode(declaration.type); - if (!popTypeResolution()) { + if (popTypeResolution()) { + links.typeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); + if (links.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.instantiations = {}; + links.instantiations[getTypeListId(links.typeParameters)] = type; + } + } + else { type = unknownType; error(declaration.name, ts.Diagnostics.Type_alias_0_circularly_references_itself, symbolToString(symbol)); } @@ -13153,7 +14711,7 @@ var ts; if (!links.declaredType) { var type = createType(512 /* TypeParameter */); type.symbol = symbol; - if (!ts.getDeclarationOfKind(symbol, 129 /* TypeParameter */).constraint) { + if (!ts.getDeclarationOfKind(symbol, 130 /* TypeParameter */).constraint) { type.constraint = noConstraintType; } links.declaredType = type; @@ -13268,34 +14826,42 @@ var ts; }); setObjectTypeMembers(type, members, callSignatures, constructSignatures, stringIndexType, numberIndexType); } - function createSignature(declaration, typeParameters, parameters, resolvedReturnType, minArgumentCount, hasRestParameter, hasStringLiterals) { + function createSignature(declaration, typeParameters, parameters, resolvedReturnType, typePredicate, minArgumentCount, hasRestParameter, hasStringLiterals) { var sig = new Signature(checker); sig.declaration = declaration; sig.typeParameters = typeParameters; sig.parameters = parameters; sig.resolvedReturnType = resolvedReturnType; + sig.typePredicate = typePredicate; sig.minArgumentCount = minArgumentCount; sig.hasRestParameter = hasRestParameter; sig.hasStringLiterals = hasStringLiterals; return sig; } function cloneSignature(sig) { - return createSignature(sig.declaration, sig.typeParameters, sig.parameters, sig.resolvedReturnType, sig.minArgumentCount, sig.hasRestParameter, sig.hasStringLiterals); + return createSignature(sig.declaration, sig.typeParameters, sig.parameters, sig.resolvedReturnType, sig.typePredicate, sig.minArgumentCount, sig.hasRestParameter, sig.hasStringLiterals); } function getDefaultConstructSignatures(classType) { - var baseTypes = getBaseTypes(classType); - if (baseTypes.length) { - var baseType = baseTypes[0]; - var baseSignatures = getSignaturesOfType(getTypeOfSymbol(baseType.symbol), 1 /* Construct */); - return ts.map(baseSignatures, function (baseSignature) { - var signature = baseType.flags & 4096 /* Reference */ ? - getSignatureInstantiation(baseSignature, baseType.typeArguments) : cloneSignature(baseSignature); - signature.typeParameters = classType.typeParameters; - signature.resolvedReturnType = classType; - return signature; - }); + if (!getBaseTypes(classType).length) { + return [createSignature(undefined, classType.localTypeParameters, emptyArray, classType, undefined, 0, false, false)]; } - return [createSignature(undefined, classType.typeParameters, emptyArray, classType, 0, false, false)]; + var baseConstructorType = getBaseConstructorTypeOfClass(classType); + var baseSignatures = getSignaturesOfType(baseConstructorType, 1 /* Construct */); + var baseTypeNode = getBaseTypeNodeOfClass(classType); + var typeArguments = ts.map(baseTypeNode.typeArguments, getTypeFromTypeNode); + var typeArgCount = typeArguments ? typeArguments.length : 0; + var result = []; + for (var _i = 0; _i < baseSignatures.length; _i++) { + var baseSig = baseSignatures[_i]; + var typeParamCount = baseSig.typeParameters ? baseSig.typeParameters.length : 0; + if (typeParamCount === typeArgCount) { + var sig = typeParamCount ? getSignatureInstantiation(baseSig, typeArguments) : cloneSignature(baseSig); + sig.typeParameters = classType.localTypeParameters; + sig.resolvedReturnType = classType; + result.push(sig); + } + } + return result; } function createTupleTypeMemberSymbols(memberTypes) { var members = {}; @@ -13401,10 +14967,10 @@ var ts; if (!constructSignatures.length) { constructSignatures = getDefaultConstructSignatures(classType); } - var baseTypes = getBaseTypes(classType); - if (baseTypes.length) { + var baseConstructorType = getBaseConstructorTypeOfClass(classType); + if (baseConstructorType.flags & 48128 /* ObjectType */) { members = createSymbolTable(getNamedMembers(members)); - addInheritedMembers(members, getPropertiesOfObjectType(getTypeOfSymbol(baseTypes[0].symbol))); + addInheritedMembers(members, getPropertiesOfObjectType(baseConstructorType)); } } stringIndexType = undefined; @@ -13490,7 +15056,7 @@ var ts; else if (type.flags & 8 /* Boolean */) { type = globalBooleanType; } - else if (type.flags & 1048576 /* ESSymbol */) { + else if (type.flags & 2097152 /* ESSymbol */) { type = globalESSymbolType; } return type; @@ -13619,11 +15185,14 @@ var ts; } return result; } + function isOptionalParameter(node) { + return ts.hasQuestionToken(node) || !!node.initializer; + } function getSignatureFromDeclaration(declaration) { var links = getNodeLinks(declaration); if (!links.resolvedSignature) { - var classType = declaration.kind === 136 /* Constructor */ ? getDeclaredTypeOfClassOrInterface(declaration.parent.symbol) : undefined; - var typeParameters = classType ? classType.typeParameters : + var classType = declaration.kind === 137 /* Constructor */ ? getDeclaredTypeOfClassOrInterface(declaration.parent.symbol) : undefined; + var typeParameters = classType ? classType.localTypeParameters : declaration.typeParameters ? getTypeParametersFromDeclaration(declaration.typeParameters) : undefined; var parameters = []; var hasStringLiterals = false; @@ -13644,24 +15213,33 @@ var ts; minArgumentCount = declaration.parameters.length; } var returnType; + var typePredicate; if (classType) { returnType = classType; } else if (declaration.type) { returnType = getTypeFromTypeNode(declaration.type); + if (declaration.type.kind === 143 /* TypePredicate */) { + var typePredicateNode = declaration.type; + typePredicate = { + parameterName: typePredicateNode.parameterName ? typePredicateNode.parameterName.text : undefined, + parameterIndex: typePredicateNode.parameterName ? getTypePredicateParameterIndex(declaration.parameters, typePredicateNode.parameterName) : undefined, + type: getTypeFromTypeNode(typePredicateNode.type) + }; + } } else { // 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 === 137 /* GetAccessor */ && !ts.hasDynamicName(declaration)) { - var setter = ts.getDeclarationOfKind(declaration.symbol, 138 /* SetAccessor */); + if (declaration.kind === 138 /* GetAccessor */ && !ts.hasDynamicName(declaration)) { + var setter = ts.getDeclarationOfKind(declaration.symbol, 139 /* SetAccessor */); returnType = getAnnotatedAccessorType(setter); } if (!returnType && ts.nodeIsMissing(declaration.body)) { returnType = anyType; } } - links.resolvedSignature = createSignature(declaration, typeParameters, parameters, returnType, minArgumentCount, ts.hasRestParameters(declaration), hasStringLiterals); + links.resolvedSignature = createSignature(declaration, typeParameters, parameters, returnType, typePredicate, minArgumentCount, ts.hasRestParameter(declaration), hasStringLiterals); } return links.resolvedSignature; } @@ -13672,19 +15250,19 @@ var ts; for (var i = 0, len = symbol.declarations.length; i < len; i++) { var node = symbol.declarations[i]; switch (node.kind) { - case 143 /* FunctionType */: - case 144 /* ConstructorType */: - case 201 /* FunctionDeclaration */: - case 135 /* MethodDeclaration */: - case 134 /* MethodSignature */: - case 136 /* Constructor */: - case 139 /* CallSignature */: - case 140 /* ConstructSignature */: - case 141 /* IndexSignature */: - case 137 /* GetAccessor */: - case 138 /* SetAccessor */: - case 163 /* FunctionExpression */: - case 164 /* ArrowFunction */: + case 145 /* FunctionType */: + case 146 /* ConstructorType */: + case 203 /* FunctionDeclaration */: + case 136 /* MethodDeclaration */: + case 135 /* MethodSignature */: + case 137 /* Constructor */: + case 140 /* CallSignature */: + case 141 /* ConstructSignature */: + case 142 /* IndexSignature */: + case 138 /* GetAccessor */: + case 139 /* SetAccessor */: + case 165 /* FunctionExpression */: + case 166 /* ArrowFunction */: // 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). @@ -13761,8 +15339,8 @@ var ts; // 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 === 136 /* Constructor */ || signature.declaration.kind === 140 /* ConstructSignature */; - var type = createObjectType(32768 /* Anonymous */ | 65536 /* FromSignature */); + var isConstructor = signature.declaration.kind === 137 /* Constructor */ || signature.declaration.kind === 141 /* ConstructSignature */; + var type = createObjectType(32768 /* Anonymous */ | 131072 /* FromSignature */); type.members = emptySymbols; type.properties = emptyArray; type.callSignatures = !isConstructor ? [signature] : emptyArray; @@ -13775,7 +15353,7 @@ var ts; return symbol.members["__index"]; } function getIndexDeclarationOfSymbol(symbol, kind) { - var syntaxKind = kind === 1 /* Number */ ? 120 /* NumberKeyword */ : 122 /* StringKeyword */; + var syntaxKind = kind === 1 /* Number */ ? 121 /* NumberKeyword */ : 123 /* StringKeyword */; var indexSymbol = getIndexSymbol(symbol); if (indexSymbol) { var len = indexSymbol.declarations.length; @@ -13805,11 +15383,14 @@ var ts; type.constraint = targetConstraint ? instantiateType(targetConstraint, type.mapper) : noConstraintType; } else { - type.constraint = getTypeFromTypeNode(ts.getDeclarationOfKind(type.symbol, 129 /* TypeParameter */).constraint); + type.constraint = getTypeFromTypeNode(ts.getDeclarationOfKind(type.symbol, 130 /* TypeParameter */).constraint); } } return type.constraint === noConstraintType ? undefined : type.constraint; } + function getParentSymbolOfTypeParameter(typeParameter) { + return getSymbolOfNode(ts.getDeclarationOfKind(typeParameter.symbol, 130 /* TypeParameter */).parent); + } function getTypeListId(types) { switch (types.length) { case 1: @@ -13836,7 +15417,7 @@ var ts; var type = types[_i]; result |= type.flags; } - return result & 786432 /* RequiresWidening */; + return result & 1572864 /* RequiresWidening */; } function createTypeReference(target, typeArguments) { var id = getTypeListId(typeArguments); @@ -13861,13 +15442,13 @@ var ts; currentNode = currentNode.parent; } // if last step was made from the type parameter this means that path has started somewhere in constraint which is illegal - links.isIllegalTypeReferenceInConstraint = currentNode.kind === 129 /* TypeParameter */; + links.isIllegalTypeReferenceInConstraint = currentNode.kind === 130 /* TypeParameter */; return links.isIllegalTypeReferenceInConstraint; } function checkTypeParameterHasIllegalReferencesInConstraint(typeParameter) { var typeParameterSymbol; function check(n) { - if (n.kind === 142 /* TypeReference */ && n.typeName.kind === 65 /* Identifier */) { + if (n.kind === 144 /* TypeReference */ && n.typeName.kind === 65 /* Identifier */) { var links = getNodeLinks(n); if (links.isIllegalTypeReferenceInConstraint === undefined) { var symbol = resolveName(typeParameter, n.typeName.text, 793056 /* Type */, undefined, undefined); @@ -13879,7 +15460,7 @@ var ts; // -> typeParameter and symbol.declaration originate from the same type parameter list // -> illegal for all declarations in symbol // forEach === exists - links.isIllegalTypeReferenceInConstraint = ts.forEach(symbol.declarations, function (d) { return d.parent == typeParameter.parent; }); + links.isIllegalTypeReferenceInConstraint = ts.forEach(symbol.declarations, function (d) { return d.parent === typeParameter.parent; }); } } if (links.isIllegalTypeReferenceInConstraint) { @@ -13893,47 +15474,79 @@ var ts; check(typeParameter.constraint); } } - function getTypeFromTypeReferenceOrExpressionWithTypeArguments(node) { + // Get type from reference to class or interface + function getTypeFromClassOrInterfaceReference(node, symbol) { + var type = getDeclaredTypeOfSymbol(symbol); + var typeParameters = type.localTypeParameters; + if (typeParameters) { + if (!node.typeArguments || node.typeArguments.length !== typeParameters.length) { + error(node, ts.Diagnostics.Generic_type_0_requires_1_type_argument_s, typeToString(type, undefined, 1 /* WriteArrayAsGenericType */), 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. + return createTypeReference(type, ts.concatenate(type.outerTypeParameters, ts.map(node.typeArguments, getTypeFromTypeNode))); + } + if (node.typeArguments) { + error(node, ts.Diagnostics.Type_0_is_not_generic, typeToString(type)); + return unknownType; + } + return type; + } + // Get type from reference to type alias. When a type alias is generic, the declared type of the type alias may include + // references to the type parameters of the alias. We replace those with the actual type arguments by instantiating the + // declared type. Instantiations are cached using the type identities of the type arguments as the key. + function getTypeFromTypeAliasReference(node, symbol) { + var type = getDeclaredTypeOfSymbol(symbol); + var links = getSymbolLinks(symbol); + var typeParameters = links.typeParameters; + if (typeParameters) { + if (!node.typeArguments || node.typeArguments.length !== typeParameters.length) { + error(node, ts.Diagnostics.Generic_type_0_requires_1_type_argument_s, symbolToString(symbol), typeParameters.length); + return unknownType; + } + var typeArguments = ts.map(node.typeArguments, getTypeFromTypeNode); + var id = getTypeListId(typeArguments); + return links.instantiations[id] || (links.instantiations[id] = instantiateType(type, createTypeMapper(typeParameters, 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 (symbol.flags & 262144 /* TypeParameter */ && isTypeParameterReferenceIllegalInConstraint(node, symbol)) { + // TypeScript 1.0 spec (April 2014): 3.4.1 + // Type parameters declared in a particular type parameter list + // may not be referenced in constraints in that type parameter list + // Implementation: such type references are resolved to 'unknown' type that usually denotes error + return unknownType; + } + if (node.typeArguments) { + error(node, ts.Diagnostics.Type_0_is_not_generic, symbolToString(symbol)); + return unknownType; + } + return getDeclaredTypeOfSymbol(symbol); + } + function getTypeFromTypeReference(node) { var links = getNodeLinks(node); if (!links.resolvedType) { - var type; - // We don't currently support heritage clauses with complex expressions in them. - // For these cases, we just set the type to be the unknownType. - if (node.kind !== 177 /* ExpressionWithTypeArguments */ || ts.isSupportedExpressionWithTypeArguments(node)) { - var typeNameOrExpression = node.kind === 142 /* TypeReference */ - ? node.typeName - : node.expression; - var symbol = resolveEntityName(typeNameOrExpression, 793056 /* Type */); - if (symbol) { - if ((symbol.flags & 262144 /* TypeParameter */) && isTypeParameterReferenceIllegalInConstraint(node, symbol)) { - // TypeScript 1.0 spec (April 2014): 3.4.1 - // Type parameters declared in a particular type parameter list - // may not be referenced in constraints in that type parameter list - // Implementation: such type references are resolved to 'unknown' type that usually denotes error - type = unknownType; - } - else { - type = getDeclaredTypeOfSymbol(symbol); - if (type.flags & (1024 /* Class */ | 2048 /* Interface */) && type.flags & 4096 /* Reference */) { - var typeParameters = type.typeParameters; - if (node.typeArguments && node.typeArguments.length === typeParameters.length) { - type = createTypeReference(type, ts.map(node.typeArguments, getTypeFromTypeNode)); - } - else { - error(node, ts.Diagnostics.Generic_type_0_requires_1_type_argument_s, typeToString(type, undefined, 1 /* WriteArrayAsGenericType */), typeParameters.length); - type = undefined; - } - } - else { - if (node.typeArguments) { - error(node, ts.Diagnostics.Type_0_is_not_generic, typeToString(type)); - type = undefined; - } - } - } - } - } - links.resolvedType = type || unknownType; + // We only support expressions that are simple qualified names. For other expressions this produces undefined. + var typeNameOrExpression = node.kind === 144 /* TypeReference */ ? node.typeName : + ts.isSupportedExpressionWithTypeArguments(node) ? node.expression : + undefined; + var symbol = typeNameOrExpression && resolveEntityName(typeNameOrExpression, 793056 /* Type */) || unknownSymbol; + var type = symbol === unknownSymbol ? unknownType : + symbol.flags & (32 /* Class */ | 64 /* Interface */) ? getTypeFromClassOrInterfaceReference(node, symbol) : + symbol.flags & 524288 /* TypeAlias */ ? getTypeFromTypeAliasReference(node, symbol) : + getTypeFromNonGenericTypeReference(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; } @@ -13944,7 +15557,7 @@ var ts; // 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(checkExpressionOrQualifiedName(node.exprName)); + links.resolvedType = getWidenedType(checkExpression(node.exprName)); } return links.resolvedType; } @@ -13954,24 +15567,24 @@ var ts; for (var _i = 0; _i < declarations.length; _i++) { var declaration = declarations[_i]; switch (declaration.kind) { - case 202 /* ClassDeclaration */: - case 203 /* InterfaceDeclaration */: - case 205 /* EnumDeclaration */: + case 204 /* ClassDeclaration */: + case 205 /* InterfaceDeclaration */: + case 207 /* EnumDeclaration */: return declaration; } } } if (!symbol) { - return emptyObjectType; + return arity ? emptyGenericType : emptyObjectType; } var type = getDeclaredTypeOfSymbol(symbol); if (!(type.flags & 48128 /* ObjectType */)) { error(getTypeDeclaration(symbol), ts.Diagnostics.Global_type_0_must_be_a_class_or_interface_type, symbol.name); - return emptyObjectType; + return arity ? emptyGenericType : emptyObjectType; } if ((type.typeParameters ? type.typeParameters.length : 0) !== arity) { error(getTypeDeclaration(symbol), ts.Diagnostics.Global_type_0_must_have_1_type_parameter_s, symbol.name, arity); - return emptyObjectType; + return arity ? emptyGenericType : emptyObjectType; } return type; } @@ -13991,15 +15604,20 @@ var ts; function getGlobalESSymbolConstructorSymbol() { return globalESSymbolConstructorSymbol || (globalESSymbolConstructorSymbol = getGlobalValueSymbol("Symbol")); } + /** + * Instantiates a global type that is generic with some element type, and returns that instantiation. + */ + function createTypeFromGenericGlobalType(genericGlobalType, elementType) { + return genericGlobalType !== emptyGenericType ? createTypeReference(genericGlobalType, [elementType]) : emptyObjectType; + } function createIterableType(elementType) { - return globalIterableType !== emptyObjectType ? createTypeReference(globalIterableType, [elementType]) : emptyObjectType; + return createTypeFromGenericGlobalType(globalIterableType, elementType); + } + function createIterableIteratorType(elementType) { + return createTypeFromGenericGlobalType(globalIterableIteratorType, elementType); } function createArrayType(elementType) { - // globalArrayType will be undefined if we get here during creation of the Array type. This for example happens if - // user code augments the Array type with call or construct signatures that have an array type as the return type. - // We instead use globalArraySymbol to obtain the (not yet fully constructed) Array type. - var arrayType = globalArrayType || getDeclaredTypeOfSymbol(globalArraySymbol); - return arrayType !== emptyObjectType ? createTypeReference(arrayType, [elementType]) : emptyObjectType; + return createTypeFromGenericGlobalType(globalArrayType, elementType); } function getTypeFromArrayTypeNode(node) { var links = getNodeLinks(node); @@ -14054,17 +15672,7 @@ var ts; } return false; } - // Since removeSubtypes checks the subtype relation, and the subtype relation on a union - // may attempt to reduce a union, it is possible that removeSubtypes could be called - // recursively on the same set of types. The removeSubtypesStack is used to track which - // sets of types are currently undergoing subtype reduction. - var removeSubtypesStack = []; function removeSubtypes(types) { - var typeListId = getTypeListId(types); - if (removeSubtypesStack.lastIndexOf(typeListId) >= 0) { - return; - } - removeSubtypesStack.push(typeListId); var i = types.length; while (i > 0) { i--; @@ -14072,12 +15680,11 @@ var ts; types.splice(i, 1); } } - removeSubtypesStack.pop(); } - function containsAnyType(types) { + function containsTypeAny(types) { for (var _i = 0; _i < types.length; _i++) { var type = types[_i]; - if (type.flags & 1 /* Any */) { + if (isTypeAny(type)) { return true; } } @@ -14103,7 +15710,7 @@ var ts; var sortedTypes = []; addTypesToSortedSet(sortedTypes, types); if (noSubtypeReduction) { - if (containsAnyType(sortedTypes)) { + if (containsTypeAny(sortedTypes)) { return anyType; } removeAllButLast(sortedTypes, undefinedType); @@ -14124,10 +15731,20 @@ var ts; } return type; } + // Subtype reduction is basically an optimization we do to avoid excessively large union types, which take longer + // to process and look strange in quick info and error messages. Semantically there is no difference between the + // reduced type and the type itself. So, when we detect a circularity we simply say that the reduced type is the + // type itself. function getReducedTypeOfUnionType(type) { - // If union type was created without subtype reduction, perform the deferred reduction now if (!type.reducedType) { - type.reducedType = getUnionType(type.types, false); + type.reducedType = circularType; + var reducedType = getUnionType(type.types, false); + if (type.reducedType === circularType) { + type.reducedType = reducedType; + } + } + else if (type.reducedType === circularType) { + type.reducedType = type; } return type.reducedType; } @@ -14165,40 +15782,42 @@ var ts; switch (node.kind) { case 112 /* AnyKeyword */: return anyType; - case 122 /* StringKeyword */: + case 123 /* StringKeyword */: return stringType; - case 120 /* NumberKeyword */: + case 121 /* NumberKeyword */: return numberType; case 113 /* BooleanKeyword */: return booleanType; - case 123 /* SymbolKeyword */: + case 124 /* SymbolKeyword */: return esSymbolType; case 99 /* VoidKeyword */: return voidType; case 8 /* StringLiteral */: return getTypeFromStringLiteral(node); - case 142 /* TypeReference */: - return getTypeFromTypeReferenceOrExpressionWithTypeArguments(node); - case 177 /* ExpressionWithTypeArguments */: - return getTypeFromTypeReferenceOrExpressionWithTypeArguments(node); - case 145 /* TypeQuery */: + case 144 /* TypeReference */: + return getTypeFromTypeReference(node); + case 143 /* TypePredicate */: + return booleanType; + case 179 /* ExpressionWithTypeArguments */: + return getTypeFromTypeReference(node); + case 147 /* TypeQuery */: return getTypeFromTypeQueryNode(node); - case 147 /* ArrayType */: + case 149 /* ArrayType */: return getTypeFromArrayTypeNode(node); - case 148 /* TupleType */: + case 150 /* TupleType */: return getTypeFromTupleTypeNode(node); - case 149 /* UnionType */: + case 151 /* UnionType */: return getTypeFromUnionTypeNode(node); - case 150 /* ParenthesizedType */: + case 152 /* ParenthesizedType */: return getTypeFromTypeNode(node.type); - case 143 /* FunctionType */: - case 144 /* ConstructorType */: - case 146 /* TypeLiteral */: + case 145 /* FunctionType */: + case 146 /* ConstructorType */: + case 148 /* TypeLiteral */: return getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node); // This function assumes that an identifier or qualified name is a type expression // Callers should first ensure this by calling isTypeNode case 65 /* Identifier */: - case 127 /* QualifiedName */: + case 128 /* QualifiedName */: var symbol = getSymbolInfo(node); return symbol && getDeclaredTypeOfSymbol(symbol); default: @@ -14288,11 +15907,19 @@ var ts; } function instantiateSignature(signature, mapper, eraseTypeParameters) { var freshTypeParameters; + var freshTypePredicate; if (signature.typeParameters && !eraseTypeParameters) { freshTypeParameters = instantiateList(signature.typeParameters, mapper, instantiateTypeParameter); mapper = combineTypeMappers(createTypeMapper(signature.typeParameters, freshTypeParameters), mapper); } - var result = createSignature(signature.declaration, freshTypeParameters, instantiateList(signature.parameters, mapper, instantiateSymbol), signature.resolvedReturnType ? instantiateType(signature.resolvedReturnType, mapper) : undefined, signature.minArgumentCount, signature.hasRestParameter, signature.hasStringLiterals); + if (signature.typePredicate) { + freshTypePredicate = { + parameterName: signature.typePredicate.parameterName, + parameterIndex: signature.typePredicate.parameterIndex, + type: instantiateType(signature.typePredicate.type, mapper) + }; + } + var result = createSignature(signature.declaration, freshTypeParameters, instantiateList(signature.parameters, mapper, instantiateSymbol), signature.resolvedReturnType ? instantiateType(signature.resolvedReturnType, mapper) : undefined, freshTypePredicate, signature.minArgumentCount, signature.hasRestParameter, signature.hasStringLiterals); result.target = signature; result.mapper = mapper; return result; @@ -14319,7 +15946,8 @@ var ts; return result; } function instantiateAnonymousType(type, mapper) { - var result = createObjectType(32768 /* Anonymous */, type.symbol); + // Mark the anonymous type as instantiated such that our infinite instantiation detection logic can recognize it + var result = createObjectType(32768 /* Anonymous */ | 65536 /* Instantiated */, type.symbol); result.properties = instantiateList(getPropertiesOfObjectType(type), mapper, instantiateSymbol); result.members = createSymbolTable(result.properties); result.callSignatures = instantiateList(getSignaturesOfType(type, 0 /* Call */), mapper, instantiateSignature); @@ -14338,7 +15966,7 @@ var ts; return mapper(type); } if (type.flags & 32768 /* Anonymous */) { - return type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) ? + return type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) ? instantiateAnonymousType(type, mapper) : type; } if (type.flags & 4096 /* Reference */) { @@ -14356,27 +15984,27 @@ var ts; // Returns true if the given expression contains (at any level of nesting) a function or arrow expression // that is subject to contextual typing. function isContextSensitive(node) { - ts.Debug.assert(node.kind !== 135 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); + ts.Debug.assert(node.kind !== 136 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); switch (node.kind) { - case 163 /* FunctionExpression */: - case 164 /* ArrowFunction */: + case 165 /* FunctionExpression */: + case 166 /* ArrowFunction */: return isContextSensitiveFunctionLikeDeclaration(node); - case 155 /* ObjectLiteralExpression */: + case 157 /* ObjectLiteralExpression */: return ts.forEach(node.properties, isContextSensitive); - case 154 /* ArrayLiteralExpression */: + case 156 /* ArrayLiteralExpression */: return ts.forEach(node.elements, isContextSensitive); - case 171 /* ConditionalExpression */: + case 173 /* ConditionalExpression */: return isContextSensitive(node.whenTrue) || isContextSensitive(node.whenFalse); - case 170 /* BinaryExpression */: + case 172 /* BinaryExpression */: return node.operatorToken.kind === 49 /* BarBarToken */ && (isContextSensitive(node.left) || isContextSensitive(node.right)); - case 225 /* PropertyAssignment */: + case 227 /* PropertyAssignment */: return isContextSensitive(node.initializer); - case 135 /* MethodDeclaration */: - case 134 /* MethodSignature */: + case 136 /* MethodDeclaration */: + case 135 /* MethodSignature */: return isContextSensitiveFunctionLikeDeclaration(node); - case 162 /* ParenthesizedExpression */: + case 164 /* ParenthesizedExpression */: return isContextSensitive(node.expression); } return false; @@ -14384,14 +16012,14 @@ var ts; function isContextSensitiveFunctionLikeDeclaration(node) { return !node.typeParameters && node.parameters.length && !ts.forEach(node.parameters, function (p) { return p.type; }); } - function getTypeWithoutConstructors(type) { + function getTypeWithoutSignatures(type) { if (type.flags & 48128 /* ObjectType */) { var resolved = resolveObjectOrUnionTypeMembers(type); if (resolved.constructSignatures.length) { var result = createObjectType(32768 /* Anonymous */, type.symbol); result.members = resolved.members; result.properties = resolved.properties; - result.callSignatures = resolved.callSignatures; + result.callSignatures = emptyArray; result.constructSignatures = emptyArray; type = result; } @@ -14399,9 +16027,6 @@ var ts; return type; } // TYPE CHECKING - var subtypeRelation = {}; - var assignableRelation = {}; - var identityRelation = {}; function isTypeIdenticalTo(source, target) { return checkTypeRelatedTo(source, target, identityRelation, undefined); } @@ -14468,7 +16093,7 @@ var ts; if (source === target) return -1 /* True */; if (relation !== identityRelation) { - if (target.flags & 1 /* Any */) + if (isTypeAny(target)) return -1 /* True */; if (source === undefinedType) return -1 /* True */; @@ -14479,7 +16104,7 @@ var ts; if (source.flags & 256 /* StringLiteral */ && target === stringType) return -1 /* True */; if (relation === assignableRelation) { - if (source.flags & 1 /* Any */) + if (isTypeAny(source)) return -1 /* True */; if (source === numberType && target.flags & 128 /* Enum */) return -1 /* True */; @@ -14678,9 +16303,9 @@ var ts; maybeStack[depth][id] = 1 /* Succeeded */; depth++; var saveExpandingFlags = expandingFlags; - if (!(expandingFlags & 1) && isDeeplyNestedGeneric(source, sourceStack)) + if (!(expandingFlags & 1) && isDeeplyNestedGeneric(source, sourceStack, depth)) expandingFlags |= 1; - if (!(expandingFlags & 2) && isDeeplyNestedGeneric(target, targetStack)) + if (!(expandingFlags & 2) && isDeeplyNestedGeneric(target, targetStack, depth)) expandingFlags |= 2; var result; if (expandingFlags === 3) { @@ -14716,33 +16341,13 @@ var ts; } return result; } - // Return true if the given type is part of a deeply nested chain of generic instantiations. We consider this to be the case - // when structural type comparisons have been started for 10 or more instantiations of the same generic type. 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 10 levels, but unequal at - // some level beyond that. - function isDeeplyNestedGeneric(type, stack) { - if (type.flags & 4096 /* Reference */ && depth >= 10) { - var target_1 = type.target; - var count = 0; - for (var i = 0; i < depth; i++) { - var t = stack[i]; - if (t.flags & 4096 /* Reference */ && t.target === target_1) { - count++; - if (count >= 10) - return true; - } - } - } - return 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 && !(source.flags & 131072 /* ObjectLiteral */); + var requireOptionalProperties = relation === subtypeRelation && !(source.flags & 262144 /* ObjectLiteral */); for (var _i = 0; _i < properties.length; _i++) { var targetProp = properties[_i]; var sourceProp = getPropertyOfType(source, targetProp.name); @@ -14848,11 +16453,11 @@ var ts; var saveErrorInfo = errorInfo; outer: for (var _i = 0; _i < targetSignatures.length; _i++) { var t = targetSignatures[_i]; - if (!t.hasStringLiterals || target.flags & 65536 /* FromSignature */) { + if (!t.hasStringLiterals || target.flags & 131072 /* FromSignature */) { var localErrors = reportErrors; for (var _a = 0; _a < sourceSignatures.length; _a++) { var s = sourceSignatures[_a]; - if (!s.hasStringLiterals || source.flags & 65536 /* FromSignature */) { + if (!s.hasStringLiterals || source.flags & 131072 /* FromSignature */) { var related = signatureRelatedTo(s, t, localErrors); if (related) { result &= related; @@ -14916,6 +16521,33 @@ var ts; } result &= related; } + if (source.typePredicate && target.typePredicate) { + var hasDifferentParameterIndex = source.typePredicate.parameterIndex !== target.typePredicate.parameterIndex; + var hasDifferentTypes; + if (hasDifferentParameterIndex || + (hasDifferentTypes = !isTypeIdenticalTo(source.typePredicate.type, target.typePredicate.type))) { + if (reportErrors) { + var sourceParamText = source.typePredicate.parameterName; + var targetParamText = target.typePredicate.parameterName; + var sourceTypeText = typeToString(source.typePredicate.type); + var targetTypeText = typeToString(target.typePredicate.type); + if (hasDifferentParameterIndex) { + reportError(ts.Diagnostics.Parameter_0_is_not_in_the_same_position_as_parameter_1, sourceParamText, targetParamText); + } + else if (hasDifferentTypes) { + reportError(ts.Diagnostics.Type_0_is_not_assignable_to_type_1, sourceTypeText, targetTypeText); + } + reportError(ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1, sourceParamText + " is " + sourceTypeText, targetParamText + " is " + targetTypeText); + } + return 0 /* False */; + } + } + else if (!source.typePredicate && target.typePredicate) { + if (reportErrors) { + reportError(ts.Diagnostics.Signature_0_must_have_a_type_predicate, signatureToString(source)); + } + return 0 /* False */; + } var t = getReturnTypeOfSignature(target); if (t === voidType) return result; @@ -15006,6 +16638,27 @@ var ts; return 0 /* False */; } } + // Return true if the given type is part of a deeply nested chain of generic instantiations. We consider this to be the case + // when structural type comparisons have been started for 10 or more instantiations of the same generic type. 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 10 levels, but unequal at + // some level beyond that. + function isDeeplyNestedGeneric(type, stack, depth) { + // We track type references (created by createTypeReference) and instantiated types (created by instantiateType) + if (type.flags & (4096 /* Reference */ | 65536 /* Instantiated */) && depth >= 5) { + var symbol = type.symbol; + var count = 0; + for (var i = 0; i < depth; i++) { + var t = stack[i]; + if (t.flags & (4096 /* Reference */ | 65536 /* Instantiated */) && t.symbol === symbol) { + count++; + if (count >= 5) + return true; + } + } + } + return false; + } function isPropertyIdenticalTo(sourceProp, targetProp) { return compareProperties(sourceProp, targetProp, compareTypes) !== 0 /* False */; } @@ -15164,11 +16817,11 @@ var ts; return createAnonymousType(type.symbol, members, emptyArray, emptyArray, stringIndexType, numberIndexType); } function getWidenedType(type) { - if (type.flags & 786432 /* RequiresWidening */) { + if (type.flags & 1572864 /* RequiresWidening */) { if (type.flags & (32 /* Undefined */ | 64 /* Null */)) { return anyType; } - if (type.flags & 131072 /* ObjectLiteral */) { + if (type.flags & 262144 /* ObjectLiteral */) { return getWidenedTypeOfObjectLiteral(type); } if (type.flags & 16384 /* Union */) { @@ -15193,11 +16846,11 @@ var ts; if (isArrayType(type)) { return reportWideningErrorsInType(type.typeArguments[0]); } - if (type.flags & 131072 /* ObjectLiteral */) { + if (type.flags & 262144 /* ObjectLiteral */) { var errorReported = false; ts.forEach(getPropertiesOfObjectType(type), function (p) { var t = getTypeOfSymbol(p); - if (t.flags & 262144 /* ContainsUndefinedOrNull */) { + if (t.flags & 524288 /* ContainsUndefinedOrNull */) { if (!reportWideningErrorsInType(t)) { error(p.valueDeclaration, ts.Diagnostics.Object_literal_s_property_0_implicitly_has_an_1_type, p.name, typeToString(getWidenedType(t))); } @@ -15212,22 +16865,22 @@ var ts; var typeAsString = typeToString(getWidenedType(type)); var diagnostic; switch (declaration.kind) { - case 133 /* PropertyDeclaration */: - case 132 /* PropertySignature */: + case 134 /* PropertyDeclaration */: + case 133 /* PropertySignature */: diagnostic = ts.Diagnostics.Member_0_implicitly_has_an_1_type; break; - case 130 /* Parameter */: + case 131 /* 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 201 /* FunctionDeclaration */: - case 135 /* MethodDeclaration */: - case 134 /* MethodSignature */: - case 137 /* GetAccessor */: - case 138 /* SetAccessor */: - case 163 /* FunctionExpression */: - case 164 /* ArrowFunction */: + case 203 /* FunctionDeclaration */: + case 136 /* MethodDeclaration */: + case 135 /* MethodSignature */: + case 138 /* GetAccessor */: + case 139 /* SetAccessor */: + case 165 /* FunctionExpression */: + case 166 /* ArrowFunction */: if (!declaration.name) { error(declaration, ts.Diagnostics.Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeAsString); return; @@ -15240,7 +16893,7 @@ var ts; error(declaration, diagnostic, ts.declarationNameToString(declaration.name), typeAsString); } function reportErrorsFromWidening(declaration, type) { - if (produceDiagnostics && compilerOptions.noImplicitAny && type.flags & 262144 /* ContainsUndefinedOrNull */) { + if (produceDiagnostics && compilerOptions.noImplicitAny && type.flags & 524288 /* ContainsUndefinedOrNull */) { // Report implicit any error within type if possible, otherwise report error on declaration if (!reportWideningErrorsInType(type)) { reportImplicitAnyError(declaration, type); @@ -15300,20 +16953,6 @@ var ts; } return false; } - function isWithinDepthLimit(type, stack) { - if (depth >= 5) { - var target_2 = type.target; - var count = 0; - for (var i = 0; i < depth; i++) { - var t = stack[i]; - if (t.flags & 4096 /* Reference */ && t.target === target_2) { - count++; - } - } - return count < 5; - } - return true; - } function inferFromTypes(source, target) { if (source === anyFunctionType) { return; @@ -15383,22 +17022,26 @@ var ts; else if (source.flags & 48128 /* ObjectType */ && (target.flags & (4096 /* Reference */ | 8192 /* Tuple */) || (target.flags & 32768 /* Anonymous */) && target.symbol && target.symbol.flags & (8192 /* Method */ | 2048 /* TypeLiteral */))) { // If source is an object type, and target is a type reference, a tuple type, the type of a method, or a type literal, infer from members - if (!isInProcess(source, target) && isWithinDepthLimit(source, sourceStack) && isWithinDepthLimit(target, targetStack)) { - if (depth === 0) { - sourceStack = []; - targetStack = []; - } - sourceStack[depth] = source; - targetStack[depth] = target; - depth++; - inferFromProperties(source, target); - inferFromSignatures(source, target, 0 /* Call */); - inferFromSignatures(source, target, 1 /* Construct */); - inferFromIndexTypes(source, target, 0 /* String */, 0 /* String */); - inferFromIndexTypes(source, target, 1 /* Number */, 1 /* Number */); - inferFromIndexTypes(source, target, 0 /* String */, 1 /* Number */); - depth--; + if (isInProcess(source, target)) { + return; } + if (isDeeplyNestedGeneric(source, sourceStack, depth) && isDeeplyNestedGeneric(target, targetStack, depth)) { + return; + } + if (depth === 0) { + sourceStack = []; + targetStack = []; + } + sourceStack[depth] = source; + targetStack[depth] = target; + depth++; + inferFromProperties(source, target); + inferFromSignatures(source, target, 0 /* Call */); + inferFromSignatures(source, target, 1 /* Construct */); + inferFromIndexTypes(source, target, 0 /* String */, 0 /* String */); + inferFromIndexTypes(source, target, 1 /* Number */, 1 /* Number */); + inferFromIndexTypes(source, target, 0 /* String */, 1 /* Number */); + depth--; } } function inferFromProperties(source, target) { @@ -15423,7 +17066,17 @@ var ts; } function inferFromSignature(source, target) { forEachMatchingParameterType(source, target, inferFromTypes); - inferFromTypes(getReturnTypeOfSignature(source), getReturnTypeOfSignature(target)); + if (source.typePredicate && target.typePredicate) { + if (target.typePredicate.parameterIndex === source.typePredicate.parameterIndex) { + // Return types from type predicates are treated as booleans. In order to infer types + // from type predicates we would need to infer using the type within the type predicate + // (i.e. 'Foo' from 'x is Foo'). + inferFromTypes(source.typePredicate.type, target.typePredicate.type); + } + } + else { + inferFromTypes(getReturnTypeOfSignature(source), getReturnTypeOfSignature(target)); + } } function inferFromIndexTypes(source, target, sourceKind, targetKind) { var targetIndexType = getIndexTypeOfType(target, targetKind); @@ -15496,10 +17149,10 @@ var ts; // The expression is restricted to a single identifier or a sequence of identifiers separated by periods while (node) { switch (node.kind) { - case 145 /* TypeQuery */: + case 147 /* TypeQuery */: return true; case 65 /* Identifier */: - case 127 /* QualifiedName */: + case 128 /* QualifiedName */: node = node.parent; continue; default: @@ -15547,7 +17200,7 @@ var ts; function isAssignedInBinaryExpression(node) { if (node.operatorToken.kind >= 53 /* FirstAssignment */ && node.operatorToken.kind <= 64 /* LastAssignment */) { var n = node.left; - while (n.kind === 162 /* ParenthesizedExpression */) { + while (n.kind === 164 /* ParenthesizedExpression */) { n = n.expression; } if (n.kind === 65 /* Identifier */ && getResolvedSymbol(n) === symbol) { @@ -15564,46 +17217,46 @@ var ts; } function isAssignedIn(node) { switch (node.kind) { - case 170 /* BinaryExpression */: + case 172 /* BinaryExpression */: return isAssignedInBinaryExpression(node); - case 199 /* VariableDeclaration */: - case 153 /* BindingElement */: + case 201 /* VariableDeclaration */: + case 155 /* BindingElement */: return isAssignedInVariableDeclaration(node); - case 151 /* ObjectBindingPattern */: - case 152 /* ArrayBindingPattern */: - case 154 /* ArrayLiteralExpression */: - case 155 /* ObjectLiteralExpression */: - case 156 /* PropertyAccessExpression */: - case 157 /* ElementAccessExpression */: - case 158 /* CallExpression */: - case 159 /* NewExpression */: - case 161 /* TypeAssertionExpression */: - case 162 /* ParenthesizedExpression */: - case 168 /* PrefixUnaryExpression */: - case 165 /* DeleteExpression */: - case 166 /* TypeOfExpression */: - case 167 /* VoidExpression */: - case 169 /* PostfixUnaryExpression */: - case 171 /* ConditionalExpression */: - case 174 /* SpreadElementExpression */: - case 180 /* Block */: - case 181 /* VariableStatement */: - case 183 /* ExpressionStatement */: - case 184 /* IfStatement */: - case 185 /* DoStatement */: - case 186 /* WhileStatement */: - case 187 /* ForStatement */: - case 188 /* ForInStatement */: - case 189 /* ForOfStatement */: - case 192 /* ReturnStatement */: - case 193 /* WithStatement */: - case 194 /* SwitchStatement */: - case 221 /* CaseClause */: - case 222 /* DefaultClause */: - case 195 /* LabeledStatement */: - case 196 /* ThrowStatement */: - case 197 /* TryStatement */: - case 224 /* CatchClause */: + case 153 /* ObjectBindingPattern */: + case 154 /* ArrayBindingPattern */: + case 156 /* ArrayLiteralExpression */: + case 157 /* ObjectLiteralExpression */: + case 158 /* PropertyAccessExpression */: + case 159 /* ElementAccessExpression */: + case 160 /* CallExpression */: + case 161 /* NewExpression */: + case 163 /* TypeAssertionExpression */: + case 164 /* ParenthesizedExpression */: + case 170 /* PrefixUnaryExpression */: + case 167 /* DeleteExpression */: + case 168 /* TypeOfExpression */: + case 169 /* VoidExpression */: + case 171 /* PostfixUnaryExpression */: + case 173 /* ConditionalExpression */: + case 176 /* SpreadElementExpression */: + case 182 /* Block */: + case 183 /* VariableStatement */: + case 185 /* ExpressionStatement */: + case 186 /* IfStatement */: + case 187 /* DoStatement */: + case 188 /* WhileStatement */: + case 189 /* ForStatement */: + case 190 /* ForInStatement */: + case 191 /* ForOfStatement */: + case 194 /* ReturnStatement */: + case 195 /* WithStatement */: + case 196 /* SwitchStatement */: + case 223 /* CaseClause */: + case 224 /* DefaultClause */: + case 197 /* LabeledStatement */: + case 198 /* ThrowStatement */: + case 199 /* TryStatement */: + case 226 /* CatchClause */: return ts.forEachChild(node, isAssignedIn); } return false; @@ -15613,10 +17266,10 @@ var ts; // Resolve location from top down towards node if it is a context sensitive expression // That helps in making sure not assigning types as any when resolved out of order var containerNodes = []; - for (var parent_3 = node.parent; parent_3; parent_3 = parent_3.parent) { - if ((ts.isExpression(parent_3) || ts.isObjectLiteralMethod(node)) && - isContextSensitive(parent_3)) { - containerNodes.unshift(parent_3); + for (var parent_5 = node.parent; parent_5; parent_5 = parent_5.parent) { + if ((ts.isExpression(parent_5) || ts.isObjectLiteralMethod(node)) && + isContextSensitive(parent_5)) { + containerNodes.unshift(parent_5); } } ts.forEach(containerNodes, function (node) { getTypeOfNode(node); }); @@ -15649,59 +17302,61 @@ var ts; function getNarrowedTypeOfSymbol(symbol, node) { var type = getTypeOfSymbol(symbol); // Only narrow when symbol is variable of type any or an object, union, or type parameter type - if (node && symbol.flags & 3 /* Variable */ && type.flags & (1 /* Any */ | 48128 /* ObjectType */ | 16384 /* Union */ | 512 /* TypeParameter */)) { - loop: while (node.parent) { - var child = node; - node = node.parent; - var narrowedType = type; - switch (node.kind) { - case 184 /* IfStatement */: - // In a branch of an if statement, narrow based on controlling expression - if (child !== node.expression) { - narrowedType = narrowType(type, node.expression, child === node.thenStatement); - } - break; - case 171 /* ConditionalExpression */: - // In a branch of a conditional expression, narrow based on controlling condition - if (child !== node.condition) { - narrowedType = narrowType(type, node.condition, child === node.whenTrue); - } - break; - case 170 /* BinaryExpression */: - // In the right operand of an && or ||, narrow based on left operand - if (child === node.right) { - if (node.operatorToken.kind === 48 /* AmpersandAmpersandToken */) { - narrowedType = narrowType(type, node.left, true); + if (node && symbol.flags & 3 /* Variable */) { + if (isTypeAny(type) || type.flags & (48128 /* ObjectType */ | 16384 /* Union */ | 512 /* TypeParameter */)) { + loop: while (node.parent) { + var child = node; + node = node.parent; + var narrowedType = type; + switch (node.kind) { + case 186 /* IfStatement */: + // In a branch of an if statement, narrow based on controlling expression + if (child !== node.expression) { + narrowedType = narrowType(type, node.expression, child === node.thenStatement); } - else if (node.operatorToken.kind === 49 /* BarBarToken */) { - narrowedType = narrowType(type, node.left, false); + break; + case 173 /* ConditionalExpression */: + // In a branch of a conditional expression, narrow based on controlling condition + if (child !== node.condition) { + narrowedType = narrowType(type, node.condition, child === node.whenTrue); } - } - break; - case 228 /* SourceFile */: - case 206 /* ModuleDeclaration */: - case 201 /* FunctionDeclaration */: - case 135 /* MethodDeclaration */: - case 134 /* MethodSignature */: - case 137 /* GetAccessor */: - case 138 /* SetAccessor */: - case 136 /* Constructor */: - // Stop at the first containing function or module declaration - break loop; - } - // Use narrowed type if construct contains no assignments to variable - if (narrowedType !== type) { - if (isVariableAssignedWithin(symbol, node)) { - break; + break; + case 172 /* BinaryExpression */: + // In the right operand of an && or ||, narrow based on left operand + if (child === node.right) { + if (node.operatorToken.kind === 48 /* AmpersandAmpersandToken */) { + narrowedType = narrowType(type, node.left, true); + } + else if (node.operatorToken.kind === 49 /* BarBarToken */) { + narrowedType = narrowType(type, node.left, false); + } + } + break; + case 230 /* SourceFile */: + case 208 /* ModuleDeclaration */: + case 203 /* FunctionDeclaration */: + case 136 /* MethodDeclaration */: + case 135 /* MethodSignature */: + case 138 /* GetAccessor */: + case 139 /* SetAccessor */: + case 137 /* Constructor */: + // Stop at the first containing function or module declaration + break loop; + } + // Use narrowed type if construct contains no assignments to variable + if (narrowedType !== type) { + if (isVariableAssignedWithin(symbol, node)) { + break; + } + type = narrowedType; } - type = narrowedType; } } } return type; function narrowTypeByEquality(type, expr, assumeTrue) { // Check that we have 'typeof ' on the left and string literal on the right - if (expr.left.kind !== 166 /* TypeOfExpression */ || expr.right.kind !== 8 /* StringLiteral */) { + if (expr.left.kind !== 168 /* TypeOfExpression */ || expr.right.kind !== 8 /* StringLiteral */) { return type; } var left = expr.left; @@ -15716,7 +17371,7 @@ var ts; if (assumeTrue) { // Assumed result is true. If check was not for a primitive type, remove all primitive types if (!typeInfo) { - return removeTypesFromUnionType(type, 258 /* StringLike */ | 132 /* NumberLike */ | 8 /* Boolean */ | 1048576 /* ESSymbol */, + return removeTypesFromUnionType(type, 258 /* StringLike */ | 132 /* NumberLike */ | 8 /* Boolean */ | 2097152 /* ESSymbol */, /*isOfTypeKind*/ true, false); } // Check was for a primitive type, return that primitive type if it is a subtype @@ -15766,7 +17421,7 @@ var ts; } function narrowTypeByInstanceof(type, expr, assumeTrue) { // Check that type is not any, assumed result is true, and we have variable symbol on the left - if (type.flags & 1 /* Any */ || !assumeTrue || expr.left.kind !== 65 /* Identifier */ || getResolvedSymbol(expr.left) !== symbol) { + if (isTypeAny(type) || !assumeTrue || expr.left.kind !== 65 /* Identifier */ || getResolvedSymbol(expr.left) !== symbol) { return type; } // Check that right operand is a function type with a prototype property @@ -15777,9 +17432,9 @@ var ts; var targetType; var prototypeProperty = getPropertyOfType(rightType, "prototype"); if (prototypeProperty) { - // Target type is type of the protoype property + // Target type is type of the prototype property var prototypePropertyType = getTypeOfSymbol(prototypeProperty); - if (prototypePropertyType !== anyType) { + if (!isTypeAny(prototypePropertyType)) { targetType = prototypePropertyType; } } @@ -15797,14 +17452,36 @@ var ts; } } if (targetType) { - // Narrow to the target type if it's a subtype of the current type - if (isTypeSubtypeOf(targetType, type)) { - return targetType; - } - // If the current type is a union type, remove all constituents that aren't subtypes of the target. - if (type.flags & 16384 /* Union */) { - return getUnionType(ts.filter(type.types, function (t) { return isTypeSubtypeOf(t, targetType); })); + return getNarrowedType(type, targetType); + } + return type; + } + function getNarrowedType(originalType, narrowedTypeCandidate) { + // Narrow to the target type if it's a subtype of the current type + if (isTypeSubtypeOf(narrowedTypeCandidate, originalType)) { + return narrowedTypeCandidate; + } + // If the current type is a union type, remove all constituents that aren't subtypes of the target. + if (originalType.flags & 16384 /* Union */) { + return getUnionType(ts.filter(originalType.types, function (t) { return isTypeSubtypeOf(t, narrowedTypeCandidate); })); + } + return originalType; + } + function narrowTypeByTypePredicate(type, expr, assumeTrue) { + if (type.flags & 1 /* Any */) { + return type; + } + var signature = getResolvedSignature(expr); + if (signature.typePredicate && + expr.arguments[signature.typePredicate.parameterIndex] && + getSymbolAtLocation(expr.arguments[signature.typePredicate.parameterIndex]) === symbol) { + if (!assumeTrue) { + if (type.flags & 16384 /* Union */) { + return getUnionType(ts.filter(type.types, function (t) { return !isTypeSubtypeOf(t, signature.typePredicate.type); })); + } + return type; } + return getNarrowedType(type, signature.typePredicate.type); } return type; } @@ -15812,9 +17489,11 @@ var ts; // will be a subtype or the same type as the argument. function narrowType(type, expr, assumeTrue) { switch (expr.kind) { - case 162 /* ParenthesizedExpression */: + case 160 /* CallExpression */: + return narrowTypeByTypePredicate(type, expr, assumeTrue); + case 164 /* ParenthesizedExpression */: return narrowType(type, expr.expression, assumeTrue); - case 170 /* BinaryExpression */: + case 172 /* BinaryExpression */: var operator = expr.operatorToken.kind; if (operator === 30 /* EqualsEqualsEqualsToken */ || operator === 31 /* ExclamationEqualsEqualsToken */) { return narrowTypeByEquality(type, expr, assumeTrue); @@ -15829,7 +17508,7 @@ var ts; return narrowTypeByInstanceof(type, expr, assumeTrue); } break; - case 168 /* PrefixUnaryExpression */: + case 170 /* PrefixUnaryExpression */: if (expr.operator === 46 /* ExclamationToken */) { return narrowType(type, expr.operand, !assumeTrue); } @@ -15846,7 +17525,7 @@ var ts; // 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 && ts.getContainingFunction(node).kind === 164 /* ArrowFunction */ && languageVersion < 2 /* ES6 */) { + if (symbol === argumentsSymbol && ts.getContainingFunction(node).kind === 166 /* ArrowFunction */ && languageVersion < 2 /* ES6 */) { error(node, ts.Diagnostics.The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_standard_function_expression); } if (symbol.flags & 8388608 /* Alias */ && !isInTypeQuery(node) && !isConstEnumOrConstEnumOnlyModule(resolveAlias(symbol))) { @@ -15870,7 +17549,7 @@ var ts; function checkBlockScopedBindingCapturedInLoop(node, symbol) { if (languageVersion >= 2 /* ES6 */ || (symbol.flags & 2 /* BlockScopedVariable */) === 0 || - symbol.valueDeclaration.parent.kind === 224 /* CatchClause */) { + symbol.valueDeclaration.parent.kind === 226 /* CatchClause */) { return; } // - check if binding is used in some function @@ -15879,12 +17558,12 @@ var ts; // nesting structure: // (variable declaration or binding element) -> variable declaration list -> container var container = symbol.valueDeclaration; - while (container.kind !== 200 /* VariableDeclarationList */) { + while (container.kind !== 202 /* VariableDeclarationList */) { container = container.parent; } // get the parent of variable declaration list container = container.parent; - if (container.kind === 181 /* VariableStatement */) { + if (container.kind === 183 /* VariableStatement */) { // if parent is variable statement - get its parent container = container.parent; } @@ -15903,9 +17582,9 @@ var ts; } } function captureLexicalThis(node, container) { - var classNode = container.parent && container.parent.kind === 202 /* ClassDeclaration */ ? container.parent : undefined; + var classNode = container.parent && container.parent.kind === 204 /* ClassDeclaration */ ? container.parent : undefined; getNodeLinks(node).flags |= 2 /* LexicalThis */; - if (container.kind === 133 /* PropertyDeclaration */ || container.kind === 136 /* Constructor */) { + if (container.kind === 134 /* PropertyDeclaration */ || container.kind === 137 /* Constructor */) { getNodeLinks(classNode).flags |= 4 /* CaptureThis */; } else { @@ -15918,39 +17597,39 @@ var ts; var container = ts.getThisContainer(node, true); var needToCaptureLexicalThis = false; // Now skip arrow functions to get the "real" owner of 'this'. - if (container.kind === 164 /* ArrowFunction */) { + if (container.kind === 166 /* ArrowFunction */) { container = ts.getThisContainer(container, 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 /* ES6 */); } switch (container.kind) { - case 206 /* ModuleDeclaration */: + case 208 /* 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 205 /* EnumDeclaration */: + case 207 /* 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 136 /* Constructor */: + case 137 /* Constructor */: if (isInConstructorArgumentInitializer(node, container)) { error(node, ts.Diagnostics.this_cannot_be_referenced_in_constructor_arguments); } break; - case 133 /* PropertyDeclaration */: - case 132 /* PropertySignature */: + case 134 /* PropertyDeclaration */: + case 133 /* PropertySignature */: if (container.flags & 128 /* Static */) { error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_static_property_initializer); } break; - case 128 /* ComputedPropertyName */: + case 129 /* ComputedPropertyName */: error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_computed_property_name); break; } if (needToCaptureLexicalThis) { captureLexicalThis(node, container); } - var classNode = container.parent && container.parent.kind === 202 /* ClassDeclaration */ ? container.parent : undefined; + var classNode = container.parent && container.parent.kind === 204 /* ClassDeclaration */ ? container.parent : undefined; if (classNode) { var symbol = getSymbolOfNode(classNode); return container.flags & 128 /* Static */ ? getTypeOfSymbol(symbol) : getDeclaredTypeOfSymbol(symbol); @@ -15959,23 +17638,21 @@ var ts; } function isInConstructorArgumentInitializer(node, constructorDecl) { for (var n = node; n && n !== constructorDecl; n = n.parent) { - if (n.kind === 130 /* Parameter */) { + if (n.kind === 131 /* Parameter */) { return true; } } return false; } function checkSuperExpression(node) { - var isCallExpression = node.parent.kind === 158 /* CallExpression */ && node.parent.expression === node; - var enclosingClass = ts.getAncestor(node, 202 /* ClassDeclaration */); - var baseClass; - if (enclosingClass && ts.getClassExtendsHeritageClauseElement(enclosingClass)) { - var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(enclosingClass)); - var baseTypes = getBaseTypes(classType); - baseClass = baseTypes.length && baseTypes[0]; - } - if (!baseClass) { - error(node, ts.Diagnostics.super_can_only_be_referenced_in_a_derived_class); + var isCallExpression = node.parent.kind === 160 /* CallExpression */ && node.parent.expression === node; + var classDeclaration = ts.getAncestor(node, 204 /* ClassDeclaration */); + var classType = classDeclaration && getDeclaredTypeOfSymbol(getSymbolOfNode(classDeclaration)); + var baseClassType = classType && getBaseTypes(classType)[0]; + if (!baseClassType) { + if (!classDeclaration || !ts.getClassExtendsHeritageClauseElement(classDeclaration)) { + error(node, ts.Diagnostics.super_can_only_be_referenced_in_a_derived_class); + } return unknownType; } var container = ts.getSuperContainer(node, true); @@ -15985,7 +17662,7 @@ var ts; if (isCallExpression) { // TS 1.0 SPEC (April 2014): 4.8.1 // Super calls are only permitted in constructors of derived classes - canUseSuperExpression = container.kind === 136 /* Constructor */; + canUseSuperExpression = container.kind === 137 /* Constructor */; } else { // TS 1.0 SPEC (April 2014) @@ -15994,28 +17671,28 @@ var ts; // - In a static member function or static member accessor // super property access might appear in arrow functions with arbitrary deep nesting needToCaptureLexicalThis = false; - while (container && container.kind === 164 /* ArrowFunction */) { + while (container && container.kind === 166 /* ArrowFunction */) { container = ts.getSuperContainer(container, true); needToCaptureLexicalThis = languageVersion < 2 /* ES6 */; } // topmost container must be something that is directly nested in the class declaration - if (container && container.parent && container.parent.kind === 202 /* ClassDeclaration */) { + if (container && container.parent && container.parent.kind === 204 /* ClassDeclaration */) { if (container.flags & 128 /* Static */) { canUseSuperExpression = - container.kind === 135 /* MethodDeclaration */ || - container.kind === 134 /* MethodSignature */ || - container.kind === 137 /* GetAccessor */ || - container.kind === 138 /* SetAccessor */; + container.kind === 136 /* MethodDeclaration */ || + container.kind === 135 /* MethodSignature */ || + container.kind === 138 /* GetAccessor */ || + container.kind === 139 /* SetAccessor */; } else { canUseSuperExpression = - container.kind === 135 /* MethodDeclaration */ || - container.kind === 134 /* MethodSignature */ || - container.kind === 137 /* GetAccessor */ || - container.kind === 138 /* SetAccessor */ || - container.kind === 133 /* PropertyDeclaration */ || - container.kind === 132 /* PropertySignature */ || - container.kind === 136 /* Constructor */; + container.kind === 136 /* MethodDeclaration */ || + container.kind === 135 /* MethodSignature */ || + container.kind === 138 /* GetAccessor */ || + container.kind === 139 /* SetAccessor */ || + container.kind === 134 /* PropertyDeclaration */ || + container.kind === 133 /* PropertySignature */ || + container.kind === 137 /* Constructor */; } } } @@ -16023,13 +17700,13 @@ var ts; var returnType; if ((container.flags & 128 /* Static */) || isCallExpression) { getNodeLinks(node).flags |= 32 /* SuperStatic */; - returnType = getTypeOfSymbol(baseClass.symbol); + returnType = getBaseConstructorTypeOfClass(classType); } else { getNodeLinks(node).flags |= 16 /* SuperInstance */; - returnType = baseClass; + returnType = baseClassType; } - if (container.kind === 136 /* Constructor */ && isInConstructorArgumentInitializer(node, container)) { + if (container.kind === 137 /* 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); returnType = unknownType; @@ -16043,7 +17720,7 @@ var ts; return returnType; } } - if (container && container.kind === 128 /* ComputedPropertyName */) { + if (container && container.kind === 129 /* ComputedPropertyName */) { error(node, ts.Diagnostics.super_cannot_be_referenced_in_a_computed_property_name); } else if (isCallExpression) { @@ -16061,7 +17738,7 @@ var ts; if (isContextSensitive(func)) { var contextualSignature = getContextualSignature(func); if (contextualSignature) { - var funcHasRestParameters = ts.hasRestParameters(func); + var funcHasRestParameters = ts.hasRestParameter(func); var len = func.parameters.length - (funcHasRestParameters ? 1 : 0); var indexOfParameter = ts.indexOf(func.parameters, parameter); if (indexOfParameter < len) { @@ -16088,7 +17765,7 @@ var ts; if (declaration.type) { return getTypeFromTypeNode(declaration.type); } - if (declaration.kind === 130 /* Parameter */) { + if (declaration.kind === 131 /* Parameter */) { var type = getContextuallyTypedParameterType(declaration); if (type) { return type; @@ -16101,22 +17778,40 @@ var ts; return undefined; } function getContextualTypeForReturnExpression(node) { + var func = ts.getContainingFunction(node); + if (func && !func.asteriskToken) { + return getContextualReturnType(func); + } + return undefined; + } + function getContextualTypeForYieldOperand(node) { var func = ts.getContainingFunction(node); if (func) { - // 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 (func.type || func.kind === 136 /* Constructor */ || func.kind === 137 /* GetAccessor */ && getSetAccessorTypeAnnotationNode(ts.getDeclarationOfKind(func.symbol, 138 /* SetAccessor */))) { - return getReturnTypeOfSignature(getSignatureFromDeclaration(func)); - } - // 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(func); - if (signature) { - return getReturnTypeOfSignature(signature); + var contextualReturnType = getContextualReturnType(func); + if (contextualReturnType) { + return node.asteriskToken + ? contextualReturnType + : getElementTypeOfIterableIterator(contextualReturnType); } } return undefined; } + 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 === 137 /* Constructor */ || + functionDecl.kind === 138 /* GetAccessor */ && getSetAccessorTypeAnnotationNode(ts.getDeclarationOfKind(functionDecl.symbol, 139 /* 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); @@ -16128,7 +17823,7 @@ var ts; return undefined; } function getContextualTypeForSubstitutionExpression(template, substitutionExpression) { - if (template.parent.kind === 160 /* TaggedTemplateExpression */) { + if (template.parent.kind === 162 /* TaggedTemplateExpression */) { return getContextualTypeForArgument(template.parent, substitutionExpression); } return undefined; @@ -16238,7 +17933,7 @@ var ts; var index = ts.indexOf(arrayLiteral.elements, node); return getTypeOfPropertyOfContextualType(type, "" + index) || getIndexTypeOfContextualType(type, 1 /* Number */) - || (languageVersion >= 2 /* ES6 */ ? checkIteratedType(type, undefined) : undefined); + || (languageVersion >= 2 /* ES6 */ ? getElementTypeOfIterable(type, undefined) : undefined); } return undefined; } @@ -16259,32 +17954,34 @@ var ts; } var parent = node.parent; switch (parent.kind) { - case 199 /* VariableDeclaration */: - case 130 /* Parameter */: - case 133 /* PropertyDeclaration */: - case 132 /* PropertySignature */: - case 153 /* BindingElement */: + case 201 /* VariableDeclaration */: + case 131 /* Parameter */: + case 134 /* PropertyDeclaration */: + case 133 /* PropertySignature */: + case 155 /* BindingElement */: return getContextualTypeForInitializerExpression(node); - case 164 /* ArrowFunction */: - case 192 /* ReturnStatement */: + case 166 /* ArrowFunction */: + case 194 /* ReturnStatement */: return getContextualTypeForReturnExpression(node); - case 158 /* CallExpression */: - case 159 /* NewExpression */: + case 175 /* YieldExpression */: + return getContextualTypeForYieldOperand(parent); + case 160 /* CallExpression */: + case 161 /* NewExpression */: return getContextualTypeForArgument(parent, node); - case 161 /* TypeAssertionExpression */: + case 163 /* TypeAssertionExpression */: return getTypeFromTypeNode(parent.type); - case 170 /* BinaryExpression */: + case 172 /* BinaryExpression */: return getContextualTypeForBinaryOperand(node); - case 225 /* PropertyAssignment */: + case 227 /* PropertyAssignment */: return getContextualTypeForObjectLiteralElement(parent); - case 154 /* ArrayLiteralExpression */: + case 156 /* ArrayLiteralExpression */: return getContextualTypeForElementExpression(node); - case 171 /* ConditionalExpression */: + case 173 /* ConditionalExpression */: return getContextualTypeForConditionalOperand(node); - case 178 /* TemplateSpan */: - ts.Debug.assert(parent.parent.kind === 172 /* TemplateExpression */); + case 180 /* TemplateSpan */: + ts.Debug.assert(parent.parent.kind === 174 /* TemplateExpression */); return getContextualTypeForSubstitutionExpression(parent.parent, node); - case 162 /* ParenthesizedExpression */: + case 164 /* ParenthesizedExpression */: return getContextualType(parent); } return undefined; @@ -16301,11 +17998,13 @@ var ts; } } function isFunctionExpressionOrArrowFunction(node) { - return node.kind === 163 /* FunctionExpression */ || node.kind === 164 /* ArrowFunction */; + return node.kind === 165 /* FunctionExpression */ || node.kind === 166 /* ArrowFunction */; } function getContextualSignatureForFunctionLikeDeclaration(node) { - // Only function expressions and arrow functions are contextually typed. - return isFunctionExpressionOrArrowFunction(node) ? getContextualSignature(node) : undefined; + // Only function expressions, arrow functions, and object literal methods are contextually typed. + return isFunctionExpressionOrArrowFunction(node) || ts.isObjectLiteralMethod(node) + ? getContextualSignature(node) + : undefined; } // 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. @@ -16313,7 +18012,7 @@ var ts; // 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 !== 135 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); + ts.Debug.assert(node.kind !== 136 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); var type = ts.isObjectLiteralMethod(node) ? getContextualTypeForObjectLiteralMethod(node) : getContextualType(node); @@ -16369,13 +18068,13 @@ var ts; // an assignment target. Examples include 'a = xxx', '{ p: a } = xxx', '[{ p: a}] = xxx'. function isAssignmentTarget(node) { var parent = node.parent; - if (parent.kind === 170 /* BinaryExpression */ && parent.operatorToken.kind === 53 /* EqualsToken */ && parent.left === node) { + if (parent.kind === 172 /* BinaryExpression */ && parent.operatorToken.kind === 53 /* EqualsToken */ && parent.left === node) { return true; } - if (parent.kind === 225 /* PropertyAssignment */) { + if (parent.kind === 227 /* PropertyAssignment */) { return isAssignmentTarget(parent.parent); } - if (parent.kind === 154 /* ArrayLiteralExpression */) { + if (parent.kind === 156 /* ArrayLiteralExpression */) { return isAssignmentTarget(parent); } return false; @@ -16400,7 +18099,7 @@ var ts; var inDestructuringPattern = isAssignmentTarget(node); for (var _i = 0; _i < elements.length; _i++) { var e = elements[_i]; - if (inDestructuringPattern && e.kind === 174 /* SpreadElementExpression */) { + if (inDestructuringPattern && e.kind === 176 /* SpreadElementExpression */) { // Given the following situation: // var c: {}; // [...c] = ["", 0]; @@ -16415,7 +18114,7 @@ var ts; // if there is no index type / iterated type. var restArrayType = checkExpression(e.expression, contextualMapper); var restElementType = getIndexTypeOfType(restArrayType, 1 /* Number */) || - (languageVersion >= 2 /* ES6 */ ? checkIteratedType(restArrayType, undefined) : undefined); + (languageVersion >= 2 /* ES6 */ ? getElementTypeOfIterable(restArrayType, undefined) : undefined); if (restElementType) { elementTypes.push(restElementType); } @@ -16424,7 +18123,7 @@ var ts; var type = checkExpression(e, contextualMapper); elementTypes.push(type); } - hasSpreadElement = hasSpreadElement || e.kind === 174 /* SpreadElementExpression */; + hasSpreadElement = hasSpreadElement || e.kind === 176 /* SpreadElementExpression */; } if (!hasSpreadElement) { var contextualType = getContextualType(node); @@ -16435,12 +18134,15 @@ var ts; return createArrayType(getUnionType(elementTypes)); } function isNumericName(name) { - return name.kind === 128 /* ComputedPropertyName */ ? isNumericComputedName(name) : isNumericLiteralName(name.text); + return name.kind === 129 /* 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 allConstituentTypesHaveKind(checkComputedPropertyName(name), 1 /* Any */ | 132 /* NumberLike */); + return isTypeAnyOrAllConstituentTypesHaveKind(checkComputedPropertyName(name), 132 /* NumberLike */); + } + function isTypeAnyOrAllConstituentTypesHaveKind(type, kind) { + return isTypeAny(type) || allConstituentTypesHaveKind(type, kind); } function isNumericLiteralName(name) { // The intent of numeric names is that @@ -16472,7 +18174,7 @@ var ts; links.resolvedType = checkExpression(node.expression); // This will allow types number, string, symbol or any. It will also allow enums, the unknown // type, and any union of these types (like string | number). - if (!allConstituentTypesHaveKind(links.resolvedType, 1 /* Any */ | 132 /* NumberLike */ | 258 /* StringLike */ | 1048576 /* ESSymbol */)) { + if (!isTypeAnyOrAllConstituentTypesHaveKind(links.resolvedType, 132 /* NumberLike */ | 258 /* StringLike */ | 2097152 /* ESSymbol */)) { error(node, ts.Diagnostics.A_computed_property_name_must_be_of_type_string_number_symbol_or_any); } else { @@ -16491,18 +18193,18 @@ var ts; for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { var memberDecl = _a[_i]; var member = memberDecl.symbol; - if (memberDecl.kind === 225 /* PropertyAssignment */ || - memberDecl.kind === 226 /* ShorthandPropertyAssignment */ || + if (memberDecl.kind === 227 /* PropertyAssignment */ || + memberDecl.kind === 228 /* ShorthandPropertyAssignment */ || ts.isObjectLiteralMethod(memberDecl)) { var type = void 0; - if (memberDecl.kind === 225 /* PropertyAssignment */) { + if (memberDecl.kind === 227 /* PropertyAssignment */) { type = checkPropertyAssignment(memberDecl, contextualMapper); } - else if (memberDecl.kind === 135 /* MethodDeclaration */) { + else if (memberDecl.kind === 136 /* MethodDeclaration */) { type = checkObjectLiteralMethod(memberDecl, contextualMapper); } else { - ts.Debug.assert(memberDecl.kind === 226 /* ShorthandPropertyAssignment */); + ts.Debug.assert(memberDecl.kind === 228 /* ShorthandPropertyAssignment */); type = checkExpression(memberDecl.name, contextualMapper); } typeFlags |= type.flags; @@ -16522,7 +18224,7 @@ var ts; // 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 === 137 /* GetAccessor */ || memberDecl.kind === 138 /* SetAccessor */); + ts.Debug.assert(memberDecl.kind === 138 /* GetAccessor */ || memberDecl.kind === 139 /* SetAccessor */); checkAccessorDeclaration(memberDecl); } if (!ts.hasDynamicName(memberDecl)) { @@ -16533,7 +18235,7 @@ var ts; var stringIndexType = getIndexType(0 /* String */); var numberIndexType = getIndexType(1 /* Number */); var result = createAnonymousType(node.symbol, propertiesTable, emptyArray, emptyArray, stringIndexType, numberIndexType); - result.flags |= 131072 /* ObjectLiteral */ | 524288 /* ContainsObjectLiteral */ | (typeFlags & 262144 /* ContainsUndefinedOrNull */); + result.flags |= 262144 /* ObjectLiteral */ | 1048576 /* ContainsObjectLiteral */ | (typeFlags & 524288 /* ContainsUndefinedOrNull */); return result; function getIndexType(kind) { if (contextualType && contextualTypeHasIndexSignature(contextualType, kind)) { @@ -16561,7 +18263,7 @@ var ts; // 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 : 133 /* PropertyDeclaration */; + return s.valueDeclaration ? s.valueDeclaration.kind : 134 /* PropertyDeclaration */; } function getDeclarationFlagsFromSymbol(s) { return s.valueDeclaration ? ts.getCombinedNodeFlags(s.valueDeclaration) : s.flags & 134217728 /* Prototype */ ? 16 /* Public */ | 128 /* Static */ : 0; @@ -16574,7 +18276,7 @@ var ts; } // Property is known to be private or protected at this point // Get the declaring and enclosing class instance types - var enclosingClassDeclaration = ts.getAncestor(node, 202 /* ClassDeclaration */); + var enclosingClassDeclaration = ts.getAncestor(node, 204 /* ClassDeclaration */); var enclosingClass = enclosingClassDeclaration ? getDeclaredTypeOfSymbol(getSymbolOfNode(enclosingClassDeclaration)) : undefined; var declaringClass = getDeclaredTypeOfSymbol(prop.parent); // Private property is accessible if declaring and enclosing class are the same @@ -16610,51 +18312,49 @@ var ts; return checkPropertyAccessExpressionOrQualifiedName(node, node.left, node.right); } function checkPropertyAccessExpressionOrQualifiedName(node, left, right) { - var type = checkExpressionOrQualifiedName(left); - if (type === unknownType) + var type = checkExpression(left); + if (isTypeAny(type)) { return type; - if (type !== anyType) { - var apparentType = getApparentType(getWidenedType(type)); - if (apparentType === unknownType) { - // handle cases when type is Type parameter with invalid constraint - return unknownType; - } - var prop = getPropertyOfType(apparentType, right.text); - if (!prop) { - if (right.text) { - error(right, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(right), typeToString(type)); - } - return unknownType; - } - getNodeLinks(node).resolvedSymbol = prop; - if (prop.parent && prop.parent.flags & 32 /* Class */) { - // 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 (left.kind === 91 /* SuperKeyword */ && getDeclarationKindFromSymbol(prop) !== 135 /* MethodDeclaration */) { - error(right, ts.Diagnostics.Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword); - } - else { - checkClassPropertyAccess(node, left, type, prop); - } - } - return getTypeOfSymbol(prop); } - return anyType; + var apparentType = getApparentType(getWidenedType(type)); + if (apparentType === unknownType) { + // handle cases when type is Type parameter with invalid constraint + return unknownType; + } + var prop = getPropertyOfType(apparentType, right.text); + if (!prop) { + if (right.text) { + error(right, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(right), typeToString(type)); + } + return unknownType; + } + getNodeLinks(node).resolvedSymbol = prop; + if (prop.parent && prop.parent.flags & 32 /* Class */) { + // 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 (left.kind === 91 /* SuperKeyword */ && getDeclarationKindFromSymbol(prop) !== 136 /* MethodDeclaration */) { + error(right, ts.Diagnostics.Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword); + } + else { + checkClassPropertyAccess(node, left, type, prop); + } + } + return getTypeOfSymbol(prop); } function isValidPropertyAccess(node, propertyName) { - var left = node.kind === 156 /* PropertyAccessExpression */ + var left = node.kind === 158 /* PropertyAccessExpression */ ? node.expression : node.left; - var type = checkExpressionOrQualifiedName(left); - if (type !== unknownType && type !== anyType) { + var type = checkExpression(left); + if (type !== unknownType && !isTypeAny(type)) { var prop = getPropertyOfType(getWidenedType(type), propertyName); if (prop && prop.parent && prop.parent.flags & 32 /* Class */) { - if (left.kind === 91 /* SuperKeyword */ && getDeclarationKindFromSymbol(prop) !== 135 /* MethodDeclaration */) { + if (left.kind === 91 /* SuperKeyword */ && getDeclarationKindFromSymbol(prop) !== 136 /* MethodDeclaration */) { return false; } else { @@ -16670,7 +18370,7 @@ var ts; // Grammar checking if (!node.argumentExpression) { var sourceFile = getSourceFile(node); - if (node.parent.kind === 159 /* NewExpression */ && node.parent.expression === node) { + if (node.parent.kind === 161 /* 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); @@ -16703,23 +18403,23 @@ var ts; // - Otherwise, if IndexExpr is of type Any, the String or Number primitive type, or an enum type, the property access is of type Any. // See if we can index as a property. if (node.argumentExpression) { - var name_6 = getPropertyNameForIndexedAccess(node.argumentExpression, indexType); - if (name_6 !== undefined) { - var prop = getPropertyOfType(objectType, name_6); + var name_10 = getPropertyNameForIndexedAccess(node.argumentExpression, indexType); + if (name_10 !== undefined) { + var prop = getPropertyOfType(objectType, name_10); if (prop) { getNodeLinks(node).resolvedSymbol = prop; return getTypeOfSymbol(prop); } else if (isConstEnum) { - error(node.argumentExpression, ts.Diagnostics.Property_0_does_not_exist_on_const_enum_1, name_6, symbolToString(objectType.symbol)); + error(node.argumentExpression, ts.Diagnostics.Property_0_does_not_exist_on_const_enum_1, name_10, symbolToString(objectType.symbol)); return unknownType; } } } // Check for compatible indexer types. - if (allConstituentTypesHaveKind(indexType, 1 /* Any */ | 258 /* StringLike */ | 132 /* NumberLike */ | 1048576 /* ESSymbol */)) { + if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 258 /* StringLike */ | 132 /* NumberLike */ | 2097152 /* ESSymbol */)) { // Try to use a number indexer. - if (allConstituentTypesHaveKind(indexType, 1 /* Any */ | 132 /* NumberLike */)) { + if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 132 /* NumberLike */)) { var numberIndexType = getIndexTypeOfType(objectType, 1 /* Number */); if (numberIndexType) { return numberIndexType; @@ -16731,7 +18431,7 @@ var ts; return stringIndexType; } // Fall back to any. - if (compilerOptions.noImplicitAny && !compilerOptions.suppressImplicitAnyIndexErrors && objectType !== anyType) { + if (compilerOptions.noImplicitAny && !compilerOptions.suppressImplicitAnyIndexErrors && !isTypeAny(objectType)) { error(node, ts.Diagnostics.Index_signature_of_object_type_implicitly_has_an_any_type); } return anyType; @@ -16772,7 +18472,7 @@ var ts; return false; } // Make sure the property type is the primitive symbol type - if ((expressionType.flags & 1048576 /* ESSymbol */) === 0) { + if ((expressionType.flags & 2097152 /* ESSymbol */) === 0) { if (reportError) { error(expression, ts.Diagnostics.A_computed_property_name_of_the_form_0_must_be_of_type_symbol, ts.getTextOfNode(expression)); } @@ -16799,7 +18499,7 @@ var ts; return true; } function resolveUntypedCall(node) { - if (node.kind === 160 /* TaggedTemplateExpression */) { + if (node.kind === 162 /* TaggedTemplateExpression */) { checkExpression(node.template); } else { @@ -16832,13 +18532,13 @@ var ts; for (var _i = 0; _i < signatures.length; _i++) { var signature = signatures[_i]; var symbol = signature.declaration && getSymbolOfNode(signature.declaration); - var parent_4 = signature.declaration && signature.declaration.parent; + var parent_6 = signature.declaration && signature.declaration.parent; if (!lastSymbol || symbol === lastSymbol) { - if (lastParent && parent_4 === lastParent) { + if (lastParent && parent_6 === lastParent) { index++; } else { - lastParent = parent_4; + lastParent = parent_6; index = cutoffIndex; } } @@ -16846,7 +18546,7 @@ var ts; // 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_4; + lastParent = parent_6; } lastSymbol = symbol; // specialized signatures always need to be placed before non-specialized signatures regardless @@ -16867,7 +18567,7 @@ var ts; } function getSpreadArgumentIndex(args) { for (var i = 0; i < args.length; i++) { - if (args[i].kind === 174 /* SpreadElementExpression */) { + if (args[i].kind === 176 /* SpreadElementExpression */) { return i; } } @@ -16877,13 +18577,13 @@ var ts; var adjustedArgCount; // 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 - if (node.kind === 160 /* TaggedTemplateExpression */) { + if (node.kind === 162 /* 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 adjustedArgCount = args.length; typeArguments = undefined; - if (tagExpression.template.kind === 172 /* TemplateExpression */) { + if (tagExpression.template.kind === 174 /* 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; @@ -16904,7 +18604,7 @@ var ts; var callExpression = node; if (!callExpression.arguments) { // This only happens when we have something of the form: 'new C' - ts.Debug.assert(callExpression.kind === 159 /* NewExpression */); + ts.Debug.assert(callExpression.kind === 161 /* NewExpression */); return signature.minArgumentCount === 0; } // For IDE scenarios we may have an incomplete call, so a trailing comma is tantamount to adding another argument. @@ -16981,10 +18681,10 @@ var ts; // wildcards for all context sensitive function expressions. for (var i = 0; i < args.length; i++) { var arg = args[i]; - if (arg.kind !== 176 /* OmittedExpression */) { + if (arg.kind !== 178 /* OmittedExpression */) { var paramType = getTypeAtPosition(signature, i); var argType = void 0; - if (i === 0 && args[i].parent.kind === 160 /* TaggedTemplateExpression */) { + if (i === 0 && args[i].parent.kind === 162 /* TaggedTemplateExpression */) { argType = globalTemplateStringsArrayType; } else { @@ -17031,12 +18731,12 @@ var ts; function checkApplicableSignature(node, args, signature, relation, excludeArgument, reportErrors) { for (var i = 0; i < args.length; i++) { var arg = args[i]; - if (arg.kind !== 176 /* OmittedExpression */) { + if (arg.kind !== 178 /* OmittedExpression */) { // Check spread elements against rest type (from arity check we know spread argument corresponds to a rest parameter) var paramType = getTypeAtPosition(signature, i); // A tagged template expression provides a special first argument, and string literals get string literal types // unless we're reporting errors - var argType = i === 0 && node.kind === 160 /* TaggedTemplateExpression */ + var argType = i === 0 && node.kind === 162 /* TaggedTemplateExpression */ ? globalTemplateStringsArrayType : arg.kind === 8 /* StringLiteral */ && !reportErrors ? getStringLiteralType(arg) @@ -17058,10 +18758,10 @@ var ts; */ function getEffectiveCallArguments(node) { var args; - if (node.kind === 160 /* TaggedTemplateExpression */) { + if (node.kind === 162 /* TaggedTemplateExpression */) { var template = node.template; args = [template]; - if (template.kind === 172 /* TemplateExpression */) { + if (template.kind === 174 /* TemplateExpression */) { ts.forEach(template.templateSpans, function (span) { args.push(span.expression); }); @@ -17072,32 +18772,11 @@ var ts; } return args; } - /** - * In a 'super' call, type arguments are not provided within the CallExpression node itself. - * Instead, they must be fetched from the class declaration's base type node. - * - * If 'node' is a 'super' call (e.g. super(...), new super(...)), then we attempt to fetch - * the type arguments off the containing class's first heritage clause (if one exists). Note that if - * type arguments are supplied on the 'super' call, they are ignored (though this is syntactically incorrect). - * - * In all other cases, the call's explicit type arguments are returned. - */ - function getEffectiveTypeArguments(callExpression) { - if (callExpression.expression.kind === 91 /* SuperKeyword */) { - var containingClass = ts.getAncestor(callExpression, 202 /* ClassDeclaration */); - var baseClassTypeNode = containingClass && ts.getClassExtendsHeritageClauseElement(containingClass); - return baseClassTypeNode && baseClassTypeNode.typeArguments; - } - else { - // Ordinary case - simple function invocation. - return callExpression.typeArguments; - } - } function resolveCall(node, signatures, candidatesOutArray) { - var isTaggedTemplate = node.kind === 160 /* TaggedTemplateExpression */; + var isTaggedTemplate = node.kind === 162 /* TaggedTemplateExpression */; var typeArguments; if (!isTaggedTemplate) { - typeArguments = getEffectiveTypeArguments(node); + typeArguments = node.typeArguments; // We already perform checking on the type arguments on the class declaration itself. if (node.expression.kind !== 91 /* SuperKeyword */) { ts.forEach(typeArguments, checkSourceElement); @@ -17192,8 +18871,8 @@ var ts; checkApplicableSignature(node, args, candidateForArgumentError, assignableRelation, undefined, true); } else if (candidateForTypeArgumentError) { - if (!isTaggedTemplate && node.typeArguments) { - checkTypeArguments(candidateForTypeArgumentError, node.typeArguments, [], true); + if (!isTaggedTemplate && typeArguments) { + checkTypeArguments(candidateForTypeArgumentError, typeArguments, [], true); } else { ts.Debug.assert(resultOfFailedInference.failedTypeParameterIndex >= 0); @@ -17287,7 +18966,11 @@ var ts; if (node.expression.kind === 91 /* SuperKeyword */) { var superType = checkSuperExpression(node.expression); if (superType !== unknownType) { - return resolveCall(node, getSignaturesOfType(superType, 1 /* Construct */), candidatesOutArray); + // 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.getAncestor(node, 204 /* ClassDeclaration */)); + var baseConstructors = getInstantiatedConstructorsForTypeArguments(superType, baseTypeNode.typeArguments); + return resolveCall(node, baseConstructors, candidatesOutArray); } return resolveUntypedCall(node); } @@ -17310,8 +18993,10 @@ var ts; // types are provided for the argument expressions, and the result is always of type Any. // We exclude union types because we may have a union of function types that happen to have // no common signatures. - if (funcType === anyType || (!callSignatures.length && !constructSignatures.length && !(funcType.flags & 16384 /* Union */) && isTypeAssignableTo(funcType, globalFunctionType))) { - if (node.typeArguments) { + if (isTypeAny(funcType) || (!callSignatures.length && !constructSignatures.length && !(funcType.flags & 16384 /* Union */) && isTypeAssignableTo(funcType, globalFunctionType))) { + // The unknownType indicates that an error already occured (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); @@ -17331,32 +19016,32 @@ var ts; return resolveCall(node, callSignatures, candidatesOutArray); } function resolveNewExpression(node, candidatesOutArray) { - if (node.arguments && languageVersion < 2 /* ES6 */) { + 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_6_and_higher); + error(node.arguments[spreadIndex], ts.Diagnostics.Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher); } } var expressionType = checkExpression(node.expression); - // TS 1.0 spec: 4.11 - // If ConstructExpr is of type Any, Args can be any argument - // list and the result of the operation is of type Any. - if (expressionType === anyType) { - if (node.typeArguments) { - error(node, ts.Diagnostics.Untyped_function_calls_may_not_accept_type_arguments); - } - return resolveUntypedCall(node); - } // If ConstructExpr'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 + // 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); } + // TS 1.0 spec: 4.11 + // If ConstructExpr 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 @@ -17388,7 +19073,7 @@ var ts; return resolveErrorCall(node); } var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */); - if (tagType === anyType || (!callSignatures.length && !(tagType.flags & 16384 /* Union */) && isTypeAssignableTo(tagType, globalFunctionType))) { + if (isTypeAny(tagType) || (!callSignatures.length && !(tagType.flags & 16384 /* Union */) && isTypeAssignableTo(tagType, globalFunctionType))) { return resolveUntypedCall(node); } if (!callSignatures.length) { @@ -17407,13 +19092,13 @@ var ts; // to correctly fill the candidatesOutArray. if (!links.resolvedSignature || candidatesOutArray) { links.resolvedSignature = anySignature; - if (node.kind === 158 /* CallExpression */) { + if (node.kind === 160 /* CallExpression */) { links.resolvedSignature = resolveCallExpression(node, candidatesOutArray); } - else if (node.kind === 159 /* NewExpression */) { + else if (node.kind === 161 /* NewExpression */) { links.resolvedSignature = resolveNewExpression(node, candidatesOutArray); } - else if (node.kind === 160 /* TaggedTemplateExpression */) { + else if (node.kind === 162 /* TaggedTemplateExpression */) { links.resolvedSignature = resolveTaggedTemplateExpression(node, candidatesOutArray); } else { @@ -17429,12 +19114,12 @@ var ts; if (node.expression.kind === 91 /* SuperKeyword */) { return voidType; } - if (node.kind === 159 /* NewExpression */) { + if (node.kind === 161 /* NewExpression */) { var declaration = signature.declaration; if (declaration && - declaration.kind !== 136 /* Constructor */ && - declaration.kind !== 140 /* ConstructSignature */ && - declaration.kind !== 144 /* ConstructorType */) { + declaration.kind !== 137 /* Constructor */ && + declaration.kind !== 141 /* ConstructSignature */ && + declaration.kind !== 146 /* ConstructorType */) { // When resolved signature is a call signature (and not a construct signature) the result type is any if (compilerOptions.noImplicitAny) { error(node, ts.Diagnostics.new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type); @@ -17482,21 +19167,43 @@ var ts; return unknownType; } var type; - if (func.body.kind !== 180 /* Block */) { + if (func.body.kind !== 182 /* Block */) { type = checkExpressionCached(func.body, contextualMapper); } else { - // Aggregate the types of expressions within all the return statements. - var types = checkAndAggregateReturnExpressionTypes(func.body, contextualMapper); - if (types.length === 0) { - return voidType; + var types; + var funcIsGenerator = !!func.asteriskToken; + if (funcIsGenerator) { + types = checkAndAggregateYieldOperandTypes(func.body, contextualMapper); + if (types.length === 0) { + var iterableIteratorAny = createIterableIteratorType(anyType); + if (compilerOptions.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; + } } - // When return statements are contextually typed we allow the return type to be a union type. Otherwise we require the - // return expressions to have a best common supertype. + else { + types = checkAndAggregateReturnExpressionTypes(func.body, contextualMapper); + if (types.length === 0) { + return voidType; + } + } + // When yield/return statements are contextually typed we allow the return type to be a union type. + // Otherwise we require the yield/return expressions to have a best common supertype. type = contextualSignature ? getUnionType(types) : getCommonSupertype(types); if (!type) { - error(func, ts.Diagnostics.No_best_common_type_exists_among_return_expressions); - return unknownType; + if (funcIsGenerator) { + error(func, ts.Diagnostics.No_best_common_type_exists_among_yield_expressions); + return createIterableIteratorType(unknownType); + } + else { + error(func, ts.Diagnostics.No_best_common_type_exists_among_return_expressions); + return unknownType; + } + } + if (funcIsGenerator) { + type = createIterableIteratorType(type); } } if (!contextualSignature) { @@ -17504,7 +19211,23 @@ var ts; } return getWidenedType(type); } - /// Returns a set of types relating to every return expression relating to a function block. + function checkAndAggregateYieldOperandTypes(body, contextualMapper) { + var aggregatedTypes = []; + ts.forEachYieldExpression(body, function (yieldExpression) { + var expr = yieldExpression.expression; + if (expr) { + var type = checkExpressionCached(expr, contextualMapper); + if (yieldExpression.asteriskToken) { + // A yield* expression effectively yields everything that its operand yields + type = checkElementTypeOfIterable(type, yieldExpression.expression); + } + if (!ts.contains(aggregatedTypes, type)) { + aggregatedTypes.push(type); + } + } + }); + return aggregatedTypes; + } function checkAndAggregateReturnExpressionTypes(body, contextualMapper) { var aggregatedTypes = []; ts.forEachReturnStatement(body, function (returnStatement) { @@ -17524,7 +19247,7 @@ var ts; }); } function bodyContainsSingleThrowStatement(body) { - return (body.statements.length === 1) && (body.statements[0].kind === 196 /* ThrowStatement */); + return (body.statements.length === 1) && (body.statements[0].kind === 198 /* ThrowStatement */); } // TypeScript Specification 1.0 (6.3) - July 2014 // An explicitly typed function whose return type isn't the Void or the Any type @@ -17535,11 +19258,11 @@ var ts; return; } // Functions that return 'void' or 'any' don't need any return expressions. - if (returnType === voidType || returnType === anyType) { + if (returnType === voidType || isTypeAny(returnType)) { return; } // If all we have is a function signature, or an arrow function with an expression body, then there is nothing to check. - if (ts.nodeIsMissing(func.body) || func.body.kind !== 180 /* Block */) { + if (ts.nodeIsMissing(func.body) || func.body.kind !== 182 /* Block */) { return; } var bodyBlock = func.body; @@ -17557,11 +19280,11 @@ var ts; error(func.type, ts.Diagnostics.A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value_or_consist_of_a_single_throw_statement); } function checkFunctionExpressionOrObjectLiteralMethod(node, contextualMapper) { - ts.Debug.assert(node.kind !== 135 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); + ts.Debug.assert(node.kind !== 136 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); // Grammar checking - var hasGrammarError = checkGrammarDeclarationNameInStrictMode(node) || checkGrammarFunctionLikeDeclaration(node); - if (!hasGrammarError && node.kind === 163 /* FunctionExpression */) { - checkGrammarFunctionName(node.name) || checkGrammarForGenerator(node); + var hasGrammarError = checkGrammarFunctionLikeDeclaration(node); + if (!hasGrammarError && node.kind === 165 /* FunctionExpression */) { + checkGrammarForGenerator(node); } // The identityMapper object is used to indicate that function expressions are wildcards if (contextualMapper === identityMapper && isContextSensitive(node)) { @@ -17592,19 +19315,27 @@ var ts; checkSignatureDeclaration(node); } } - if (produceDiagnostics && node.kind !== 135 /* MethodDeclaration */ && node.kind !== 134 /* MethodSignature */) { + if (produceDiagnostics && node.kind !== 136 /* MethodDeclaration */ && node.kind !== 135 /* MethodSignature */) { checkCollisionWithCapturedSuperVariable(node, node.name); checkCollisionWithCapturedThisVariable(node, node.name); } return type; } function checkFunctionExpressionOrObjectLiteralMethodBody(node) { - ts.Debug.assert(node.kind !== 135 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); + ts.Debug.assert(node.kind !== 136 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); if (node.type && !node.asteriskToken) { checkIfNonVoidFunctionHasReturnExpressionsOrSingleThrowStatment(node, getTypeFromTypeNode(node.type)); } if (node.body) { - if (node.body.kind === 180 /* Block */) { + 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 === 182 /* Block */) { checkSourceElement(node.body); } else { @@ -17617,7 +19348,7 @@ var ts; } } function checkArithmeticOperandType(operand, type, diagnostic) { - if (!allConstituentTypesHaveKind(type, 1 /* Any */ | 132 /* NumberLike */)) { + if (!isTypeAnyOrAllConstituentTypesHaveKind(type, 132 /* NumberLike */)) { error(operand, diagnostic); return false; } @@ -17646,17 +19377,17 @@ var ts; // An identifier expression that references any other kind of entity is classified as a value(and therefore cannot be the target of an assignment). return !symbol || symbol === unknownSymbol || symbol === argumentsSymbol || (symbol.flags & 3 /* Variable */) !== 0; } - case 156 /* PropertyAccessExpression */: { + case 158 /* PropertyAccessExpression */: { var symbol = findSymbol(n); // TypeScript 1.0 spec (April 2014): 4.10 // A property access expression is always classified as a reference. // NOTE (not in spec): assignment to enum members should not be allowed return !symbol || symbol === unknownSymbol || (symbol.flags & ~8 /* EnumMember */) !== 0; } - case 157 /* ElementAccessExpression */: + case 159 /* ElementAccessExpression */: // old compiler doesn't check indexed assess return true; - case 162 /* ParenthesizedExpression */: + case 164 /* ParenthesizedExpression */: return isReferenceOrErrorExpression(n.expression); default: return false; @@ -17665,21 +19396,21 @@ var ts; function isConstVariableReference(n) { switch (n.kind) { case 65 /* Identifier */: - case 156 /* PropertyAccessExpression */: { + case 158 /* PropertyAccessExpression */: { var symbol = findSymbol(n); return symbol && (symbol.flags & 3 /* Variable */) !== 0 && (getDeclarationFlagsFromSymbol(symbol) & 8192 /* Const */) !== 0; } - case 157 /* ElementAccessExpression */: { + case 159 /* ElementAccessExpression */: { var index = n.argumentExpression; var symbol = findSymbol(n.expression); if (symbol && index && index.kind === 8 /* StringLiteral */) { - var name_7 = index.text; - var prop = getPropertyOfType(getTypeOfSymbol(symbol), name_7); + var name_11 = index.text; + var prop = getPropertyOfType(getTypeOfSymbol(symbol), name_11); return prop && (prop.flags & 3 /* Variable */) !== 0 && (getDeclarationFlagsFromSymbol(prop) & 8192 /* Const */) !== 0; } return false; } - case 162 /* ParenthesizedExpression */: + case 164 /* ParenthesizedExpression */: return isConstVariableReference(n.expression); default: return false; @@ -17696,13 +19427,7 @@ var ts; return true; } function checkDeleteExpression(node) { - // Grammar checking - if (node.parserContextFlags & 1 /* StrictMode */ && node.expression.kind === 65 /* 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 - grammarErrorOnNode(node.expression, ts.Diagnostics.delete_cannot_be_called_on_an_identifier_in_strict_mode); - } - var operandType = checkExpression(node.expression); + checkExpression(node.expression); return booleanType; } function checkTypeOfExpression(node) { @@ -17714,19 +19439,12 @@ var ts; return undefinedType; } function checkPrefixUnaryExpression(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 ((node.operator === 38 /* PlusPlusToken */ || node.operator === 39 /* MinusMinusToken */)) { - checkGrammarEvalOrArgumentsInStrictMode(node, node.operand); - } var operandType = checkExpression(node.operand); switch (node.operator) { case 33 /* PlusToken */: case 34 /* MinusToken */: case 47 /* TildeToken */: - if (someConstituentTypeHasKind(operandType, 1048576 /* ESSymbol */)) { + if (someConstituentTypeHasKind(operandType, 2097152 /* ESSymbol */)) { error(node.operand, ts.Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, ts.tokenToString(node.operator)); } return numberType; @@ -17744,11 +19462,6 @@ var ts; return unknownType; } function checkPostfixUnaryExpression(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. - checkGrammarEvalOrArgumentsInStrictMode(node, node.operand); var operandType = checkExpression(node.operand); var ok = checkArithmeticOperandType(node.operand, operandType, ts.Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type); if (ok) { @@ -17804,11 +19517,11 @@ var ts; // and the right operand to be of type Any or a subtype of the 'Function' interface type. // 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 (allConstituentTypesHaveKind(leftType, 1049086 /* Primitive */)) { + if (allConstituentTypesHaveKind(leftType, 2097662 /* Primitive */)) { error(node.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 (!(rightType.flags & 1 /* Any */ || isTypeSubtypeOf(rightType, globalFunctionType))) { + if (!(isTypeAny(rightType) || isTypeSubtypeOf(rightType, globalFunctionType))) { error(node.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; @@ -17818,10 +19531,10 @@ var ts; // The in operator requires the left operand to be of type Any, the String primitive type, or the Number primitive type, // and the right operand to be of type Any, an object type, or a type parameter type. // The result is always of the Boolean primitive type. - if (!allConstituentTypesHaveKind(leftType, 1 /* Any */ | 258 /* StringLike */ | 132 /* NumberLike */ | 1048576 /* ESSymbol */)) { + if (!isTypeAnyOrAllConstituentTypesHaveKind(leftType, 258 /* StringLike */ | 132 /* NumberLike */ | 2097152 /* ESSymbol */)) { error(node.left, ts.Diagnostics.The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol); } - if (!allConstituentTypesHaveKind(rightType, 1 /* Any */ | 48128 /* ObjectType */ | 512 /* TypeParameter */)) { + if (!isTypeAnyOrAllConstituentTypesHaveKind(rightType, 48128 /* ObjectType */ | 512 /* TypeParameter */)) { error(node.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; @@ -17830,18 +19543,19 @@ var ts; var properties = node.properties; for (var _i = 0; _i < properties.length; _i++) { var p = properties[_i]; - if (p.kind === 225 /* PropertyAssignment */ || p.kind === 226 /* ShorthandPropertyAssignment */) { + if (p.kind === 227 /* PropertyAssignment */ || p.kind === 228 /* ShorthandPropertyAssignment */) { // TODO(andersh): Computed property support - var name_8 = p.name; - var type = sourceType.flags & 1 /* Any */ ? sourceType : - getTypeOfPropertyOfType(sourceType, name_8.text) || - isNumericLiteralName(name_8.text) && getIndexTypeOfType(sourceType, 1 /* Number */) || + var name_12 = p.name; + var type = isTypeAny(sourceType) + ? sourceType + : getTypeOfPropertyOfType(sourceType, name_12.text) || + isNumericLiteralName(name_12.text) && getIndexTypeOfType(sourceType, 1 /* Number */) || getIndexTypeOfType(sourceType, 0 /* String */); if (type) { - checkDestructuringAssignment(p.initializer || name_8, type); + checkDestructuringAssignment(p.initializer || name_12, type); } else { - error(name_8, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(sourceType), ts.declarationNameToString(name_8)); + error(name_12, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(sourceType), ts.declarationNameToString(name_12)); } } else { @@ -17858,11 +19572,12 @@ var ts; var elements = node.elements; for (var i = 0; i < elements.length; i++) { var e = elements[i]; - if (e.kind !== 176 /* OmittedExpression */) { - if (e.kind !== 174 /* SpreadElementExpression */) { + if (e.kind !== 178 /* OmittedExpression */) { + if (e.kind !== 176 /* SpreadElementExpression */) { var propName = "" + i; - var type = sourceType.flags & 1 /* Any */ ? sourceType : - isTupleLikeType(sourceType) + var type = isTypeAny(sourceType) + ? sourceType + : isTupleLikeType(sourceType) ? getTypeOfPropertyOfType(sourceType, propName) : elementType; if (type) { @@ -17883,7 +19598,7 @@ var ts; } else { var restExpression = e.expression; - if (restExpression.kind === 170 /* BinaryExpression */ && restExpression.operatorToken.kind === 53 /* EqualsToken */) { + if (restExpression.kind === 172 /* BinaryExpression */ && restExpression.operatorToken.kind === 53 /* EqualsToken */) { error(restExpression.operatorToken, ts.Diagnostics.A_rest_element_cannot_have_an_initializer); } else { @@ -17896,14 +19611,14 @@ var ts; return sourceType; } function checkDestructuringAssignment(target, sourceType, contextualMapper) { - if (target.kind === 170 /* BinaryExpression */ && target.operatorToken.kind === 53 /* EqualsToken */) { + if (target.kind === 172 /* BinaryExpression */ && target.operatorToken.kind === 53 /* EqualsToken */) { checkBinaryExpression(target, contextualMapper); target = target.left; } - if (target.kind === 155 /* ObjectLiteralExpression */) { + if (target.kind === 157 /* ObjectLiteralExpression */) { return checkObjectLiteralAssignment(target, sourceType, contextualMapper); } - if (target.kind === 154 /* ArrayLiteralExpression */) { + if (target.kind === 156 /* ArrayLiteralExpression */) { return checkArrayLiteralAssignment(target, sourceType, contextualMapper); } return checkReferenceAssignment(target, sourceType, contextualMapper); @@ -17916,14 +19631,8 @@ var ts; return sourceType; } function checkBinaryExpression(node, contextualMapper) { - // Grammar checking - if (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) - checkGrammarEvalOrArgumentsInStrictMode(node, node.left); - } var operator = node.operatorToken.kind; - if (operator === 53 /* EqualsToken */ && (node.left.kind === 155 /* ObjectLiteralExpression */ || node.left.kind === 154 /* ArrayLiteralExpression */)) { + if (operator === 53 /* EqualsToken */ && (node.left.kind === 157 /* ObjectLiteralExpression */ || node.left.kind === 156 /* ArrayLiteralExpression */)) { return checkDestructuringAssignment(node.left, checkExpression(node.right, contextualMapper), contextualMapper); } var leftType = checkExpression(node.left, contextualMapper); @@ -17997,10 +19706,10 @@ var ts; // If one or both operands are of the String primitive type, the result is of the String primitive type. resultType = stringType; } - else if (leftType.flags & 1 /* Any */ || rightType.flags & 1 /* Any */) { + 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 = anyType; + resultType = leftType === unknownType || rightType === unknownType ? unknownType : anyType; } // Symbols are not allowed at all in arithmetic expressions if (resultType && !checkForDisallowedESSymbolOperand(operator)) { @@ -18047,8 +19756,8 @@ var ts; } // Return true if there was no error, false if there was an error. function checkForDisallowedESSymbolOperand(operator) { - var offendingSymbolOperand = someConstituentTypeHasKind(leftType, 1048576 /* ESSymbol */) ? node.left : - someConstituentTypeHasKind(rightType, 1048576 /* ESSymbol */) ? node.right : + var offendingSymbolOperand = someConstituentTypeHasKind(leftType, 2097152 /* ESSymbol */) ? node.left : + someConstituentTypeHasKind(rightType, 2097152 /* ESSymbol */) ? node.right : undefined; if (offendingSymbolOperand) { error(offendingSymbolOperand, ts.Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, ts.tokenToString(operator)); @@ -18091,14 +19800,53 @@ var ts; error(node, ts.Diagnostics.Operator_0_cannot_be_applied_to_types_1_and_2, ts.tokenToString(node.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 (current.kind === 204 /* ClassDeclaration */ || current.kind === 177 /* ClassExpression */) { + return true; + } + current = parent; + parent = parent.parent; + } + return false; + } function checkYieldExpression(node) { // Grammar checking - if (!(node.parserContextFlags & 4 /* Yield */)) { - grammarErrorOnFirstToken(node, ts.Diagnostics.yield_expression_must_be_contained_within_a_generator_declaration); + if (!(node.parserContextFlags & 4 /* Yield */) || isYieldExpressionInClass(node)) { + grammarErrorOnFirstToken(node, ts.Diagnostics.A_yield_expression_is_only_allowed_in_a_generator_body); } - else { - grammarErrorOnFirstToken(node, ts.Diagnostics.yield_expressions_are_not_currently_supported); + 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. + if (func && func.asteriskToken) { + var expressionType = checkExpressionCached(node.expression, undefined); + var expressionElementType; + var nodeIsYieldStar = !!node.asteriskToken; + if (nodeIsYieldStar) { + expressionElementType = checkElementTypeOfIterable(expressionType, node.expression); + } + // 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 = getElementTypeOfIterableIterator(getTypeFromTypeNode(func.type)) || anyType; + if (nodeIsYieldStar) { + checkTypeAssignableTo(expressionElementType, signatureElementType, node.expression, undefined); + } + else { + checkTypeAssignableTo(expressionType, signatureElementType, node.expression, undefined); + } + } + } } + // Both yield and yield* expressions have type 'any' + return anyType; } function checkConditionalExpression(node, contextualMapper) { checkExpression(node.condition); @@ -18135,7 +19883,7 @@ var ts; // 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 === 128 /* ComputedPropertyName */) { + if (node.name.kind === 129 /* ComputedPropertyName */) { checkComputedPropertyName(node.name); } return checkExpression(node.initializer, contextualMapper); @@ -18146,7 +19894,7 @@ var ts; // 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 === 128 /* ComputedPropertyName */) { + if (node.name.kind === 129 /* ComputedPropertyName */) { checkComputedPropertyName(node.name); } var uninstantiatedType = checkFunctionExpressionOrObjectLiteralMethod(node, contextualMapper); @@ -18167,10 +19915,6 @@ var ts; } return type; } - function checkExpression(node, contextualMapper) { - checkGrammarIdentifierInStrictMode(node); - return checkExpressionOrQualifiedName(node, contextualMapper); - } // 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.12.2 in spec) and provides the type mapper to use in @@ -18178,9 +19922,9 @@ var ts; // object, it serves as an indicator that all contained function and arrow expressions should be considered to // have the wildcard function type; this form of type check is used during overload resolution to exclude // contextually typed function and arrow expressions in the initial phase. - function checkExpressionOrQualifiedName(node, contextualMapper) { + function checkExpression(node, contextualMapper) { var type; - if (node.kind == 127 /* QualifiedName */) { + if (node.kind === 128 /* QualifiedName */) { type = checkQualifiedName(node); } else { @@ -18192,9 +19936,9 @@ var ts; // - 'left' in property access // - 'object' in indexed access // - target in rhs of import statement - var ok = (node.parent.kind === 156 /* PropertyAccessExpression */ && node.parent.expression === node) || - (node.parent.kind === 157 /* ElementAccessExpression */ && node.parent.expression === node) || - ((node.kind === 65 /* Identifier */ || node.kind === 127 /* QualifiedName */) && isInRightSideOfImportOrExportAssignment(node)); + var ok = (node.parent.kind === 158 /* PropertyAccessExpression */ && node.parent.expression === node) || + (node.parent.kind === 159 /* ElementAccessExpression */ && node.parent.expression === node) || + ((node.kind === 65 /* Identifier */ || node.kind === 128 /* 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); } @@ -18221,62 +19965,60 @@ var ts; return booleanType; case 7 /* NumericLiteral */: return checkNumericLiteral(node); - case 172 /* TemplateExpression */: + case 174 /* TemplateExpression */: return checkTemplateExpression(node); case 8 /* StringLiteral */: case 10 /* NoSubstitutionTemplateLiteral */: return stringType; case 9 /* RegularExpressionLiteral */: return globalRegExpType; - case 154 /* ArrayLiteralExpression */: + case 156 /* ArrayLiteralExpression */: return checkArrayLiteral(node, contextualMapper); - case 155 /* ObjectLiteralExpression */: + case 157 /* ObjectLiteralExpression */: return checkObjectLiteral(node, contextualMapper); - case 156 /* PropertyAccessExpression */: + case 158 /* PropertyAccessExpression */: return checkPropertyAccessExpression(node); - case 157 /* ElementAccessExpression */: + case 159 /* ElementAccessExpression */: return checkIndexedAccess(node); - case 158 /* CallExpression */: - case 159 /* NewExpression */: + case 160 /* CallExpression */: + case 161 /* NewExpression */: return checkCallExpression(node); - case 160 /* TaggedTemplateExpression */: + case 162 /* TaggedTemplateExpression */: return checkTaggedTemplateExpression(node); - case 161 /* TypeAssertionExpression */: + case 163 /* TypeAssertionExpression */: return checkTypeAssertion(node); - case 162 /* ParenthesizedExpression */: + case 164 /* ParenthesizedExpression */: return checkExpression(node.expression, contextualMapper); - case 175 /* ClassExpression */: + case 177 /* ClassExpression */: return checkClassExpression(node); - case 163 /* FunctionExpression */: - case 164 /* ArrowFunction */: + case 165 /* FunctionExpression */: + case 166 /* ArrowFunction */: return checkFunctionExpressionOrObjectLiteralMethod(node, contextualMapper); - case 166 /* TypeOfExpression */: + case 168 /* TypeOfExpression */: return checkTypeOfExpression(node); - case 165 /* DeleteExpression */: + case 167 /* DeleteExpression */: return checkDeleteExpression(node); - case 167 /* VoidExpression */: + case 169 /* VoidExpression */: return checkVoidExpression(node); - case 168 /* PrefixUnaryExpression */: + case 170 /* PrefixUnaryExpression */: return checkPrefixUnaryExpression(node); - case 169 /* PostfixUnaryExpression */: + case 171 /* PostfixUnaryExpression */: return checkPostfixUnaryExpression(node); - case 170 /* BinaryExpression */: + case 172 /* BinaryExpression */: return checkBinaryExpression(node, contextualMapper); - case 171 /* ConditionalExpression */: + case 173 /* ConditionalExpression */: return checkConditionalExpression(node, contextualMapper); - case 174 /* SpreadElementExpression */: + case 176 /* SpreadElementExpression */: return checkSpreadElementExpression(node, contextualMapper); - case 176 /* OmittedExpression */: + case 178 /* OmittedExpression */: return undefinedType; - case 173 /* YieldExpression */: - checkYieldExpression(node); - return unknownType; + case 175 /* YieldExpression */: + return checkYieldExpression(node); } return unknownType; } // DECLARATION AND STATEMENT TYPE CHECKING function checkTypeParameter(node) { - checkGrammarDeclarationNameInStrictMode(node); // Grammar Checking if (node.expression) { grammarErrorOnFirstToken(node.expression, ts.Diagnostics.Type_expected); @@ -18293,15 +20035,13 @@ var ts; // 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). - // It is a SyntaxError if the identifier eval or arguments appears within a FormalParameterList of a - // strict mode FunctionLikeDeclaration or FunctionExpression(13.1) // Grammar checking - checkGrammarDecorators(node) || checkGrammarModifiers(node) || checkGrammarEvalOrArgumentsInStrictMode(node, node.name); + checkGrammarDecorators(node) || checkGrammarModifiers(node); checkVariableLikeDeclaration(node); var func = ts.getContainingFunction(node); if (node.flags & 112 /* AccessibilityModifier */) { func = ts.getContainingFunction(node); - if (!(func.kind === 136 /* Constructor */ && ts.nodeIsPresent(func.body))) { + if (!(func.kind === 137 /* Constructor */ && ts.nodeIsPresent(func.body))) { error(node, ts.Diagnostics.A_parameter_property_is_only_allowed_in_a_constructor_implementation); } } @@ -18314,38 +20054,139 @@ var ts; error(node, ts.Diagnostics.A_rest_parameter_must_be_of_an_array_type); } } + function isSyntacticallyValidGenerator(node) { + if (!node.asteriskToken || !node.body) { + return false; + } + return node.kind === 136 /* MethodDeclaration */ || + node.kind === 203 /* FunctionDeclaration */ || + node.kind === 165 /* FunctionExpression */; + } + function getTypePredicateParameterIndex(parameterList, parameter) { + if (parameterList) { + for (var i = 0; i < parameterList.length; i++) { + var param = parameterList[i]; + if (param.name.kind === 65 /* Identifier */ && + param.name.text === parameter.text) { + return i; + } + } + } + return -1; + } + function isInLegalTypePredicatePosition(node) { + switch (node.parent.kind) { + case 166 /* ArrowFunction */: + case 140 /* CallSignature */: + case 203 /* FunctionDeclaration */: + case 165 /* FunctionExpression */: + case 145 /* FunctionType */: + case 136 /* MethodDeclaration */: + case 135 /* MethodSignature */: + return node === node.parent.type; + } + return false; + } function checkSignatureDeclaration(node) { // Grammar checking - if (node.kind === 141 /* IndexSignature */) { + if (node.kind === 142 /* IndexSignature */) { checkGrammarIndexSignature(node); } - else if (node.kind === 143 /* FunctionType */ || node.kind === 201 /* FunctionDeclaration */ || node.kind === 144 /* ConstructorType */ || - node.kind === 139 /* CallSignature */ || node.kind === 136 /* Constructor */ || - node.kind === 140 /* ConstructSignature */) { + else if (node.kind === 145 /* FunctionType */ || node.kind === 203 /* FunctionDeclaration */ || node.kind === 146 /* ConstructorType */ || + node.kind === 140 /* CallSignature */ || node.kind === 137 /* Constructor */ || + node.kind === 141 /* ConstructSignature */) { checkGrammarFunctionLikeDeclaration(node); } checkTypeParameters(node.typeParameters); ts.forEach(node.parameters, checkParameter); if (node.type) { - checkSourceElement(node.type); + if (node.type.kind === 143 /* TypePredicate */) { + var typePredicate = getSignatureFromDeclaration(node).typePredicate; + var typePredicateNode = node.type; + if (isInLegalTypePredicatePosition(typePredicateNode)) { + if (typePredicate.parameterIndex >= 0) { + if (node.parameters[typePredicate.parameterIndex].dotDotDotToken) { + error(typePredicateNode.parameterName, ts.Diagnostics.A_type_predicate_cannot_reference_a_rest_parameter); + } + else { + checkTypeAssignableTo(typePredicate.type, getTypeAtLocation(node.parameters[typePredicate.parameterIndex]), typePredicateNode.type); + } + } + else if (typePredicateNode.parameterName) { + var hasReportedError = false; + for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) { + var param = _a[_i]; + if (hasReportedError) { + break; + } + if (param.name.kind === 153 /* ObjectBindingPattern */ || + param.name.kind === 154 /* ArrayBindingPattern */) { + (function checkBindingPattern(pattern) { + for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) { + var element = _a[_i]; + if (element.name.kind === 65 /* Identifier */ && + element.name.text === typePredicate.parameterName) { + error(typePredicateNode.parameterName, ts.Diagnostics.A_type_predicate_cannot_reference_element_0_in_a_binding_pattern, typePredicate.parameterName); + hasReportedError = true; + break; + } + else if (element.name.kind === 154 /* ArrayBindingPattern */ || + element.name.kind === 153 /* ObjectBindingPattern */) { + checkBindingPattern(element.name); + } + } + })(param.name); + } + } + if (!hasReportedError) { + error(typePredicateNode.parameterName, ts.Diagnostics.Cannot_find_parameter_0, typePredicate.parameterName); + } + } + } + else { + error(typePredicateNode, ts.Diagnostics.A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods); + } + } + else { + checkSourceElement(node.type); + } } if (produceDiagnostics) { checkCollisionWithArgumentsInGeneratedCode(node); if (compilerOptions.noImplicitAny && !node.type) { switch (node.kind) { - case 140 /* ConstructSignature */: + case 141 /* ConstructSignature */: error(node, ts.Diagnostics.Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type); break; - case 139 /* CallSignature */: + case 140 /* CallSignature */: error(node, ts.Diagnostics.Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type); break; } } + if (node.type) { + if (languageVersion >= 2 /* ES6 */ && isSyntacticallyValidGenerator(node)) { + var returnType = getTypeFromTypeNode(node.type); + if (returnType === voidType) { + error(node.type, ts.Diagnostics.A_generator_cannot_have_a_void_type_annotation); + } + else { + var generatorElementType = getElementTypeOfIterableIterator(returnType) || anyType; + var iterableIteratorInstantiation = createIterableIteratorType(generatorElementType); + // 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); + } + } + } } checkSpecializedSignatureDeclaration(node); } function checkTypeForDuplicateIndexSignatures(node) { - if (node.kind === 203 /* InterfaceDeclaration */) { + if (node.kind === 205 /* 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 @@ -18365,7 +20206,7 @@ var ts; var declaration = decl; if (declaration.parameters.length === 1 && declaration.parameters[0].type) { switch (declaration.parameters[0].type.kind) { - case 122 /* StringKeyword */: + case 123 /* StringKeyword */: if (!seenStringIndexer) { seenStringIndexer = true; } @@ -18373,7 +20214,7 @@ var ts; error(declaration, ts.Diagnostics.Duplicate_string_index_signature); } break; - case 120 /* NumberKeyword */: + case 121 /* NumberKeyword */: if (!seenNumericIndexer) { seenNumericIndexer = true; } @@ -18417,17 +20258,17 @@ var ts; return; } function isSuperCallExpression(n) { - return n.kind === 158 /* CallExpression */ && n.expression.kind === 91 /* SuperKeyword */; + return n.kind === 160 /* CallExpression */ && n.expression.kind === 91 /* SuperKeyword */; } function containsSuperCall(n) { if (isSuperCallExpression(n)) { return true; } switch (n.kind) { - case 163 /* FunctionExpression */: - case 201 /* FunctionDeclaration */: - case 164 /* ArrowFunction */: - case 155 /* ObjectLiteralExpression */: return false; + case 165 /* FunctionExpression */: + case 203 /* FunctionDeclaration */: + case 166 /* ArrowFunction */: + case 157 /* ObjectLiteralExpression */: return false; default: return ts.forEachChild(n, containsSuperCall); } } @@ -18435,12 +20276,12 @@ var ts; if (n.kind === 93 /* ThisKeyword */) { error(n, ts.Diagnostics.this_cannot_be_referenced_in_current_location); } - else if (n.kind !== 163 /* FunctionExpression */ && n.kind !== 201 /* FunctionDeclaration */) { + else if (n.kind !== 165 /* FunctionExpression */ && n.kind !== 203 /* FunctionDeclaration */) { ts.forEachChild(n, markThisReferencesAsErrors); } } function isInstancePropertyWithInitializer(n) { - return n.kind === 133 /* PropertyDeclaration */ && + return n.kind === 134 /* PropertyDeclaration */ && !(n.flags & 128 /* Static */) && !!n.initializer; } @@ -18457,7 +20298,7 @@ var ts; ts.forEach(node.parameters, function (p) { return p.flags & (16 /* Public */ | 32 /* Private */ | 64 /* Protected */); }); if (superCallShouldBeFirst) { var statements = node.body.statements; - if (!statements.length || statements[0].kind !== 183 /* ExpressionStatement */ || !isSuperCallExpression(statements[0].expression)) { + if (!statements.length || statements[0].kind !== 185 /* ExpressionStatement */ || !isSuperCallExpression(statements[0].expression)) { 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 { @@ -18475,7 +20316,7 @@ var ts; if (produceDiagnostics) { // Grammar checking accessors checkGrammarFunctionLikeDeclaration(node) || checkGrammarAccessor(node) || checkGrammarComputedPropertyName(node.name); - if (node.kind === 137 /* GetAccessor */) { + if (node.kind === 138 /* GetAccessor */) { if (!ts.isInAmbientContext(node) && ts.nodeIsPresent(node.body) && !(bodyContainsAReturnStatement(node.body) || bodyContainsSingleThrowStatement(node.body))) { error(node.name, ts.Diagnostics.A_get_accessor_must_return_a_value_or_consist_of_a_single_throw_statement); } @@ -18483,7 +20324,7 @@ var ts; 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 === 137 /* GetAccessor */ ? 138 /* SetAccessor */ : 137 /* GetAccessor */; + var otherKind = node.kind === 138 /* GetAccessor */ ? 139 /* SetAccessor */ : 138 /* GetAccessor */; var otherAccessor = ts.getDeclarationOfKind(node.symbol, otherKind); if (otherAccessor) { if (((node.flags & 112 /* AccessibilityModifier */) !== (otherAccessor.flags & 112 /* AccessibilityModifier */))) { @@ -18507,28 +20348,27 @@ var ts; function checkMissingDeclaration(node) { checkDecorators(node); } + function checkTypeArgumentConstraints(typeParameters, typeArguments) { + var result = true; + for (var i = 0; i < typeParameters.length; i++) { + var constraint = getConstraintOfTypeParameter(typeParameters[i]); + if (constraint) { + var typeArgument = typeArguments[i]; + result = result && checkTypeAssignableTo(getTypeFromTypeNode(typeArgument), constraint, typeArgument, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); + } + } + return result; + } function checkTypeReferenceNode(node) { - checkGrammarTypeReferenceInStrictMode(node.typeName); - return checkTypeReferenceOrExpressionWithTypeArguments(node); - } - function checkExpressionWithTypeArguments(node) { - checkGrammarExpressionWithTypeArgumentsInStrictMode(node.expression); - return checkTypeReferenceOrExpressionWithTypeArguments(node); - } - function checkTypeReferenceOrExpressionWithTypeArguments(node) { - // Grammar checking checkGrammarTypeArguments(node, node.typeArguments); - var type = getTypeFromTypeReferenceOrExpressionWithTypeArguments(node); + var type = getTypeFromTypeReference(node); if (type !== unknownType && node.typeArguments) { // Do type argument local checks only if referenced type is successfully resolved - var len = node.typeArguments.length; - for (var i = 0; i < len; i++) { - checkSourceElement(node.typeArguments[i]); - var constraint = getConstraintOfTypeParameter(type.target.typeParameters[i]); - if (produceDiagnostics && constraint) { - var typeArgument = type.typeArguments[i]; - checkTypeAssignableTo(typeArgument, constraint, node, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); - } + 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); } } } @@ -18580,9 +20420,9 @@ var ts; var signaturesToCheck; // Unnamed (call\construct) signatures in interfaces are inherited and not shadowed so examining just node symbol won't give complete answer. // Use declaring type to obtain full list of signatures. - if (!signatureDeclarationNode.name && signatureDeclarationNode.parent && signatureDeclarationNode.parent.kind === 203 /* InterfaceDeclaration */) { - ts.Debug.assert(signatureDeclarationNode.kind === 139 /* CallSignature */ || signatureDeclarationNode.kind === 140 /* ConstructSignature */); - var signatureKind = signatureDeclarationNode.kind === 139 /* CallSignature */ ? 0 /* Call */ : 1 /* Construct */; + if (!signatureDeclarationNode.name && signatureDeclarationNode.parent && signatureDeclarationNode.parent.kind === 205 /* InterfaceDeclaration */) { + ts.Debug.assert(signatureDeclarationNode.kind === 140 /* CallSignature */ || signatureDeclarationNode.kind === 141 /* ConstructSignature */); + var signatureKind = signatureDeclarationNode.kind === 140 /* CallSignature */ ? 0 /* Call */ : 1 /* Construct */; var containingSymbol = getSymbolOfNode(signatureDeclarationNode.parent); var containingType = getDeclaredTypeOfSymbol(containingSymbol); signaturesToCheck = getSignaturesOfType(containingType, signatureKind); @@ -18600,7 +20440,7 @@ var ts; } function getEffectiveDeclarationFlags(n, flagsToCheck) { var flags = ts.getCombinedNodeFlags(n); - if (n.parent.kind !== 203 /* InterfaceDeclaration */ && ts.isInAmbientContext(n)) { + if (n.parent.kind !== 205 /* InterfaceDeclaration */ && ts.isInAmbientContext(n)) { if (!(flags & 2 /* Ambient */)) { // It is nested in an ambient context, which means it is automatically exported flags |= 1 /* Export */; @@ -18683,7 +20523,7 @@ var ts; // TODO(jfreeman): These are methods, so handle computed name case if (node.name && subsequentNode.name && node.name.text === subsequentNode.name.text) { // the only situation when this is possible (same kind\same name but different symbol) - mixed static and instance class members - ts.Debug.assert(node.kind === 135 /* MethodDeclaration */ || node.kind === 134 /* MethodSignature */); + ts.Debug.assert(node.kind === 136 /* MethodDeclaration */ || node.kind === 135 /* MethodSignature */); ts.Debug.assert((node.flags & 128 /* Static */) !== (subsequentNode.flags & 128 /* Static */)); var diagnostic = node.flags & 128 /* Static */ ? ts.Diagnostics.Function_overload_must_be_static : ts.Diagnostics.Function_overload_must_not_be_static; error(errorNode_1, diagnostic); @@ -18712,7 +20552,7 @@ var ts; var current = declarations[_i]; var node = current; var inAmbientContext = ts.isInAmbientContext(node); - var inAmbientContextOrInterface = node.parent.kind === 203 /* InterfaceDeclaration */ || node.parent.kind === 146 /* TypeLiteral */ || inAmbientContext; + var inAmbientContextOrInterface = node.parent.kind === 205 /* InterfaceDeclaration */ || node.parent.kind === 148 /* TypeLiteral */ || inAmbientContext; if (inAmbientContextOrInterface) { // check if declarations are consecutive only if they are non-ambient // 1. ambient declarations can be interleaved @@ -18723,7 +20563,7 @@ var ts; // 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 === 201 /* FunctionDeclaration */ || node.kind === 135 /* MethodDeclaration */ || node.kind === 134 /* MethodSignature */ || node.kind === 136 /* Constructor */) { + if (node.kind === 203 /* FunctionDeclaration */ || node.kind === 136 /* MethodDeclaration */ || node.kind === 135 /* MethodSignature */ || node.kind === 137 /* Constructor */) { var currentNodeFlags = getEffectiveDeclarationFlags(node, flagsToCheck); someNodeFlags |= currentNodeFlags; allNodeFlags &= currentNodeFlags; @@ -18846,16 +20686,16 @@ var ts; } function getDeclarationSpaces(d) { switch (d.kind) { - case 203 /* InterfaceDeclaration */: + case 205 /* InterfaceDeclaration */: return 2097152 /* ExportType */; - case 206 /* ModuleDeclaration */: + case 208 /* ModuleDeclaration */: return d.name.kind === 8 /* StringLiteral */ || ts.getModuleInstanceState(d) !== 0 /* NonInstantiated */ ? 4194304 /* ExportNamespace */ | 1048576 /* ExportValue */ : 4194304 /* ExportNamespace */; - case 202 /* ClassDeclaration */: - case 205 /* EnumDeclaration */: + case 204 /* ClassDeclaration */: + case 207 /* EnumDeclaration */: return 2097152 /* ExportType */ | 1048576 /* ExportValue */; - case 209 /* ImportEqualsDeclaration */: + case 211 /* ImportEqualsDeclaration */: var result = 0; var target = resolveAlias(getSymbolOfNode(d)); ts.forEach(target.declarations, function (d) { result |= getDeclarationSpaces(d); }); @@ -18870,23 +20710,23 @@ var ts; var expression = node.expression; var exprType = checkExpression(expression); switch (node.parent.kind) { - case 202 /* ClassDeclaration */: + case 204 /* ClassDeclaration */: var classSymbol = getSymbolOfNode(node.parent); var classConstructorType = getTypeOfSymbol(classSymbol); var classDecoratorType = instantiateSingleCallFunctionType(getGlobalClassDecoratorType(), [classConstructorType]); checkTypeAssignableTo(exprType, classDecoratorType, node); break; - case 133 /* PropertyDeclaration */: + case 134 /* PropertyDeclaration */: checkTypeAssignableTo(exprType, getGlobalPropertyDecoratorType(), node); break; - case 135 /* MethodDeclaration */: - case 137 /* GetAccessor */: - case 138 /* SetAccessor */: + case 136 /* MethodDeclaration */: + case 138 /* GetAccessor */: + case 139 /* SetAccessor */: var methodType = getTypeOfNode(node.parent); var methodDecoratorType = instantiateSingleCallFunctionType(getGlobalMethodDecoratorType(), [methodType]); checkTypeAssignableTo(exprType, methodDecoratorType, node); break; - case 130 /* Parameter */: + case 131 /* Parameter */: checkTypeAssignableTo(exprType, getGlobalParameterDecoratorType(), node); break; } @@ -18896,14 +20736,14 @@ var ts; // When we are emitting type metadata for decorators, we need to try to check the type // as if it were an expression so that we can emit the type in a value position when we // serialize the type metadata. - if (node && node.kind === 142 /* TypeReference */) { + if (node && node.kind === 144 /* TypeReference */) { var type = getTypeFromTypeNode(node); - var shouldCheckIfUnknownType = type === unknownType && compilerOptions.separateCompilation; - if (!type || (!shouldCheckIfUnknownType && type.flags & (1048703 /* Intrinsic */ | 132 /* NumberLike */ | 258 /* StringLike */))) { + var shouldCheckIfUnknownType = type === unknownType && compilerOptions.isolatedModules; + if (!type || (!shouldCheckIfUnknownType && type.flags & (2097279 /* Intrinsic */ | 132 /* NumberLike */ | 258 /* StringLike */))) { return; } if (shouldCheckIfUnknownType || type.symbol.valueDeclaration) { - checkExpressionOrQualifiedName(node.typeName); + checkExpression(node.typeName); } } } @@ -18913,19 +20753,19 @@ var ts; */ function checkTypeAnnotationAsExpression(node) { switch (node.kind) { - case 133 /* PropertyDeclaration */: + case 134 /* PropertyDeclaration */: checkTypeNodeAsExpression(node.type); break; - case 130 /* Parameter */: + case 131 /* Parameter */: checkTypeNodeAsExpression(node.type); break; - case 135 /* MethodDeclaration */: + case 136 /* MethodDeclaration */: checkTypeNodeAsExpression(node.type); break; - case 137 /* GetAccessor */: + case 138 /* GetAccessor */: checkTypeNodeAsExpression(node.type); break; - case 138 /* SetAccessor */: + case 139 /* SetAccessor */: checkTypeNodeAsExpression(getSetAccessorTypeAnnotationNode(node)); break; } @@ -18948,51 +20788,50 @@ var ts; 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_Specify_experimentalDecorators_to_remove_this_warning); + } if (compilerOptions.emitDecoratorMetadata) { // we only need to perform these checks if we are emitting serialized type metadata for the target of a decorator. switch (node.kind) { - case 202 /* ClassDeclaration */: + case 204 /* ClassDeclaration */: var constructor = ts.getFirstConstructorWithBody(node); if (constructor) { checkParameterTypeAnnotationsAsExpressions(constructor); } break; - case 135 /* MethodDeclaration */: + case 136 /* MethodDeclaration */: checkParameterTypeAnnotationsAsExpressions(node); // fall-through - case 138 /* SetAccessor */: - case 137 /* GetAccessor */: - case 133 /* PropertyDeclaration */: - case 130 /* Parameter */: + case 139 /* SetAccessor */: + case 138 /* GetAccessor */: + case 134 /* PropertyDeclaration */: + case 131 /* Parameter */: checkTypeAnnotationAsExpression(node); break; } } emitDecorate = true; - if (node.kind === 130 /* Parameter */) { + if (node.kind === 131 /* Parameter */) { emitParam = true; } ts.forEach(node.decorators, checkDecorator); } function checkFunctionDeclaration(node) { if (produceDiagnostics) { - checkFunctionLikeDeclaration(node) || - checkGrammarDisallowedModifiersInBlockOrObjectLiteralExpression(node) || - checkGrammarFunctionName(node.name) || - checkGrammarForGenerator(node); + checkFunctionLikeDeclaration(node) || checkGrammarForGenerator(node); checkCollisionWithCapturedSuperVariable(node, node.name); checkCollisionWithCapturedThisVariable(node, node.name); checkCollisionWithRequireExportsInGeneratedCode(node, node.name); } } function checkFunctionLikeDeclaration(node) { - checkGrammarDeclarationNameInStrictMode(node); checkDecorators(node); checkSignatureDeclaration(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 === 128 /* ComputedPropertyName */) { + if (node.name && node.name.kind === 129 /* ComputedPropertyName */) { // This check will account for methods in class/interface declarations, // as well as accessors in classes/object literals checkComputedPropertyName(node.name); @@ -19020,25 +20859,33 @@ var ts; if (node.type && !isAccessor(node.kind) && !node.asteriskToken) { checkIfNonVoidFunctionHasReturnExpressionsOrSingleThrowStatment(node, getTypeFromTypeNode(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 (compilerOptions.noImplicitAny && ts.nodeIsMissing(node.body) && !node.type && !isPrivateWithinAmbient(node)) { - reportImplicitAnyError(node, anyType); + 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 (compilerOptions.noImplicitAny && ts.nodeIsMissing(node.body) && !isPrivateWithinAmbient(node)) { + reportImplicitAnyError(node, anyType); + } + if (node.asteriskToken && 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)); + } } } function checkBlock(node) { // Grammar checking for SyntaxKind.Block - if (node.kind === 180 /* Block */) { + if (node.kind === 182 /* Block */) { checkGrammarStatementInAmbientContext(node); } ts.forEach(node.statements, checkSourceElement); - if (ts.isFunctionBlock(node) || node.kind === 207 /* ModuleBlock */) { + if (ts.isFunctionBlock(node) || node.kind === 209 /* ModuleBlock */) { checkFunctionExpressionBodies(node); } } function checkCollisionWithArgumentsInGeneratedCode(node) { // no rest parameters \ declaration context \ overload - no codegen impact - if (!ts.hasRestParameters(node) || ts.isInAmbientContext(node) || ts.nodeIsMissing(node.body)) { + if (!ts.hasRestParameter(node) || ts.isInAmbientContext(node) || ts.nodeIsMissing(node.body)) { return; } ts.forEach(node.parameters, function (p) { @@ -19051,12 +20898,12 @@ var ts; if (!(identifier && identifier.text === name)) { return false; } - if (node.kind === 133 /* PropertyDeclaration */ || - node.kind === 132 /* PropertySignature */ || - node.kind === 135 /* MethodDeclaration */ || - node.kind === 134 /* MethodSignature */ || - node.kind === 137 /* GetAccessor */ || - node.kind === 138 /* SetAccessor */) { + if (node.kind === 134 /* PropertyDeclaration */ || + node.kind === 133 /* PropertySignature */ || + node.kind === 136 /* MethodDeclaration */ || + node.kind === 135 /* MethodSignature */ || + node.kind === 138 /* GetAccessor */ || + node.kind === 139 /* SetAccessor */) { // it is ok to have member named '_super' or '_this' - member access is always qualified return false; } @@ -19065,7 +20912,7 @@ var ts; return false; } var root = ts.getRootDeclaration(node); - if (root.kind === 130 /* Parameter */ && ts.nodeIsMissing(root.parent.body)) { + if (root.kind === 131 /* Parameter */ && ts.nodeIsMissing(root.parent.body)) { // just an overload - no codegen impact return false; } @@ -19098,7 +20945,7 @@ var ts; return; } // bubble up and find containing type - var enclosingClass = ts.getAncestor(node, 202 /* ClassDeclaration */); + var enclosingClass = ts.getAncestor(node, 204 /* ClassDeclaration */); // if containing type was not found or it is ambient - exit (no codegen) if (!enclosingClass || ts.isInAmbientContext(enclosingClass)) { return; @@ -19118,12 +20965,12 @@ var ts; return; } // Uninstantiated modules shouldnt do this check - if (node.kind === 206 /* ModuleDeclaration */ && ts.getModuleInstanceState(node) !== 1 /* Instantiated */) { + if (node.kind === 208 /* 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 === 228 /* SourceFile */ && ts.isExternalModule(parent)) { + if (parent.kind === 230 /* SourceFile */ && ts.isExternalModule(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)); } @@ -19158,7 +21005,7 @@ var ts; // 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 === 199 /* VariableDeclaration */ && !node.initializer) { + if (node.kind === 201 /* VariableDeclaration */ && !node.initializer) { return; } var symbol = getSymbolOfNode(node); @@ -19168,24 +21015,24 @@ var ts; localDeclarationSymbol !== symbol && localDeclarationSymbol.flags & 2 /* BlockScopedVariable */) { if (getDeclarationFlagsFromSymbol(localDeclarationSymbol) & 12288 /* BlockScoped */) { - var varDeclList = ts.getAncestor(localDeclarationSymbol.valueDeclaration, 200 /* VariableDeclarationList */); - var container = varDeclList.parent.kind === 181 /* VariableStatement */ && varDeclList.parent.parent + var varDeclList = ts.getAncestor(localDeclarationSymbol.valueDeclaration, 202 /* VariableDeclarationList */); + var container = varDeclList.parent.kind === 183 /* 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 === 180 /* Block */ && ts.isFunctionLike(container.parent) || - container.kind === 207 /* ModuleBlock */ || - container.kind === 206 /* ModuleDeclaration */ || - container.kind === 228 /* SourceFile */); + (container.kind === 182 /* Block */ && ts.isFunctionLike(container.parent) || + container.kind === 209 /* ModuleBlock */ || + container.kind === 208 /* ModuleDeclaration */ || + container.kind === 230 /* 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_9 = symbolToString(localDeclarationSymbol); - error(node, ts.Diagnostics.Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1, name_9, name_9); + var name_13 = symbolToString(localDeclarationSymbol); + error(node, ts.Diagnostics.Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1, name_13, name_13); } } } @@ -19193,7 +21040,7 @@ var ts; } // Check that a parameter initializer contains no references to parameters declared to the right of itself function checkParameterInitializer(node) { - if (ts.getRootDeclaration(node).kind !== 130 /* Parameter */) { + if (ts.getRootDeclaration(node).kind !== 131 /* Parameter */) { return; } var func = ts.getContainingFunction(node); @@ -19204,7 +21051,7 @@ var ts; // check FunctionLikeDeclaration.locals (stores parameters\function local variable) // if it contains entry with a specified name and if this entry matches the resolved symbol if (referencedSymbol && referencedSymbol !== unknownSymbol && getSymbol(func.locals, referencedSymbol.name, 107455 /* Value */) === referencedSymbol) { - if (referencedSymbol.valueDeclaration.kind === 130 /* Parameter */) { + if (referencedSymbol.valueDeclaration.kind === 131 /* Parameter */) { if (referencedSymbol.valueDeclaration === node) { error(n, ts.Diagnostics.Parameter_0_cannot_be_referenced_in_its_initializer, ts.declarationNameToString(node.name)); return; @@ -19224,14 +21071,13 @@ var ts; } // Check variable, parameter, or property declaration function checkVariableLikeDeclaration(node) { - checkGrammarDeclarationNameInStrictMode(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 === 128 /* ComputedPropertyName */) { + if (node.name.kind === 129 /* ComputedPropertyName */) { checkComputedPropertyName(node.name); if (node.initializer) { checkExpressionCached(node.initializer); @@ -19242,7 +21088,7 @@ var ts; 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 === 130 /* Parameter */ && ts.nodeIsMissing(ts.getContainingFunction(node).body)) { + if (node.initializer && ts.getRootDeclaration(node).kind === 131 /* Parameter */ && ts.nodeIsMissing(ts.getContainingFunction(node).body)) { error(node, ts.Diagnostics.A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation); return; } @@ -19274,10 +21120,10 @@ var ts; checkTypeAssignableTo(checkExpressionCached(node.initializer), declarationType, node, undefined); } } - if (node.kind !== 133 /* PropertyDeclaration */ && node.kind !== 132 /* PropertySignature */) { + if (node.kind !== 134 /* PropertyDeclaration */ && node.kind !== 133 /* PropertySignature */) { // We know we don't have a binding pattern or computed name here checkExportsOnMergedDeclarations(node); - if (node.kind === 199 /* VariableDeclaration */ || node.kind === 153 /* BindingElement */) { + if (node.kind === 201 /* VariableDeclaration */ || node.kind === 155 /* BindingElement */) { checkVarDeclaredNamesNotShadowed(node); } checkCollisionWithCapturedSuperVariable(node, node.name); @@ -19295,7 +21141,7 @@ var ts; } function checkVariableStatement(node) { // Grammar checking - checkGrammarDecorators(node) || checkGrammarDisallowedModifiersInBlockOrObjectLiteralExpression(node) || checkGrammarModifiers(node) || checkGrammarVariableDeclarationList(node.declarationList) || checkGrammarForDisallowedLetOrConstStatement(node); + checkGrammarDecorators(node) || checkGrammarModifiers(node) || checkGrammarVariableDeclarationList(node.declarationList) || checkGrammarForDisallowedLetOrConstStatement(node); ts.forEach(node.declarationList.declarations, checkSourceElement); } function checkGrammarDisallowedModifiersInBlockOrObjectLiteralExpression(node) { @@ -19307,7 +21153,7 @@ var ts; } function inBlockOrObjectLiteralExpression(node) { while (node) { - if (node.kind === 180 /* Block */ || node.kind === 155 /* ObjectLiteralExpression */) { + if (node.kind === 182 /* Block */ || node.kind === 157 /* ObjectLiteralExpression */) { return true; } node = node.parent; @@ -19340,12 +21186,12 @@ var ts; function checkForStatement(node) { // Grammar checking if (!checkGrammarStatementInAmbientContext(node)) { - if (node.initializer && node.initializer.kind == 200 /* VariableDeclarationList */) { + if (node.initializer && node.initializer.kind === 202 /* VariableDeclarationList */) { checkGrammarVariableDeclarationList(node.initializer); } } if (node.initializer) { - if (node.initializer.kind === 200 /* VariableDeclarationList */) { + if (node.initializer.kind === 202 /* VariableDeclarationList */) { ts.forEach(node.initializer.declarations, checkVariableDeclaration); } else { @@ -19365,14 +21211,14 @@ var ts; // 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 === 200 /* VariableDeclarationList */) { + if (node.initializer.kind === 202 /* VariableDeclarationList */) { checkForInOrForOfVariableDeclaration(node); } else { var varExpr = node.initializer; var iteratedType = checkRightHandSideOfForOf(node.expression); // There may be a destructuring assignment on the left side - if (varExpr.kind === 154 /* ArrayLiteralExpression */ || varExpr.kind === 155 /* ObjectLiteralExpression */) { + if (varExpr.kind === 156 /* ArrayLiteralExpression */ || varExpr.kind === 157 /* 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. @@ -19385,7 +21231,7 @@ var ts; // 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 - // getIteratedType. + // getElementTypeOfIterable. if (iteratedType) { checkTypeAssignableTo(iteratedType, leftType, varExpr, undefined); } @@ -19401,7 +21247,7 @@ var ts; // 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 === 200 /* VariableDeclarationList */) { + if (node.initializer.kind === 202 /* 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); @@ -19415,10 +21261,10 @@ var ts; // 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 === 154 /* ArrayLiteralExpression */ || varExpr.kind === 155 /* ObjectLiteralExpression */) { + if (varExpr.kind === 156 /* ArrayLiteralExpression */ || varExpr.kind === 157 /* ObjectLiteralExpression */) { error(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern); } - else if (!allConstituentTypesHaveKind(leftType, 1 /* Any */ | 258 /* StringLike */)) { + else if (!isTypeAnyOrAllConstituentTypesHaveKind(leftType, 258 /* StringLike */)) { error(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any); } else { @@ -19429,7 +21275,7 @@ var ts; var rightType = checkExpression(node.expression); // 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 (!allConstituentTypesHaveKind(rightType, 1 /* Any */ | 48128 /* ObjectType */ | 512 /* TypeParameter */)) { + if (!isTypeAnyOrAllConstituentTypesHaveKind(rightType, 48128 /* ObjectType */ | 512 /* TypeParameter */)) { 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); @@ -19447,11 +21293,11 @@ var ts; return checkIteratedTypeOrElementType(expressionType, rhsExpression, true); } function checkIteratedTypeOrElementType(inputType, errorNode, allowStringInput) { - if (inputType.flags & 1 /* Any */) { + if (isTypeAny(inputType)) { return inputType; } if (languageVersion >= 2 /* ES6 */) { - return checkIteratedType(inputType, errorNode) || anyType; + return checkElementTypeOfIterable(inputType, errorNode); } if (allowStringInput) { return checkElementTypeOfArrayOrString(inputType, errorNode); @@ -19468,88 +21314,127 @@ var ts; /** * When errorNode is undefined, it means we should not report any errors. */ - function checkIteratedType(iterable, errorNode) { - ts.Debug.assert(languageVersion >= 2 /* ES6 */); - var iteratedType = getIteratedType(iterable, errorNode); + function checkElementTypeOfIterable(iterable, errorNode) { + var elementType = getElementTypeOfIterable(iterable, errorNode); // Now even though we have extracted the iteratedType, we will have to validate that the type // passed in is actually an Iterable. - if (errorNode && iteratedType) { - checkTypeAssignableTo(iterable, createIterableType(iteratedType), errorNode); + if (errorNode && elementType) { + checkTypeAssignableTo(iterable, createIterableType(elementType), errorNode); } - return iteratedType; - function getIteratedType(iterable, errorNode) { - // 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]: { // iteratorFunction - // (): { // iterator - // next: { // iteratorNextFunction - // (): { // iteratorNextResult - // value: T // iteratorNextValue - // } - // } - // } - // } - // } - // - // 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'. - if (allConstituentTypesHaveKind(iterable, 1 /* Any */)) { - return undefined; - } + return elementType || anyType; + } + /** + * 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]: { // iteratorFunction + * (): Iterator + * } + * } + * + * 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'. + */ + function getElementTypeOfIterable(type, errorNode) { + if (isTypeAny(type)) { + return undefined; + } + var typeAsIterable = type; + if (!typeAsIterable.iterableElementType) { // As an optimization, if the type is instantiated directly using the globalIterableType (Iterable), // then just grab its type argument. - if ((iterable.flags & 4096 /* Reference */) && iterable.target === globalIterableType) { - return iterable.typeArguments[0]; + if ((type.flags & 4096 /* Reference */) && type.target === globalIterableType) { + typeAsIterable.iterableElementType = type.typeArguments[0]; } - var iteratorFunction = getTypeOfPropertyOfType(iterable, ts.getPropertyNameForKnownSymbolName("iterator")); - if (iteratorFunction && allConstituentTypesHaveKind(iteratorFunction, 1 /* Any */)) { - return undefined; - } - var iteratorFunctionSignatures = iteratorFunction ? getSignaturesOfType(iteratorFunction, 0 /* Call */) : emptyArray; - if (iteratorFunctionSignatures.length === 0) { - if (errorNode) { - error(errorNode, ts.Diagnostics.Type_must_have_a_Symbol_iterator_method_that_returns_an_iterator); + else { + var iteratorFunction = getTypeOfPropertyOfType(type, ts.getPropertyNameForKnownSymbolName("iterator")); + if (isTypeAny(iteratorFunction)) { + return undefined; } - return undefined; - } - var iterator = getUnionType(ts.map(iteratorFunctionSignatures, getReturnTypeOfSignature)); - if (allConstituentTypesHaveKind(iterator, 1 /* Any */)) { - return undefined; - } - var iteratorNextFunction = getTypeOfPropertyOfType(iterator, "next"); - if (iteratorNextFunction && allConstituentTypesHaveKind(iteratorNextFunction, 1 /* Any */)) { - return undefined; - } - var iteratorNextFunctionSignatures = iteratorNextFunction ? getSignaturesOfType(iteratorNextFunction, 0 /* Call */) : emptyArray; - if (iteratorNextFunctionSignatures.length === 0) { - if (errorNode) { - error(errorNode, ts.Diagnostics.An_iterator_must_have_a_next_method); + var iteratorFunctionSignatures = iteratorFunction ? getSignaturesOfType(iteratorFunction, 0 /* Call */) : emptyArray; + if (iteratorFunctionSignatures.length === 0) { + if (errorNode) { + error(errorNode, ts.Diagnostics.Type_must_have_a_Symbol_iterator_method_that_returns_an_iterator); + } + return undefined; } - return undefined; + typeAsIterable.iterableElementType = getElementTypeOfIterator(getUnionType(ts.map(iteratorFunctionSignatures, getReturnTypeOfSignature)), errorNode); } - var iteratorNextResult = getUnionType(ts.map(iteratorNextFunctionSignatures, getReturnTypeOfSignature)); - if (allConstituentTypesHaveKind(iteratorNextResult, 1 /* Any */)) { - return undefined; - } - var iteratorNextValue = getTypeOfPropertyOfType(iteratorNextResult, "value"); - if (!iteratorNextValue) { - if (errorNode) { - error(errorNode, ts.Diagnostics.The_type_returned_by_the_next_method_of_an_iterator_must_have_a_value_property); - } - return undefined; - } - return iteratorNextValue; } + return typeAsIterable.iterableElementType; + } + /** + * This function has very similar logic as getElementTypeOfIterable, except that it operates on + * Iterators instead of Iterables. Here is the structure: + * + * { // iterator + * next: { // iteratorNextFunction + * (): { // iteratorNextResult + * value: T // iteratorNextValue + * } + * } + * } + * + */ + function getElementTypeOfIterator(type, errorNode) { + if (isTypeAny(type)) { + return undefined; + } + var typeAsIterator = type; + if (!typeAsIterator.iteratorElementType) { + // As an optimization, if the type is instantiated directly using the globalIteratorType (Iterator), + // then just grab its type argument. + if ((type.flags & 4096 /* Reference */) && type.target === globalIteratorType) { + typeAsIterator.iteratorElementType = type.typeArguments[0]; + } + else { + var iteratorNextFunction = getTypeOfPropertyOfType(type, "next"); + if (isTypeAny(iteratorNextFunction)) { + return undefined; + } + var iteratorNextFunctionSignatures = iteratorNextFunction ? getSignaturesOfType(iteratorNextFunction, 0 /* Call */) : emptyArray; + if (iteratorNextFunctionSignatures.length === 0) { + if (errorNode) { + error(errorNode, ts.Diagnostics.An_iterator_must_have_a_next_method); + } + return undefined; + } + var iteratorNextResult = getUnionType(ts.map(iteratorNextFunctionSignatures, getReturnTypeOfSignature)); + if (isTypeAny(iteratorNextResult)) { + return undefined; + } + var iteratorNextValue = getTypeOfPropertyOfType(iteratorNextResult, "value"); + if (!iteratorNextValue) { + if (errorNode) { + error(errorNode, ts.Diagnostics.The_type_returned_by_the_next_method_of_an_iterator_must_have_a_value_property); + } + return undefined; + } + typeAsIterator.iteratorElementType = iteratorNextValue; + } + } + return typeAsIterator.iteratorElementType; + } + function getElementTypeOfIterableIterator(type) { + if (isTypeAny(type)) { + return undefined; + } + // As an optimization, if the type is instantiated directly using the globalIterableIteratorType (IterableIterator), + // then just grab its type argument. + if ((type.flags & 4096 /* Reference */) && type.target === globalIterableIteratorType) { + return type.typeArguments[0]; + } + return getElementTypeOfIterable(type, undefined) || + getElementTypeOfIterator(type, undefined); } /** * This function does the following steps: @@ -19615,7 +21500,7 @@ var ts; // TODO: Check that target label is valid } function isGetAccessorWithAnnotatatedSetAccessor(node) { - return !!(node.kind === 137 /* GetAccessor */ && getSetAccessorTypeAnnotationNode(ts.getDeclarationOfKind(node.symbol, 138 /* SetAccessor */))); + return !!(node.kind === 138 /* GetAccessor */ && getSetAccessorTypeAnnotationNode(ts.getDeclarationOfKind(node.symbol, 139 /* SetAccessor */))); } function checkReturnStatement(node) { // Grammar checking @@ -19628,31 +21513,32 @@ var ts; if (node.expression) { var func = ts.getContainingFunction(node); if (func) { - var returnType = getReturnTypeOfSignature(getSignatureFromDeclaration(func)); + var signature = getSignatureFromDeclaration(func); + var returnType = getReturnTypeOfSignature(signature); var exprType = checkExpressionCached(node.expression); - if (func.kind === 138 /* SetAccessor */) { + if (func.asteriskToken) { + // 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 === 139 /* SetAccessor */) { error(node.expression, ts.Diagnostics.Setters_cannot_return_a_value); } - else { - if (func.kind === 136 /* Constructor */) { - if (!isTypeAssignableTo(exprType, returnType)) { - error(node.expression, ts.Diagnostics.Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class); - } - } - else if (func.type || isGetAccessorWithAnnotatatedSetAccessor(func)) { - checkTypeAssignableTo(exprType, returnType, node.expression, undefined); + else if (func.kind === 137 /* Constructor */) { + if (!isTypeAssignableTo(exprType, returnType)) { + error(node.expression, ts.Diagnostics.Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class); } } + else if (func.type || isGetAccessorWithAnnotatatedSetAccessor(func) || signature.typePredicate) { + checkTypeAssignableTo(exprType, returnType, node.expression, undefined); + } } } } function checkWithStatement(node) { - // Grammar checking for withStatement - if (!checkGrammarStatementInAmbientContext(node)) { - if (node.parserContextFlags & 1 /* StrictMode */) { - grammarErrorOnFirstToken(node, ts.Diagnostics.with_statements_are_not_allowed_in_strict_mode); - } - } + checkGrammarStatementInAmbientContext(node); checkExpression(node.expression); error(node.expression, ts.Diagnostics.All_symbols_within_a_with_block_will_be_resolved_to_any); } @@ -19664,7 +21550,7 @@ var ts; var expressionType = checkExpression(node.expression); ts.forEach(node.caseBlock.clauses, function (clause) { // Grammar check for duplicate default clauses, skip if we already report duplicate default clause - if (clause.kind === 222 /* DefaultClause */ && !hasDuplicateDefaultClause) { + if (clause.kind === 224 /* DefaultClause */ && !hasDuplicateDefaultClause) { if (firstDefaultClause === undefined) { firstDefaultClause = clause; } @@ -19676,7 +21562,7 @@ var ts; hasDuplicateDefaultClause = true; } } - if (produceDiagnostics && clause.kind === 221 /* CaseClause */) { + if (produceDiagnostics && clause.kind === 223 /* 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 assignable to or from the type of the 'switch' expression. @@ -19697,7 +21583,7 @@ var ts; if (ts.isFunctionLike(current)) { break; } - if (current.kind === 195 /* LabeledStatement */ && current.label.text === node.label.text) { + if (current.kind === 197 /* 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)); break; @@ -19745,9 +21631,6 @@ var ts; grammarErrorOnNode(localSymbol.valueDeclaration, ts.Diagnostics.Cannot_redeclare_identifier_0_in_catch_clause, identifierName); } } - // 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 - checkGrammarEvalOrArgumentsInStrictMode(node, catchClause.variableDeclaration.name); } } checkBlock(catchClause.block); @@ -19767,7 +21650,7 @@ var ts; checkIndexConstraintForProperty(prop, propType, type, declaredStringIndexer, stringIndexType, 0 /* String */); checkIndexConstraintForProperty(prop, propType, type, declaredNumberIndexer, numberIndexType, 1 /* Number */); }); - if (type.flags & 1024 /* Class */ && type.symbol.valueDeclaration.kind === 202 /* ClassDeclaration */) { + if (type.flags & 1024 /* Class */ && type.symbol.valueDeclaration.kind === 204 /* ClassDeclaration */) { var classDeclaration = type.symbol.valueDeclaration; for (var _i = 0, _a = classDeclaration.members; _i < _a.length; _i++) { var member = _a[_i]; @@ -19805,7 +21688,7 @@ var ts; // perform property check if property or indexer is declared in 'type' // this allows to rule out cases when both property and indexer are inherited from the base class var errorNode; - if (prop.valueDeclaration.name.kind === 128 /* ComputedPropertyName */ || prop.parent === containingType.symbol) { + if (prop.valueDeclaration.name.kind === 129 /* ComputedPropertyName */ || prop.parent === containingType.symbol) { errorNode = prop.valueDeclaration; } else if (indexDeclaration) { @@ -19861,11 +21744,7 @@ var ts; return unknownType; } function checkClassDeclaration(node) { - checkGrammarDeclarationNameInStrictMode(node); // Grammar checking - if (node.parent.kind !== 207 /* ModuleBlock */ && node.parent.kind !== 228 /* SourceFile */) { - grammarErrorOnNode(node, ts.Diagnostics.class_declarations_are_only_supported_directly_inside_a_module_or_as_a_top_level_declaration); - } if (!node.name && !(node.flags & 256 /* Default */)) { grammarErrorOnFirstToken(node, ts.Diagnostics.A_class_declaration_without_the_default_modifier_must_have_a_name); } @@ -19883,36 +21762,42 @@ var ts; var staticType = getTypeOfSymbol(symbol); var baseTypeNode = ts.getClassExtendsHeritageClauseElement(node); if (baseTypeNode) { - if (!ts.isSupportedExpressionWithTypeArguments(baseTypeNode)) { - error(baseTypeNode.expression, ts.Diagnostics.Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_class_extends_clauses); - } emitExtends = emitExtends || !ts.isInAmbientContext(node); - checkExpressionWithTypeArguments(baseTypeNode); - } - var baseTypes = getBaseTypes(type); - if (baseTypes.length) { - if (produceDiagnostics) { + var baseTypes = getBaseTypes(type); + if (baseTypes.length && produceDiagnostics) { var baseType = baseTypes[0]; + var staticBaseType = getBaseConstructorTypeOfClass(type); + if (baseTypeNode.typeArguments) { + ts.forEach(baseTypeNode.typeArguments, checkSourceElement); + for (var _i = 0, _a = getConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments); _i < _a.length; _i++) { + var constructor = _a[_i]; + if (!checkTypeArgumentConstraints(constructor.typeParameters, baseTypeNode.typeArguments)) { + break; + } + } + } checkTypeAssignableTo(type, baseType, node.name || node, ts.Diagnostics.Class_0_incorrectly_extends_base_class_1); - var staticBaseType = getTypeOfSymbol(baseType.symbol); - checkTypeAssignableTo(staticType, getTypeWithoutConstructors(staticBaseType), node.name || node, ts.Diagnostics.Class_static_side_0_incorrectly_extends_base_class_static_side_1); - if (baseType.symbol !== resolveEntityName(baseTypeNode.expression, 107455 /* Value */)) { - error(baseTypeNode, ts.Diagnostics.Type_name_0_in_extends_clause_does_not_reference_constructor_function_for_0, typeToString(baseType)); + checkTypeAssignableTo(staticType, getTypeWithoutSignatures(staticBaseType), node.name || node, ts.Diagnostics.Class_static_side_0_incorrectly_extends_base_class_static_side_1); + if (!(staticBaseType.symbol && staticBaseType.symbol.flags & 32 /* Class */)) { + // 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); + if (ts.forEach(constructors, function (sig) { return getReturnTypeOfSignature(sig) !== baseType; })) { + error(baseTypeNode.expression, ts.Diagnostics.Base_constructors_must_all_have_the_same_return_type); + } } checkKindsOfPropertyMemberOverrides(type, baseType); } } - if (baseTypes.length || (baseTypeNode && compilerOptions.separateCompilation)) { - // Check that base type can be evaluated as expression - checkExpressionOrQualifiedName(baseTypeNode.expression); - } var implementedTypeNodes = ts.getClassImplementsHeritageClauseElements(node); if (implementedTypeNodes) { ts.forEach(implementedTypeNodes, function (typeRefNode) { if (!ts.isSupportedExpressionWithTypeArguments(typeRefNode)) { error(typeRefNode.expression, ts.Diagnostics.A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments); } - checkExpressionWithTypeArguments(typeRefNode); + checkTypeReferenceNode(typeRefNode); if (produceDiagnostics) { var t = getTypeFromTypeNode(typeRefNode); if (t !== unknownType) { @@ -20000,7 +21885,7 @@ var ts; } } function isAccessor(kind) { - return kind === 137 /* GetAccessor */ || kind === 138 /* SetAccessor */; + return kind === 138 /* GetAccessor */ || kind === 139 /* SetAccessor */; } function areTypeParametersIdentical(list1, list2) { if (!list1 && !list2) { @@ -20064,13 +21949,13 @@ var ts; } function checkInterfaceDeclaration(node) { // Grammar checking - checkGrammarDeclarationNameInStrictMode(node) || checkGrammarDecorators(node) || checkGrammarModifiers(node) || checkGrammarInterfaceDeclaration(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); - var firstInterfaceDecl = ts.getDeclarationOfKind(symbol, 203 /* InterfaceDeclaration */); + var firstInterfaceDecl = ts.getDeclarationOfKind(symbol, 205 /* InterfaceDeclaration */); if (symbol.declarations.length > 1) { if (node !== firstInterfaceDecl && !areTypeParametersIdentical(firstInterfaceDecl.typeParameters, node.typeParameters)) { error(node.name, ts.Diagnostics.All_declarations_of_an_interface_must_have_identical_type_parameters); @@ -20092,7 +21977,7 @@ var ts; if (!ts.isSupportedExpressionWithTypeArguments(heritageElement)) { error(heritageElement.expression, ts.Diagnostics.An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments); } - checkExpressionWithTypeArguments(heritageElement); + checkTypeReferenceNode(heritageElement); }); ts.forEach(node.members, checkSourceElement); if (produceDiagnostics) { @@ -20114,7 +21999,7 @@ var ts; var ambient = ts.isInAmbientContext(node); var enumIsConst = ts.isConst(node); ts.forEach(node.members, function (member) { - if (member.name.kind !== 128 /* ComputedPropertyName */ && isNumericLiteralName(member.name.text)) { + if (member.name.kind !== 129 /* ComputedPropertyName */ && isNumericLiteralName(member.name.text)) { error(member.name, ts.Diagnostics.An_enum_member_cannot_have_a_numeric_name); } var initializer = member.initializer; @@ -20154,7 +22039,7 @@ var ts; return evalConstant(initializer); function evalConstant(e) { switch (e.kind) { - case 168 /* PrefixUnaryExpression */: + case 170 /* PrefixUnaryExpression */: var value = evalConstant(e.operand); if (value === undefined) { return undefined; @@ -20165,7 +22050,7 @@ var ts; case 47 /* TildeToken */: return ~value; } return undefined; - case 170 /* BinaryExpression */: + case 172 /* BinaryExpression */: var left = evalConstant(e.left); if (left === undefined) { return undefined; @@ -20190,11 +22075,11 @@ var ts; return undefined; case 7 /* NumericLiteral */: return +e.text; - case 162 /* ParenthesizedExpression */: + case 164 /* ParenthesizedExpression */: return evalConstant(e.expression); case 65 /* Identifier */: - case 157 /* ElementAccessExpression */: - case 156 /* PropertyAccessExpression */: + case 159 /* ElementAccessExpression */: + case 158 /* PropertyAccessExpression */: var member = initializer.parent; var currentType = getTypeOfSymbol(getSymbolOfNode(member.parent)); var enumType; @@ -20207,7 +22092,7 @@ var ts; } else { var expression; - if (e.kind === 157 /* ElementAccessExpression */) { + if (e.kind === 159 /* ElementAccessExpression */) { if (e.argumentExpression === undefined || e.argumentExpression.kind !== 8 /* StringLiteral */) { return undefined; @@ -20225,7 +22110,7 @@ var ts; if (current.kind === 65 /* Identifier */) { break; } - else if (current.kind === 156 /* PropertyAccessExpression */) { + else if (current.kind === 158 /* PropertyAccessExpression */) { current = current.expression; } else { @@ -20264,15 +22149,15 @@ var ts; return; } // Grammar checking - checkGrammarDeclarationNameInStrictMode(node) || checkGrammarDecorators(node) || checkGrammarModifiers(node) || checkGrammarEnumDeclaration(node); + checkGrammarDecorators(node) || checkGrammarModifiers(node) || checkGrammarEnumDeclaration(node); checkTypeNameIsReserved(node.name, ts.Diagnostics.Enum_name_cannot_be_0); checkCollisionWithCapturedThisVariable(node, node.name); checkCollisionWithRequireExportsInGeneratedCode(node, node.name); checkExportsOnMergedDeclarations(node); computeEnumMemberValues(node); var enumIsConst = ts.isConst(node); - if (compilerOptions.separateCompilation && enumIsConst && ts.isInAmbientContext(node)) { - error(node.name, ts.Diagnostics.Ambient_const_enums_are_not_allowed_when_the_separateCompilation_flag_is_provided); + 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, @@ -20294,7 +22179,7 @@ var ts; var seenEnumMissingInitialInitializer = false; ts.forEach(enumSymbol.declarations, function (declaration) { // return true if we hit a violation of the rule, false otherwise - if (declaration.kind !== 205 /* EnumDeclaration */) { + if (declaration.kind !== 207 /* EnumDeclaration */) { return false; } var enumDeclaration = declaration; @@ -20317,8 +22202,8 @@ var ts; var declarations = symbol.declarations; for (var _i = 0; _i < declarations.length; _i++) { var declaration = declarations[_i]; - if ((declaration.kind === 202 /* ClassDeclaration */ || - (declaration.kind === 201 /* FunctionDeclaration */ && ts.nodeIsPresent(declaration.body))) && + if ((declaration.kind === 204 /* ClassDeclaration */ || + (declaration.kind === 203 /* FunctionDeclaration */ && ts.nodeIsPresent(declaration.body))) && !ts.isInAmbientContext(declaration)) { return declaration; } @@ -20341,7 +22226,15 @@ var ts; function checkModuleDeclaration(node) { if (produceDiagnostics) { // Grammar checking - if (!checkGrammarDeclarationNameInStrictMode(node) && !checkGrammarDecorators(node) && !checkGrammarModifiers(node)) { + var isAmbientExternalModule = node.name.kind === 8 /* StringLiteral */; + 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 (!ts.isInAmbientContext(node) && node.name.kind === 8 /* StringLiteral */) { grammarErrorOnNode(node.name, ts.Diagnostics.Only_ambient_modules_can_use_quoted_names); } @@ -20354,7 +22247,7 @@ var ts; if (symbol.flags & 512 /* ValueModule */ && symbol.declarations.length > 1 && !ts.isInAmbientContext(node) - && ts.isInstantiatedModule(node, compilerOptions.preserveConstEnums || compilerOptions.separateCompilation)) { + && ts.isInstantiatedModule(node, compilerOptions.preserveConstEnums || compilerOptions.isolatedModules)) { var firstNonAmbientClassOrFunc = getFirstNonAmbientClassOrFunctionDeclaration(symbol); if (firstNonAmbientClassOrFunc) { if (ts.getSourceFileOfNode(node) !== ts.getSourceFileOfNode(firstNonAmbientClassOrFunc)) { @@ -20366,14 +22259,14 @@ var ts; } // 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, 202 /* ClassDeclaration */); + var mergedClass = ts.getDeclarationOfKind(symbol, 204 /* ClassDeclaration */); if (mergedClass && inSameLexicalScope(node, mergedClass)) { getNodeLinks(node).flags |= 2048 /* LexicalModuleMergesWithClass */; } } // Checks for ambient external modules. - if (node.name.kind === 8 /* StringLiteral */) { + if (isAmbientExternalModule) { if (!isGlobalSourceFile(node.parent)) { error(node.name, ts.Diagnostics.Ambient_modules_cannot_be_nested_in_other_modules); } @@ -20386,10 +22279,10 @@ var ts; } function getFirstIdentifier(node) { while (true) { - if (node.kind === 127 /* QualifiedName */) { + if (node.kind === 128 /* QualifiedName */) { node = node.left; } - else if (node.kind === 156 /* PropertyAccessExpression */) { + else if (node.kind === 158 /* PropertyAccessExpression */) { node = node.expression; } else { @@ -20405,9 +22298,9 @@ var ts; error(moduleName, ts.Diagnostics.String_literal_expected); return false; } - var inAmbientExternalModule = node.parent.kind === 207 /* ModuleBlock */ && node.parent.parent.name.kind === 8 /* StringLiteral */; - if (node.parent.kind !== 228 /* SourceFile */ && !inAmbientExternalModule) { - error(moduleName, node.kind === 216 /* ExportDeclaration */ ? + var inAmbientExternalModule = node.parent.kind === 209 /* ModuleBlock */ && node.parent.parent.name.kind === 8 /* StringLiteral */; + if (node.parent.kind !== 230 /* SourceFile */ && !inAmbientExternalModule) { + error(moduleName, node.kind === 218 /* ExportDeclaration */ ? ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace : ts.Diagnostics.Import_declarations_in_a_namespace_cannot_reference_a_module); return false; @@ -20430,7 +22323,7 @@ var ts; (symbol.flags & 793056 /* Type */ ? 793056 /* Type */ : 0) | (symbol.flags & 1536 /* Namespace */ ? 1536 /* Namespace */ : 0); if (target.flags & excludedMeanings) { - var message = node.kind === 218 /* ExportSpecifier */ ? + var message = node.kind === 220 /* 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)); @@ -20443,7 +22336,11 @@ var ts; checkAliasSymbol(node); } function checkImportDeclaration(node) { - if (!checkGrammarImportDeclarationNameInStrictMode(node) && !checkGrammarDecorators(node) && !checkGrammarModifiers(node) && (node.flags & 499 /* Modifier */)) { + 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) && (node.flags & 499 /* Modifier */)) { grammarErrorOnFirstToken(node, ts.Diagnostics.An_import_declaration_cannot_have_modifiers); } if (checkExternalImportOrExportDeclaration(node)) { @@ -20453,7 +22350,7 @@ var ts; checkImportBinding(importClause); } if (importClause.namedBindings) { - if (importClause.namedBindings.kind === 212 /* NamespaceImport */) { + if (importClause.namedBindings.kind === 214 /* NamespaceImport */) { checkImportBinding(importClause.namedBindings); } else { @@ -20464,7 +22361,11 @@ var ts; } } function checkImportEqualsDeclaration(node) { - checkGrammarDeclarationNameInStrictMode(node) || checkGrammarDecorators(node) || checkGrammarModifiers(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 (node.flags & 1 /* Export */) { @@ -20494,6 +22395,10 @@ var ts; } } 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) && (node.flags & 499 /* Modifier */)) { grammarErrorOnFirstToken(node, ts.Diagnostics.An_export_declaration_cannot_have_modifiers); } @@ -20502,8 +22407,8 @@ var ts; // export { x, y } // export { x, y } from "foo" ts.forEach(node.exportClause.elements, checkExportSpecifier); - var inAmbientExternalModule = node.parent.kind === 207 /* ModuleBlock */ && node.parent.parent.name.kind === 8 /* StringLiteral */; - if (node.parent.kind !== 228 /* SourceFile */ && !inAmbientExternalModule) { + var inAmbientExternalModule = node.parent.kind === 209 /* ModuleBlock */ && node.parent.parent.name.kind === 8 /* StringLiteral */; + if (node.parent.kind !== 230 /* SourceFile */ && !inAmbientExternalModule) { error(node, ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace); } } @@ -20516,6 +22421,11 @@ var ts; } } } + function checkGrammarModuleElementContext(node, errorMessage) { + if (node.parent.kind !== 230 /* SourceFile */ && node.parent.kind !== 209 /* ModuleBlock */ && node.parent.kind !== 208 /* ModuleDeclaration */) { + return grammarErrorOnFirstToken(node, errorMessage); + } + } function checkExportSpecifier(node) { checkAliasSymbol(node); if (!node.parent.parent.moduleSpecifier) { @@ -20523,8 +22433,12 @@ var ts; } } function checkExportAssignment(node) { - var container = node.parent.kind === 228 /* SourceFile */ ? node.parent : node.parent.parent; - if (container.kind === 206 /* ModuleDeclaration */ && container.name.kind === 65 /* Identifier */) { + 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 === 230 /* SourceFile */ ? node.parent : node.parent.parent; + if (container.kind === 208 /* ModuleDeclaration */ && container.name.kind === 65 /* Identifier */) { error(node, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_namespace); return; } @@ -20551,10 +22465,10 @@ var ts; } } function getModuleStatements(node) { - if (node.kind === 228 /* SourceFile */) { + if (node.kind === 230 /* SourceFile */) { return node.statements; } - if (node.kind === 206 /* ModuleDeclaration */ && node.body.kind === 207 /* ModuleBlock */) { + if (node.kind === 208 /* ModuleDeclaration */ && node.body.kind === 209 /* ModuleBlock */) { return node.body.statements; } return emptyArray; @@ -20579,111 +22493,118 @@ var ts; links.exportsChecked = true; } } + function checkTypePredicate(node) { + if (!isInLegalTypePredicatePosition(node)) { + error(node, ts.Diagnostics.A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods); + } + } function checkSourceElement(node) { if (!node) return; switch (node.kind) { - case 129 /* TypeParameter */: + case 130 /* TypeParameter */: return checkTypeParameter(node); - case 130 /* Parameter */: + case 131 /* Parameter */: return checkParameter(node); - case 133 /* PropertyDeclaration */: - case 132 /* PropertySignature */: + case 134 /* PropertyDeclaration */: + case 133 /* PropertySignature */: return checkPropertyDeclaration(node); - case 143 /* FunctionType */: - case 144 /* ConstructorType */: - case 139 /* CallSignature */: - case 140 /* ConstructSignature */: + case 145 /* FunctionType */: + case 146 /* ConstructorType */: + case 140 /* CallSignature */: + case 141 /* ConstructSignature */: return checkSignatureDeclaration(node); - case 141 /* IndexSignature */: + case 142 /* IndexSignature */: return checkSignatureDeclaration(node); - case 135 /* MethodDeclaration */: - case 134 /* MethodSignature */: + case 136 /* MethodDeclaration */: + case 135 /* MethodSignature */: return checkMethodDeclaration(node); - case 136 /* Constructor */: + case 137 /* Constructor */: return checkConstructorDeclaration(node); - case 137 /* GetAccessor */: - case 138 /* SetAccessor */: + case 138 /* GetAccessor */: + case 139 /* SetAccessor */: return checkAccessorDeclaration(node); - case 142 /* TypeReference */: + case 144 /* TypeReference */: return checkTypeReferenceNode(node); - case 145 /* TypeQuery */: + case 143 /* TypePredicate */: + return checkTypePredicate(node); + case 147 /* TypeQuery */: return checkTypeQuery(node); - case 146 /* TypeLiteral */: + case 148 /* TypeLiteral */: return checkTypeLiteral(node); - case 147 /* ArrayType */: + case 149 /* ArrayType */: return checkArrayType(node); - case 148 /* TupleType */: + case 150 /* TupleType */: return checkTupleType(node); - case 149 /* UnionType */: + case 151 /* UnionType */: return checkUnionType(node); - case 150 /* ParenthesizedType */: + case 152 /* ParenthesizedType */: return checkSourceElement(node.type); - case 201 /* FunctionDeclaration */: + case 203 /* FunctionDeclaration */: return checkFunctionDeclaration(node); - case 180 /* Block */: - case 207 /* ModuleBlock */: + case 182 /* Block */: + case 209 /* ModuleBlock */: return checkBlock(node); - case 181 /* VariableStatement */: + case 183 /* VariableStatement */: return checkVariableStatement(node); - case 183 /* ExpressionStatement */: + case 185 /* ExpressionStatement */: return checkExpressionStatement(node); - case 184 /* IfStatement */: + case 186 /* IfStatement */: return checkIfStatement(node); - case 185 /* DoStatement */: + case 187 /* DoStatement */: return checkDoStatement(node); - case 186 /* WhileStatement */: + case 188 /* WhileStatement */: return checkWhileStatement(node); - case 187 /* ForStatement */: + case 189 /* ForStatement */: return checkForStatement(node); - case 188 /* ForInStatement */: + case 190 /* ForInStatement */: return checkForInStatement(node); - case 189 /* ForOfStatement */: + case 191 /* ForOfStatement */: return checkForOfStatement(node); - case 190 /* ContinueStatement */: - case 191 /* BreakStatement */: + case 192 /* ContinueStatement */: + case 193 /* BreakStatement */: return checkBreakOrContinueStatement(node); - case 192 /* ReturnStatement */: + case 194 /* ReturnStatement */: return checkReturnStatement(node); - case 193 /* WithStatement */: + case 195 /* WithStatement */: return checkWithStatement(node); - case 194 /* SwitchStatement */: + case 196 /* SwitchStatement */: return checkSwitchStatement(node); - case 195 /* LabeledStatement */: + case 197 /* LabeledStatement */: return checkLabeledStatement(node); - case 196 /* ThrowStatement */: + case 198 /* ThrowStatement */: return checkThrowStatement(node); - case 197 /* TryStatement */: + case 199 /* TryStatement */: return checkTryStatement(node); - case 199 /* VariableDeclaration */: + case 201 /* VariableDeclaration */: return checkVariableDeclaration(node); - case 153 /* BindingElement */: + case 155 /* BindingElement */: return checkBindingElement(node); - case 202 /* ClassDeclaration */: + case 204 /* ClassDeclaration */: return checkClassDeclaration(node); - case 203 /* InterfaceDeclaration */: + case 205 /* InterfaceDeclaration */: return checkInterfaceDeclaration(node); - case 204 /* TypeAliasDeclaration */: + case 206 /* TypeAliasDeclaration */: return checkTypeAliasDeclaration(node); - case 205 /* EnumDeclaration */: + case 207 /* EnumDeclaration */: return checkEnumDeclaration(node); - case 206 /* ModuleDeclaration */: + case 208 /* ModuleDeclaration */: return checkModuleDeclaration(node); - case 210 /* ImportDeclaration */: + case 212 /* ImportDeclaration */: return checkImportDeclaration(node); - case 209 /* ImportEqualsDeclaration */: + case 211 /* ImportEqualsDeclaration */: return checkImportEqualsDeclaration(node); - case 216 /* ExportDeclaration */: + case 218 /* ExportDeclaration */: return checkExportDeclaration(node); - case 215 /* ExportAssignment */: + case 217 /* ExportAssignment */: return checkExportAssignment(node); - case 182 /* EmptyStatement */: + case 184 /* EmptyStatement */: checkGrammarStatementInAmbientContext(node); return; - case 198 /* DebuggerStatement */: + case 200 /* DebuggerStatement */: checkGrammarStatementInAmbientContext(node); return; - case 219 /* MissingDeclaration */: + case 221 /* MissingDeclaration */: return checkMissingDeclaration(node); } } @@ -20698,81 +22619,83 @@ var ts; // Delaying the type check of the body ensures foo has been assigned a type. function checkFunctionExpressionBodies(node) { switch (node.kind) { - case 163 /* FunctionExpression */: - case 164 /* ArrowFunction */: + case 165 /* FunctionExpression */: + case 166 /* ArrowFunction */: ts.forEach(node.parameters, checkFunctionExpressionBodies); checkFunctionExpressionOrObjectLiteralMethodBody(node); break; - case 135 /* MethodDeclaration */: - case 134 /* MethodSignature */: + case 136 /* MethodDeclaration */: + case 135 /* MethodSignature */: + ts.forEach(node.decorators, checkFunctionExpressionBodies); ts.forEach(node.parameters, checkFunctionExpressionBodies); if (ts.isObjectLiteralMethod(node)) { checkFunctionExpressionOrObjectLiteralMethodBody(node); } break; - case 136 /* Constructor */: - case 137 /* GetAccessor */: - case 138 /* SetAccessor */: - case 201 /* FunctionDeclaration */: + case 137 /* Constructor */: + case 138 /* GetAccessor */: + case 139 /* SetAccessor */: + case 203 /* FunctionDeclaration */: ts.forEach(node.parameters, checkFunctionExpressionBodies); break; - case 193 /* WithStatement */: + case 195 /* WithStatement */: checkFunctionExpressionBodies(node.expression); break; - case 130 /* Parameter */: - case 133 /* PropertyDeclaration */: - case 132 /* PropertySignature */: - case 151 /* ObjectBindingPattern */: - case 152 /* ArrayBindingPattern */: - case 153 /* BindingElement */: - case 154 /* ArrayLiteralExpression */: - case 155 /* ObjectLiteralExpression */: - case 225 /* PropertyAssignment */: - case 156 /* PropertyAccessExpression */: - case 157 /* ElementAccessExpression */: - case 158 /* CallExpression */: - case 159 /* NewExpression */: - case 160 /* TaggedTemplateExpression */: - case 172 /* TemplateExpression */: - case 178 /* TemplateSpan */: - case 161 /* TypeAssertionExpression */: - case 162 /* ParenthesizedExpression */: - case 166 /* TypeOfExpression */: - case 167 /* VoidExpression */: - case 165 /* DeleteExpression */: - case 168 /* PrefixUnaryExpression */: - case 169 /* PostfixUnaryExpression */: - case 170 /* BinaryExpression */: - case 171 /* ConditionalExpression */: - case 174 /* SpreadElementExpression */: - case 180 /* Block */: - case 207 /* ModuleBlock */: - case 181 /* VariableStatement */: - case 183 /* ExpressionStatement */: - case 184 /* IfStatement */: - case 185 /* DoStatement */: - case 186 /* WhileStatement */: - case 187 /* ForStatement */: - case 188 /* ForInStatement */: - case 189 /* ForOfStatement */: - case 190 /* ContinueStatement */: - case 191 /* BreakStatement */: - case 192 /* ReturnStatement */: - case 194 /* SwitchStatement */: - case 208 /* CaseBlock */: - case 221 /* CaseClause */: - case 222 /* DefaultClause */: - case 195 /* LabeledStatement */: - case 196 /* ThrowStatement */: - case 197 /* TryStatement */: - case 224 /* CatchClause */: - case 199 /* VariableDeclaration */: - case 200 /* VariableDeclarationList */: - case 202 /* ClassDeclaration */: - case 205 /* EnumDeclaration */: - case 227 /* EnumMember */: - case 215 /* ExportAssignment */: - case 228 /* SourceFile */: + case 132 /* Decorator */: + case 131 /* Parameter */: + case 134 /* PropertyDeclaration */: + case 133 /* PropertySignature */: + case 153 /* ObjectBindingPattern */: + case 154 /* ArrayBindingPattern */: + case 155 /* BindingElement */: + case 156 /* ArrayLiteralExpression */: + case 157 /* ObjectLiteralExpression */: + case 227 /* PropertyAssignment */: + case 158 /* PropertyAccessExpression */: + case 159 /* ElementAccessExpression */: + case 160 /* CallExpression */: + case 161 /* NewExpression */: + case 162 /* TaggedTemplateExpression */: + case 174 /* TemplateExpression */: + case 180 /* TemplateSpan */: + case 163 /* TypeAssertionExpression */: + case 164 /* ParenthesizedExpression */: + case 168 /* TypeOfExpression */: + case 169 /* VoidExpression */: + case 167 /* DeleteExpression */: + case 170 /* PrefixUnaryExpression */: + case 171 /* PostfixUnaryExpression */: + case 172 /* BinaryExpression */: + case 173 /* ConditionalExpression */: + case 176 /* SpreadElementExpression */: + case 182 /* Block */: + case 209 /* ModuleBlock */: + case 183 /* VariableStatement */: + case 185 /* ExpressionStatement */: + case 186 /* IfStatement */: + case 187 /* DoStatement */: + case 188 /* WhileStatement */: + case 189 /* ForStatement */: + case 190 /* ForInStatement */: + case 191 /* ForOfStatement */: + case 192 /* ContinueStatement */: + case 193 /* BreakStatement */: + case 194 /* ReturnStatement */: + case 196 /* SwitchStatement */: + case 210 /* CaseBlock */: + case 223 /* CaseClause */: + case 224 /* DefaultClause */: + case 197 /* LabeledStatement */: + case 198 /* ThrowStatement */: + case 199 /* TryStatement */: + case 226 /* CatchClause */: + case 201 /* VariableDeclaration */: + case 202 /* VariableDeclarationList */: + case 204 /* ClassDeclaration */: + case 207 /* EnumDeclaration */: + case 229 /* EnumMember */: + case 217 /* ExportAssignment */: + case 230 /* SourceFile */: ts.forEachChild(node, checkFunctionExpressionBodies); break; } @@ -20786,6 +22709,11 @@ var ts; function checkSourceFileWorker(node) { var links = getNodeLinks(node); if (!(links.flags & 1 /* TypeChecked */)) { + // Check whether the file has declared it is the default lib, + // and whether the user has specifically chosen to avoid checking it. + if (node.isDefaultLib && compilerOptions.skipDefaultLibCheck) { + return; + } // Grammar checking checkGrammarSourceFile(node); emitExtends = false; @@ -20835,7 +22763,7 @@ var ts; function isInsideWithStatementBody(node) { if (node) { while (node.parent) { - if (node.parent.kind === 193 /* WithStatement */ && node.parent.statement === node) { + if (node.parent.kind === 195 /* WithStatement */ && node.parent.statement === node) { return true; } node = node.parent; @@ -20858,23 +22786,23 @@ var ts; copySymbols(location.locals, meaning); } switch (location.kind) { - case 228 /* SourceFile */: + case 230 /* SourceFile */: if (!ts.isExternalModule(location)) { break; } - case 206 /* ModuleDeclaration */: + case 208 /* ModuleDeclaration */: copySymbols(getSymbolOfNode(location).exports, meaning & 8914931 /* ModuleMember */); break; - case 205 /* EnumDeclaration */: + case 207 /* EnumDeclaration */: copySymbols(getSymbolOfNode(location).exports, meaning & 8 /* EnumMember */); break; - case 202 /* ClassDeclaration */: - case 203 /* InterfaceDeclaration */: + case 204 /* ClassDeclaration */: + case 205 /* InterfaceDeclaration */: if (!(memberFlags & 128 /* Static */)) { copySymbols(getSymbolOfNode(location).members, meaning & 793056 /* Type */); } break; - case 163 /* FunctionExpression */: + case 165 /* FunctionExpression */: if (location.name) { copySymbol(location.symbol, meaning); } @@ -20912,22 +22840,22 @@ var ts; copySymbols(location.locals, meaning); } switch (location.kind) { - case 228 /* SourceFile */: + case 230 /* SourceFile */: if (!ts.isExternalModule(location)) break; - case 206 /* ModuleDeclaration */: + case 208 /* ModuleDeclaration */: copySymbols(getSymbolOfNode(location).exports, meaning & 8914931 /* ModuleMember */); break; - case 205 /* EnumDeclaration */: + case 207 /* EnumDeclaration */: copySymbols(getSymbolOfNode(location).exports, meaning & 8 /* EnumMember */); break; - case 202 /* ClassDeclaration */: - case 203 /* InterfaceDeclaration */: + case 204 /* ClassDeclaration */: + case 205 /* InterfaceDeclaration */: if (!(memberFlags & 128 /* Static */)) { copySymbols(getSymbolOfNode(location).members, meaning & 793056 /* Type */); } break; - case 163 /* FunctionExpression */: + case 165 /* FunctionExpression */: if (location.name) { copySymbol(location.symbol, meaning); } @@ -20940,124 +22868,43 @@ var ts; return symbolsToArray(symbols); } function isTypeDeclarationName(name) { - return name.kind == 65 /* Identifier */ && + return name.kind === 65 /* Identifier */ && isTypeDeclaration(name.parent) && name.parent.name === name; } function isTypeDeclaration(node) { switch (node.kind) { - case 129 /* TypeParameter */: - case 202 /* ClassDeclaration */: - case 203 /* InterfaceDeclaration */: - case 204 /* TypeAliasDeclaration */: - case 205 /* EnumDeclaration */: + case 130 /* TypeParameter */: + case 204 /* ClassDeclaration */: + case 205 /* InterfaceDeclaration */: + case 206 /* TypeAliasDeclaration */: + case 207 /* 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 === 127 /* QualifiedName */) { + while (node.parent && node.parent.kind === 128 /* QualifiedName */) { node = node.parent; } - return node.parent && node.parent.kind === 142 /* TypeReference */; + return node.parent && node.parent.kind === 144 /* TypeReference */; } function isHeritageClauseElementIdentifier(entityName) { var node = entityName; - while (node.parent && node.parent.kind === 156 /* PropertyAccessExpression */) { + while (node.parent && node.parent.kind === 158 /* PropertyAccessExpression */) { node = node.parent; } - return node.parent && node.parent.kind === 177 /* ExpressionWithTypeArguments */; - } - function isTypeNode(node) { - if (142 /* FirstTypeNode */ <= node.kind && node.kind <= 150 /* LastTypeNode */) { - return true; - } - switch (node.kind) { - case 112 /* AnyKeyword */: - case 120 /* NumberKeyword */: - case 122 /* StringKeyword */: - case 113 /* BooleanKeyword */: - case 123 /* SymbolKeyword */: - return true; - case 99 /* VoidKeyword */: - return node.parent.kind !== 167 /* VoidExpression */; - case 8 /* StringLiteral */: - // Specialized signatures can have string literals as their parameters' type names - return node.parent.kind === 130 /* Parameter */; - case 177 /* ExpressionWithTypeArguments */: - return true; - // Identifiers and qualified names may be type nodes, depending on their context. Climb - // above them to find the lowest container - case 65 /* Identifier */: - // If the identifier is the RHS of a qualified name, then it's a type iff its parent is. - if (node.parent.kind === 127 /* QualifiedName */ && node.parent.right === node) { - node = node.parent; - } - else if (node.parent.kind === 156 /* PropertyAccessExpression */ && node.parent.name === node) { - node = node.parent; - } - // fall through - case 127 /* QualifiedName */: - case 156 /* PropertyAccessExpression */: - // At this point, node is either a qualified name or an identifier - ts.Debug.assert(node.kind === 65 /* Identifier */ || node.kind === 127 /* QualifiedName */ || node.kind === 156 /* PropertyAccessExpression */, "'node' was expected to be a qualified name, identifier or property access in 'isTypeNode'."); - var parent_5 = node.parent; - if (parent_5.kind === 145 /* TypeQuery */) { - return false; - } - // Do not recursively call isTypeNode on the parent. In the example: - // - // let a: A.B.C; - // - // Calling isTypeNode would consider the qualified name A.B a type node. Only C or - // A.B.C is a type node. - if (142 /* FirstTypeNode */ <= parent_5.kind && parent_5.kind <= 150 /* LastTypeNode */) { - return true; - } - switch (parent_5.kind) { - case 177 /* ExpressionWithTypeArguments */: - return true; - case 129 /* TypeParameter */: - return node === parent_5.constraint; - case 133 /* PropertyDeclaration */: - case 132 /* PropertySignature */: - case 130 /* Parameter */: - case 199 /* VariableDeclaration */: - return node === parent_5.type; - case 201 /* FunctionDeclaration */: - case 163 /* FunctionExpression */: - case 164 /* ArrowFunction */: - case 136 /* Constructor */: - case 135 /* MethodDeclaration */: - case 134 /* MethodSignature */: - case 137 /* GetAccessor */: - case 138 /* SetAccessor */: - return node === parent_5.type; - case 139 /* CallSignature */: - case 140 /* ConstructSignature */: - case 141 /* IndexSignature */: - return node === parent_5.type; - case 161 /* TypeAssertionExpression */: - return node === parent_5.type; - case 158 /* CallExpression */: - case 159 /* NewExpression */: - return parent_5.typeArguments && ts.indexOf(parent_5.typeArguments, node) >= 0; - case 160 /* TaggedTemplateExpression */: - // TODO (drosen): TaggedTemplateExpressions may eventually support type arguments. - return false; - } - } - return false; + return node.parent && node.parent.kind === 179 /* ExpressionWithTypeArguments */; } function getLeftSideOfImportEqualsOrExportAssignment(nodeOnRightSide) { - while (nodeOnRightSide.parent.kind === 127 /* QualifiedName */) { + while (nodeOnRightSide.parent.kind === 128 /* QualifiedName */) { nodeOnRightSide = nodeOnRightSide.parent; } - if (nodeOnRightSide.parent.kind === 209 /* ImportEqualsDeclaration */) { + if (nodeOnRightSide.parent.kind === 211 /* ImportEqualsDeclaration */) { return nodeOnRightSide.parent.moduleReference === nodeOnRightSide && nodeOnRightSide.parent; } - if (nodeOnRightSide.parent.kind === 215 /* ExportAssignment */) { + if (nodeOnRightSide.parent.kind === 217 /* ExportAssignment */) { return nodeOnRightSide.parent.expression === nodeOnRightSide && nodeOnRightSide.parent; } return undefined; @@ -21069,11 +22916,11 @@ var ts; if (ts.isDeclarationName(entityName)) { return getSymbolOfNode(entityName.parent); } - if (entityName.parent.kind === 215 /* ExportAssignment */) { + if (entityName.parent.kind === 217 /* ExportAssignment */) { return resolveEntityName(entityName, /*all meanings*/ 107455 /* Value */ | 793056 /* Type */ | 1536 /* Namespace */ | 8388608 /* Alias */); } - if (entityName.kind !== 156 /* PropertyAccessExpression */) { + if (entityName.kind !== 158 /* PropertyAccessExpression */) { if (isInRightSideOfImportOrExportAssignment(entityName)) { // Since we already checked for ExportAssignment, this really could only be an Import return getSymbolOfPartOfRightHandSideOfImportEquals(entityName); @@ -21083,7 +22930,7 @@ var ts; entityName = entityName.parent; } if (isHeritageClauseElementIdentifier(entityName)) { - var meaning = entityName.parent.kind === 177 /* ExpressionWithTypeArguments */ ? 793056 /* Type */ : 1536 /* Namespace */; + var meaning = entityName.parent.kind === 179 /* ExpressionWithTypeArguments */ ? 793056 /* Type */ : 1536 /* Namespace */; meaning |= 8388608 /* Alias */; return resolveEntityName(entityName, meaning); } @@ -21098,14 +22945,14 @@ var ts; var meaning = 107455 /* Value */ | 8388608 /* Alias */; return resolveEntityName(entityName, meaning); } - else if (entityName.kind === 156 /* PropertyAccessExpression */) { + else if (entityName.kind === 158 /* PropertyAccessExpression */) { var symbol = getNodeLinks(entityName).resolvedSymbol; if (!symbol) { checkPropertyAccessExpression(entityName); } return getNodeLinks(entityName).resolvedSymbol; } - else if (entityName.kind === 127 /* QualifiedName */) { + else if (entityName.kind === 128 /* QualifiedName */) { var symbol = getNodeLinks(entityName).resolvedSymbol; if (!symbol) { checkQualifiedName(entityName); @@ -21114,7 +22961,7 @@ var ts; } } else if (isTypeReferenceIdentifier(entityName)) { - var meaning = entityName.parent.kind === 142 /* TypeReference */ ? 793056 /* Type */ : 1536 /* Namespace */; + var meaning = entityName.parent.kind === 144 /* TypeReference */ ? 793056 /* Type */ : 1536 /* Namespace */; // Include aliases in the meaning, this ensures that we do not follow aliases to where they point and instead // return the alias symbol. meaning |= 8388608 /* Alias */; @@ -21133,14 +22980,14 @@ var ts; return getSymbolOfNode(node.parent); } if (node.kind === 65 /* Identifier */ && isInRightSideOfImportOrExportAssignment(node)) { - return node.parent.kind === 215 /* ExportAssignment */ + return node.parent.kind === 217 /* ExportAssignment */ ? getSymbolOfEntityNameOrPropertyAccessExpression(node) : getSymbolOfPartOfRightHandSideOfImportEquals(node); } switch (node.kind) { case 65 /* Identifier */: - case 156 /* PropertyAccessExpression */: - case 127 /* QualifiedName */: + case 158 /* PropertyAccessExpression */: + case 128 /* QualifiedName */: return getSymbolOfEntityNameOrPropertyAccessExpression(node); case 93 /* ThisKeyword */: case 91 /* SuperKeyword */: @@ -21149,7 +22996,7 @@ var ts; case 114 /* ConstructorKeyword */: // constructor keyword for an overload, should take us to the definition if it exist var constructorDeclaration = node.parent; - if (constructorDeclaration && constructorDeclaration.kind === 136 /* Constructor */) { + if (constructorDeclaration && constructorDeclaration.kind === 137 /* Constructor */) { return constructorDeclaration.parent.symbol; } return undefined; @@ -21158,14 +23005,14 @@ var ts; var moduleName; if ((ts.isExternalModuleImportEqualsDeclaration(node.parent.parent) && ts.getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node) || - ((node.parent.kind === 210 /* ImportDeclaration */ || node.parent.kind === 216 /* ExportDeclaration */) && + ((node.parent.kind === 212 /* ImportDeclaration */ || node.parent.kind === 218 /* ExportDeclaration */) && node.parent.moduleSpecifier === node)) { return resolveExternalModuleName(node, node); } // Intentional fall-through case 7 /* NumericLiteral */: // index access - if (node.parent.kind == 157 /* ElementAccessExpression */ && node.parent.argumentExpression === node) { + if (node.parent.kind === 159 /* ElementAccessExpression */ && node.parent.argumentExpression === node) { var objectType = checkExpression(node.parent.expression); if (objectType === unknownType) return undefined; @@ -21182,7 +23029,7 @@ var ts; // 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 === 226 /* ShorthandPropertyAssignment */) { + if (location && location.kind === 228 /* ShorthandPropertyAssignment */) { return resolveEntityName(location.name, 107455 /* Value */); } return undefined; @@ -21192,12 +23039,17 @@ var ts; // We cannot answer semantic questions within a with block, do not proceed any further return unknownType; } - if (isTypeNode(node)) { + if (ts.isTypeNode(node)) { return getTypeFromTypeNode(node); } if (ts.isExpression(node)) { return getTypeOfExpression(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. + return getBaseTypes(getDeclaredTypeOfSymbol(getSymbolOfNode(node.parent.parent)))[0]; + } if (isTypeDeclaration(node)) { // In this case, we call getSymbolOfNode instead of getSymbolInfo because it is a declaration var symbol = getSymbolOfNode(node); @@ -21246,9 +23098,9 @@ var ts; function getRootSymbols(symbol) { if (symbol.flags & 268435456 /* UnionProperty */) { var symbols = []; - var name_10 = symbol.name; + var name_14 = symbol.name; ts.forEach(getSymbolLinks(symbol).unionType.types, function (t) { - symbols.push(getPropertyOfType(t, name_10)); + symbols.push(getPropertyOfType(t, name_14)); }); return symbols; } @@ -21261,93 +23113,92 @@ var ts; return [symbol]; } // Emitter support - function isExternalModuleSymbol(symbol) { - return symbol.flags & 512 /* ValueModule */ && symbol.declarations.length === 1 && symbol.declarations[0].kind === 228 /* SourceFile */; - } - function getAliasNameSubstitution(symbol, getGeneratedNameForNode) { - // If this is es6 or higher, just use the name of the export - // no need to qualify it. - if (languageVersion >= 2 /* ES6 */) { - return undefined; - } - var node = getDeclarationOfAliasSymbol(symbol); - if (node) { - if (node.kind === 211 /* ImportClause */) { - var defaultKeyword; - if (languageVersion === 0 /* ES3 */) { - defaultKeyword = "[\"default\"]"; - } - else { - defaultKeyword = ".default"; - } - return getGeneratedNameForNode(node.parent) + defaultKeyword; - } - if (node.kind === 214 /* ImportSpecifier */) { - var moduleName = getGeneratedNameForNode(node.parent.parent.parent); - var propertyName = node.propertyName || node.name; - return moduleName + "." + ts.unescapeIdentifier(propertyName.text); - } - } - } - function getExportNameSubstitution(symbol, location, getGeneratedNameForNode) { - if (isExternalModuleSymbol(symbol.parent)) { - // 1. If this is es6 or higher, just use the name of the export - // no need to qualify it. - // 2. export mechanism for System modules is different from CJS\AMD - // and it does not need qualifications for exports - if (languageVersion >= 2 /* ES6 */ || compilerOptions.module === 4 /* System */) { - return undefined; - } - return "exports." + ts.unescapeIdentifier(symbol.name); - } - var node = location; - var containerSymbol = getParentOfSymbol(symbol); - while (node) { - if ((node.kind === 206 /* ModuleDeclaration */ || node.kind === 205 /* EnumDeclaration */) && getSymbolOfNode(node) === containerSymbol) { - return getGeneratedNameForNode(node) + "." + ts.unescapeIdentifier(symbol.name); - } - node = node.parent; - } - } - function getExpressionNameSubstitution(node, getGeneratedNameForNode) { - var symbol = getNodeLinks(node).resolvedSymbol || (ts.isDeclarationName(node) ? getSymbolOfNode(node.parent) : undefined); + // 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) { + var symbol = getReferencedValueSymbol(node); if (symbol) { - // Whan an identifier resolves to a parented symbol, it references an exported entity from - // another declaration of the same internal module. - if (symbol.parent) { - return getExportNameSubstitution(symbol, node.parent, getGeneratedNameForNode); + 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 (exportSymbol.flags & 944 /* ExportHasLocal */) { + return undefined; + } + symbol = exportSymbol; } - // 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 = getExportSymbolOfValueSymbolIfExported(symbol); - if (symbol !== exportSymbol && !(exportSymbol.flags & 944 /* ExportHasLocal */)) { - return getExportNameSubstitution(exportSymbol, node.parent, getGeneratedNameForNode); - } - // Named imports from ES6 import declarations are rewritten - if (symbol.flags & 8388608 /* Alias */) { - return getAliasNameSubstitution(symbol, getGeneratedNameForNode); + var parentSymbol = getParentOfSymbol(symbol); + if (parentSymbol) { + if (parentSymbol.flags & 512 /* ValueModule */ && parentSymbol.valueDeclaration.kind === 230 /* SourceFile */) { + return parentSymbol.valueDeclaration; + } + for (var n = node.parent; n; n = n.parent) { + if ((n.kind === 208 /* ModuleDeclaration */ || n.kind === 207 /* EnumDeclaration */) && getSymbolOfNode(n) === parentSymbol) { + return n; + } + } } } } + // 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) { + var symbol = getReferencedValueSymbol(node); + return symbol && symbol.flags & 8388608 /* Alias */ ? getDeclarationOfAliasSymbol(symbol) : undefined; + } + function isStatementWithLocals(node) { + switch (node.kind) { + case 182 /* Block */: + case 210 /* CaseBlock */: + case 189 /* ForStatement */: + case 190 /* ForInStatement */: + case 191 /* ForOfStatement */: + return true; + } + return false; + } + function isNestedRedeclarationSymbol(symbol) { + if (symbol.flags & 418 /* BlockScoped */) { + var links = getSymbolLinks(symbol); + if (links.isNestedRedeclaration === undefined) { + var container = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration); + links.isNestedRedeclaration = isStatementWithLocals(container) && + !!resolveName(container.parent, symbol.name, 107455 /* Value */, undefined, undefined); + } + return links.isNestedRedeclaration; + } + return false; + } + // When resolved as an expression identifier, if the given node references a nested block scoped entity with + // a name that hides an existing name, return the declaration of that entity. Otherwise, return undefined. + function getReferencedNestedRedeclaration(node) { + var symbol = getReferencedValueSymbol(node); + return symbol && isNestedRedeclarationSymbol(symbol) ? symbol.valueDeclaration : undefined; + } + // Return true if the given node is a declaration of a nested block scoped entity with a name that hides an + // existing name. + function isNestedRedeclaration(node) { + return isNestedRedeclarationSymbol(getSymbolOfNode(node)); + } function isValueAliasDeclaration(node) { switch (node.kind) { - case 209 /* ImportEqualsDeclaration */: - case 211 /* ImportClause */: - case 212 /* NamespaceImport */: - case 214 /* ImportSpecifier */: - case 218 /* ExportSpecifier */: + case 211 /* ImportEqualsDeclaration */: + case 213 /* ImportClause */: + case 214 /* NamespaceImport */: + case 216 /* ImportSpecifier */: + case 220 /* ExportSpecifier */: return isAliasResolvedToValue(getSymbolOfNode(node)); - case 216 /* ExportDeclaration */: + case 218 /* ExportDeclaration */: var exportClause = node.exportClause; return exportClause && ts.forEach(exportClause.elements, isValueAliasDeclaration); - case 215 /* ExportAssignment */: + case 217 /* ExportAssignment */: return node.expression && node.expression.kind === 65 /* Identifier */ ? isAliasResolvedToValue(getSymbolOfNode(node)) : true; } return false; } function isTopLevelValueImportEqualsWithEntityName(node) { - if (node.parent.kind !== 228 /* SourceFile */ || !ts.isInternalModuleImportEqualsDeclaration(node)) { + if (node.parent.kind !== 230 /* SourceFile */ || !ts.isInternalModuleImportEqualsDeclaration(node)) { // parent is not source file or it is not reference to internal module return false; } @@ -21356,7 +23207,7 @@ var ts; } function isAliasResolvedToValue(symbol) { var target = resolveAlias(symbol); - if (target === unknownSymbol && compilerOptions.separateCompilation) { + if (target === unknownSymbol && compilerOptions.isolatedModules) { return true; } // const enums and modules that contain only const enums are not considered values from the emit perespective @@ -21405,7 +23256,7 @@ var ts; return getNodeLinks(node).enumMemberValue; } function getConstantValue(node) { - if (node.kind === 227 /* EnumMember */) { + if (node.kind === 229 /* EnumMember */) { return getEnumMemberValue(node); } var symbol = getNodeLinks(node).resolvedSymbol; @@ -21418,10 +23269,13 @@ var ts; return undefined; } /** Serializes an EntityName (with substitutions) to an appropriate JS constructor value. Used by the __metadata decorator. */ - function serializeEntityName(node, getGeneratedNameForNode, fallbackPath) { + function serializeEntityName(node, fallbackPath) { if (node.kind === 65 /* Identifier */) { - var substitution = getExpressionNameSubstitution(node, getGeneratedNameForNode); - var text = substitution || node.text; + // TODO(ron.buckton): The getExpressionNameSubstitution function has been removed, but calling it + // here has no effect anyway as an identifier in a type name is not an expression. + // var substitution = getExpressionNameSubstitution(node, getGeneratedNameForNode); + // var text = substitution || (node).text; + var text = node.text; if (fallbackPath) { fallbackPath.push(text); } @@ -21430,15 +23284,15 @@ var ts; } } else { - var left = serializeEntityName(node.left, getGeneratedNameForNode, fallbackPath); - var right = serializeEntityName(node.right, getGeneratedNameForNode, fallbackPath); + var left = serializeEntityName(node.left, fallbackPath); + var right = serializeEntityName(node.right, fallbackPath); if (!fallbackPath) { return left + "." + right; } } } /** Serializes a TypeReferenceNode to an appropriate JS constructor value. Used by the __metadata decorator. */ - function serializeTypeReferenceNode(node, getGeneratedNameForNode) { + function serializeTypeReferenceNode(node) { // serialization of a TypeReferenceNode uses the following rules: // // * The serialized type of a TypeReference that is `void` is "void 0". @@ -21466,16 +23320,16 @@ var ts; else if (type.flags & 8192 /* Tuple */) { return "Array"; } - else if (type.flags & 1048576 /* ESSymbol */) { + else if (type.flags & 2097152 /* ESSymbol */) { return "Symbol"; } else if (type === unknownType) { var fallbackPath = []; - serializeEntityName(node.typeName, getGeneratedNameForNode, fallbackPath); + serializeEntityName(node.typeName, fallbackPath); return fallbackPath; } else if (type.symbol && type.symbol.valueDeclaration) { - return serializeEntityName(node.typeName, getGeneratedNameForNode); + return serializeEntityName(node.typeName); } else if (typeHasCallOrConstructSignatures(type)) { return "Function"; @@ -21483,7 +23337,7 @@ var ts; return "Object"; } /** Serializes a TypeNode to an appropriate JS constructor value. Used by the __metadata decorator. */ - function serializeTypeNode(node, getGeneratedNameForNode) { + function serializeTypeNode(node) { // serialization of a TypeNode uses the following rules: // // * The serialized type of `void` is "void 0" (undefined). @@ -21498,26 +23352,26 @@ var ts; switch (node.kind) { case 99 /* VoidKeyword */: return "void 0"; - case 150 /* ParenthesizedType */: - return serializeTypeNode(node.type, getGeneratedNameForNode); - case 143 /* FunctionType */: - case 144 /* ConstructorType */: + case 152 /* ParenthesizedType */: + return serializeTypeNode(node.type); + case 145 /* FunctionType */: + case 146 /* ConstructorType */: return "Function"; - case 147 /* ArrayType */: - case 148 /* TupleType */: + case 149 /* ArrayType */: + case 150 /* TupleType */: return "Array"; case 113 /* BooleanKeyword */: return "Boolean"; - case 122 /* StringKeyword */: + case 123 /* StringKeyword */: case 8 /* StringLiteral */: return "String"; - case 120 /* NumberKeyword */: + case 121 /* NumberKeyword */: return "Number"; - case 142 /* TypeReference */: - return serializeTypeReferenceNode(node, getGeneratedNameForNode); - case 145 /* TypeQuery */: - case 146 /* TypeLiteral */: - case 149 /* UnionType */: + case 144 /* TypeReference */: + return serializeTypeReferenceNode(node); + case 147 /* TypeQuery */: + case 148 /* TypeLiteral */: + case 151 /* UnionType */: case 112 /* AnyKeyword */: break; default: @@ -21528,7 +23382,7 @@ var ts; return "Object"; } /** Serializes the type of a declaration to an appropriate JS constructor value. Used by the __metadata decorator for a class member. */ - function serializeTypeOfNode(node, getGeneratedNameForNode) { + function serializeTypeOfNode(node) { // serialization of the type of a declaration uses the following rules: // // * The serialized type of a ClassDeclaration is "Function" @@ -21540,11 +23394,11 @@ var ts; // // For rules on serializing type annotations, see `serializeTypeNode`. switch (node.kind) { - case 202 /* ClassDeclaration */: return "Function"; - case 133 /* PropertyDeclaration */: return serializeTypeNode(node.type, getGeneratedNameForNode); - case 130 /* Parameter */: return serializeTypeNode(node.type, getGeneratedNameForNode); - case 137 /* GetAccessor */: return serializeTypeNode(node.type, getGeneratedNameForNode); - case 138 /* SetAccessor */: return serializeTypeNode(getSetAccessorTypeAnnotationNode(node), getGeneratedNameForNode); + case 204 /* ClassDeclaration */: return "Function"; + case 134 /* PropertyDeclaration */: return serializeTypeNode(node.type); + case 131 /* Parameter */: return serializeTypeNode(node.type); + case 138 /* GetAccessor */: return serializeTypeNode(node.type); + case 139 /* SetAccessor */: return serializeTypeNode(getSetAccessorTypeAnnotationNode(node)); } if (ts.isFunctionLike(node)) { return "Function"; @@ -21552,7 +23406,7 @@ var ts; return "void 0"; } /** Serializes the parameter types of a function or the constructor of a class. Used by the __metadata decorator for a method or set accessor. */ - function serializeParameterTypesOfNode(node, getGeneratedNameForNode) { + function serializeParameterTypesOfNode(node) { // serialization of parameter types uses the following rules: // // * If the declaration is a class, the parameters of the first constructor with a body are used. @@ -21561,7 +23415,7 @@ var ts; // For the rules on serializing the type of each parameter declaration, see `serializeTypeOfDeclaration`. if (node) { var valueDeclaration; - if (node.kind === 202 /* ClassDeclaration */) { + if (node.kind === 204 /* ClassDeclaration */) { valueDeclaration = ts.getFirstConstructorWithBody(node); } else if (ts.isFunctionLike(node) && ts.nodeIsPresent(node.body)) { @@ -21576,19 +23430,19 @@ var ts; for (var i = 0; i < parameterCount; i++) { if (parameters[i].dotDotDotToken) { var parameterType = parameters[i].type; - if (parameterType.kind === 147 /* ArrayType */) { + if (parameterType.kind === 149 /* ArrayType */) { parameterType = parameterType.elementType; } - else if (parameterType.kind === 142 /* TypeReference */ && parameterType.typeArguments && parameterType.typeArguments.length === 1) { + else if (parameterType.kind === 144 /* TypeReference */ && parameterType.typeArguments && parameterType.typeArguments.length === 1) { parameterType = parameterType.typeArguments[0]; } else { parameterType = undefined; } - result[i] = serializeTypeNode(parameterType, getGeneratedNameForNode); + result[i] = serializeTypeNode(parameterType); } else { - result[i] = serializeTypeOfNode(parameters[i], getGeneratedNameForNode); + result[i] = serializeTypeOfNode(parameters[i]); } } return result; @@ -21598,9 +23452,9 @@ var ts; return emptyArray; } /** Serializes the return type of function. Used by the __metadata decorator for a method. */ - function serializeReturnTypeOfNode(node, getGeneratedNameForNode) { + function serializeReturnTypeOfNode(node) { if (node && ts.isFunctionLike(node)) { - return serializeTypeNode(node.type, getGeneratedNameForNode); + return serializeTypeNode(node.type); } return "void 0"; } @@ -21623,25 +23477,25 @@ var ts; function hasGlobalName(name) { return ts.hasProperty(globals, name); } - function resolvesToSomeValue(location, name) { - ts.Debug.assert(!ts.nodeIsSynthesized(location), "resolvesToSomeValue called with a synthesized location"); - return !!resolveName(location, name, 107455 /* Value */, undefined, undefined); + function getReferencedValueSymbol(reference) { + return getNodeLinks(reference).resolvedSymbol || + resolveName(reference, reference.text, 107455 /* Value */ | 1048576 /* ExportValue */ | 8388608 /* Alias */, + /*nodeNotFoundMessage*/ undefined, undefined); } function getReferencedValueDeclaration(reference) { ts.Debug.assert(!ts.nodeIsSynthesized(reference)); - var symbol = getNodeLinks(reference).resolvedSymbol || - resolveName(reference, reference.text, 107455 /* Value */ | 8388608 /* Alias */, undefined, undefined); + var symbol = getReferencedValueSymbol(reference); return symbol && getExportSymbolOfValueSymbolIfExported(symbol).valueDeclaration; } function getBlockScopedVariableId(n) { ts.Debug.assert(!ts.nodeIsSynthesized(n)); - var isVariableDeclarationOrBindingElement = n.parent.kind === 153 /* BindingElement */ || (n.parent.kind === 199 /* VariableDeclaration */ && n.parent.name === n); + var isVariableDeclarationOrBindingElement = n.parent.kind === 155 /* BindingElement */ || (n.parent.kind === 201 /* VariableDeclaration */ && n.parent.name === n); var symbol = (isVariableDeclarationOrBindingElement ? getSymbolOfNode(n.parent) : undefined) || getNodeLinks(n).resolvedSymbol || resolveName(n, n.text, 107455 /* Value */ | 8388608 /* Alias */, undefined, undefined); var isLetOrConst = symbol && (symbol.flags & 2 /* BlockScopedVariable */) && - symbol.valueDeclaration.parent.kind !== 224 /* CatchClause */; + symbol.valueDeclaration.parent.kind !== 226 /* CatchClause */; if (isLetOrConst) { // side-effect of calling this method: // assign id to symbol if it was not yet set @@ -21663,7 +23517,10 @@ var ts; } function createResolver() { return { - getExpressionNameSubstitution: getExpressionNameSubstitution, + getReferencedExportContainer: getReferencedExportContainer, + getReferencedImportDeclaration: getReferencedImportDeclaration, + getReferencedNestedRedeclaration: getReferencedNestedRedeclaration, + isNestedRedeclaration: isNestedRedeclaration, isValueAliasDeclaration: isValueAliasDeclaration, hasGlobalName: hasGlobalName, isReferencedAliasDeclaration: isReferencedAliasDeclaration, @@ -21677,7 +23534,6 @@ var ts; isSymbolAccessible: isSymbolAccessible, isEntityNameVisible: isEntityNameVisible, getConstantValue: getConstantValue, - resolvesToSomeValue: resolvesToSomeValue, collectLinkedAliases: collectLinkedAliases, getBlockScopedVariableId: getBlockScopedVariableId, getReferencedValueDeclaration: getReferencedValueDeclaration, @@ -21703,8 +23559,7 @@ var ts; getSymbolLinks(unknownSymbol).type = unknownType; globals[undefinedSymbol.name] = undefinedSymbol; // Initialize special types - globalArraySymbol = getGlobalTypeSymbol("Array"); - globalArrayType = getTypeOfGlobalSymbol(globalArraySymbol, 1); + globalArrayType = getGlobalType("Array", 1); globalObjectType = getGlobalType("Object"); globalFunctionType = getGlobalType("Function"); globalStringType = getGlobalType("String"); @@ -21722,6 +23577,8 @@ var ts; globalESSymbolType = getGlobalType("Symbol"); globalESSymbolConstructorSymbol = getGlobalValueSymbol("Symbol"); globalIterableType = getGlobalType("Iterable", 1); + globalIteratorType = getGlobalType("Iterator", 1); + globalIterableIteratorType = getGlobalType("IterableIterator", 1); } else { globalTemplateStringsArrayType = unknownType; @@ -21730,141 +23587,13 @@ var ts; // a global Symbol already, particularly if it is a class. globalESSymbolType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); globalESSymbolConstructorSymbol = undefined; + globalIterableType = emptyGenericType; + globalIteratorType = emptyGenericType; + globalIterableIteratorType = emptyGenericType; } anyArrayType = createArrayType(anyType); } // GRAMMAR CHECKING - function isReservedWordInStrictMode(node) { - // Check that originalKeywordKind is less than LastFutureReservedWord to see if an Identifier is a strict-mode reserved word - return (node.parserContextFlags & 1 /* StrictMode */) && - (102 /* FirstFutureReservedWord */ <= node.originalKeywordKind && node.originalKeywordKind <= 110 /* LastFutureReservedWord */); - } - function reportStrictModeGrammarErrorInClassDeclaration(identifier, message, arg0, arg1, arg2) { - // We are checking if this name is inside class declaration or class expression (which are under class definitions inside ES6 spec.) - // if so, we would like to give more explicit invalid usage error. - if (ts.getAncestor(identifier, 202 /* ClassDeclaration */) || ts.getAncestor(identifier, 175 /* ClassExpression */)) { - return grammarErrorOnNode(identifier, message, arg0); - } - return false; - } - function checkGrammarImportDeclarationNameInStrictMode(node) { - // Check if the import declaration used strict-mode reserved word in its names bindings - if (node.importClause) { - var impotClause = node.importClause; - if (impotClause.namedBindings) { - var nameBindings = impotClause.namedBindings; - if (nameBindings.kind === 212 /* NamespaceImport */) { - var name_11 = nameBindings.name; - if (isReservedWordInStrictMode(name_11)) { - var nameText = ts.declarationNameToString(name_11); - return grammarErrorOnNode(name_11, ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode, nameText); - } - } - else if (nameBindings.kind === 213 /* NamedImports */) { - var reportError = false; - for (var _i = 0, _a = nameBindings.elements; _i < _a.length; _i++) { - var element = _a[_i]; - var name_12 = element.name; - if (isReservedWordInStrictMode(name_12)) { - var nameText = ts.declarationNameToString(name_12); - reportError = reportError || grammarErrorOnNode(name_12, ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode, nameText); - } - } - return reportError; - } - } - } - return false; - } - function checkGrammarDeclarationNameInStrictMode(node) { - var name = node.name; - if (name && name.kind === 65 /* Identifier */ && isReservedWordInStrictMode(name)) { - var nameText = ts.declarationNameToString(name); - switch (node.kind) { - case 130 /* Parameter */: - case 199 /* VariableDeclaration */: - case 201 /* FunctionDeclaration */: - case 129 /* TypeParameter */: - case 153 /* BindingElement */: - case 203 /* InterfaceDeclaration */: - case 204 /* TypeAliasDeclaration */: - case 205 /* EnumDeclaration */: - return checkGrammarIdentifierInStrictMode(name); - case 202 /* ClassDeclaration */: - // Report an error if the class declaration uses strict-mode reserved word. - return grammarErrorOnNode(name, ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_strict_mode, nameText); - case 206 /* ModuleDeclaration */: - // Report an error if the module declaration uses strict-mode reserved word. - // TODO(yuisu): fix this when having external module in strict mode - return grammarErrorOnNode(name, ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode, nameText); - case 209 /* ImportEqualsDeclaration */: - // TODO(yuisu): fix this when having external module in strict mode - return grammarErrorOnNode(name, ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode, nameText); - } - } - return false; - } - function checkGrammarTypeReferenceInStrictMode(typeName) { - // Check if the type reference is using strict mode keyword - // Example: - // class C { - // foo(x: public){} // Error. - // } - if (typeName.kind === 65 /* Identifier */) { - checkGrammarTypeNameInStrictMode(typeName); - } - else if (typeName.kind === 127 /* QualifiedName */) { - // Walk from right to left and report a possible error at each Identifier in QualifiedName - // Example: - // x1: public.private.package // error at public and private - checkGrammarTypeNameInStrictMode(typeName.right); - checkGrammarTypeReferenceInStrictMode(typeName.left); - } - } - // This function will report an error for every identifier in property access expression - // whether it violates strict mode reserved words. - // Example: - // public // error at public - // public.private.package // error at public - // B.private.B // no error - function checkGrammarExpressionWithTypeArgumentsInStrictMode(expression) { - // Example: - // class C extends public // error at public - if (expression && expression.kind === 65 /* Identifier */) { - return checkGrammarIdentifierInStrictMode(expression); - } - else if (expression && expression.kind === 156 /* PropertyAccessExpression */) { - // Walk from left to right in PropertyAccessExpression until we are at the left most expression - // in PropertyAccessExpression. According to grammar production of MemberExpression, - // the left component expression is a PrimaryExpression (i.e. Identifier) while the other - // component after dots can be IdentifierName. - checkGrammarExpressionWithTypeArgumentsInStrictMode(expression.expression); - } - } - // The function takes an identifier itself or an expression which has SyntaxKind.Identifier. - function checkGrammarIdentifierInStrictMode(node, nameText) { - if (node && node.kind === 65 /* Identifier */ && isReservedWordInStrictMode(node)) { - if (!nameText) { - nameText = ts.declarationNameToString(node); - } - // TODO (yuisu): Fix when module is a strict mode - var errorReport = reportStrictModeGrammarErrorInClassDeclaration(node, ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_strict_mode, nameText) || - grammarErrorOnNode(node, ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode, nameText); - return errorReport; - } - return false; - } - // The function takes an identifier when uses as a typeName in TypeReferenceNode - function checkGrammarTypeNameInStrictMode(node) { - if (node && node.kind === 65 /* Identifier */ && isReservedWordInStrictMode(node)) { - var nameText = ts.declarationNameToString(node); - // TODO (yuisu): Fix when module is a strict mode - var errorReport = reportStrictModeGrammarErrorInClassDeclaration(node, ts.Diagnostics.Type_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_strict_mode, nameText) || - grammarErrorOnNode(node, ts.Diagnostics.Type_expected_0_is_a_reserved_word_in_strict_mode, nameText); - return errorReport; - } - return false; - } function checkGrammarDecorators(node) { if (!node.decorators) { return false; @@ -21875,7 +23604,7 @@ var ts; else if (languageVersion < 1 /* ES5 */) { return grammarErrorOnFirstToken(node, ts.Diagnostics.Decorators_are_only_available_when_targeting_ECMAScript_5_and_higher); } - else if (node.kind === 137 /* GetAccessor */ || node.kind === 138 /* SetAccessor */) { + else if (node.kind === 138 /* GetAccessor */ || node.kind === 139 /* 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); @@ -21885,26 +23614,35 @@ var ts; } function checkGrammarModifiers(node) { switch (node.kind) { - case 137 /* GetAccessor */: - case 138 /* SetAccessor */: - case 136 /* Constructor */: - case 133 /* PropertyDeclaration */: - case 132 /* PropertySignature */: - case 135 /* MethodDeclaration */: - case 134 /* MethodSignature */: - case 141 /* IndexSignature */: - case 202 /* ClassDeclaration */: - case 203 /* InterfaceDeclaration */: - case 206 /* ModuleDeclaration */: - case 205 /* EnumDeclaration */: - case 181 /* VariableStatement */: - case 201 /* FunctionDeclaration */: - case 204 /* TypeAliasDeclaration */: - case 210 /* ImportDeclaration */: - case 209 /* ImportEqualsDeclaration */: - case 216 /* ExportDeclaration */: - case 215 /* ExportAssignment */: - case 130 /* Parameter */: + case 138 /* GetAccessor */: + case 139 /* SetAccessor */: + case 137 /* Constructor */: + case 134 /* PropertyDeclaration */: + case 133 /* PropertySignature */: + case 136 /* MethodDeclaration */: + case 135 /* MethodSignature */: + case 142 /* IndexSignature */: + case 208 /* ModuleDeclaration */: + case 212 /* ImportDeclaration */: + case 211 /* ImportEqualsDeclaration */: + case 218 /* ExportDeclaration */: + case 217 /* ExportAssignment */: + case 131 /* Parameter */: + break; + case 204 /* ClassDeclaration */: + case 205 /* InterfaceDeclaration */: + case 183 /* VariableStatement */: + case 203 /* FunctionDeclaration */: + case 206 /* TypeAliasDeclaration */: + if (node.modifiers && node.parent.kind !== 209 /* ModuleBlock */ && node.parent.kind !== 230 /* SourceFile */) { + return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here); + } + break; + case 207 /* EnumDeclaration */: + if (node.modifiers && (node.modifiers.length > 1 || node.modifiers[0].kind !== 70 /* ConstKeyword */) && + node.parent.kind !== 209 /* ModuleBlock */ && node.parent.kind !== 230 /* SourceFile */) { + return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here); + } break; default: return false; @@ -21938,7 +23676,7 @@ var ts; else if (flags & 128 /* Static */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "static"); } - else if (node.parent.kind === 207 /* ModuleBlock */ || node.parent.kind === 228 /* SourceFile */) { + else if (node.parent.kind === 209 /* ModuleBlock */ || node.parent.kind === 230 /* SourceFile */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_element, text); } flags |= ts.modifierToFlag(modifier.kind); @@ -21947,10 +23685,10 @@ var ts; if (flags & 128 /* Static */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "static"); } - else if (node.parent.kind === 207 /* ModuleBlock */ || node.parent.kind === 228 /* SourceFile */) { + else if (node.parent.kind === 209 /* ModuleBlock */ || node.parent.kind === 230 /* SourceFile */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_element, "static"); } - else if (node.kind === 130 /* Parameter */) { + else if (node.kind === 131 /* Parameter */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "static"); } flags |= 128 /* Static */; @@ -21963,10 +23701,10 @@ var ts; else if (flags & 2 /* Ambient */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "export", "declare"); } - else if (node.parent.kind === 202 /* ClassDeclaration */) { + else if (node.parent.kind === 204 /* ClassDeclaration */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_class_element, "export"); } - else if (node.kind === 130 /* Parameter */) { + else if (node.kind === 131 /* Parameter */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "export"); } flags |= 1 /* Export */; @@ -21975,13 +23713,13 @@ var ts; if (flags & 2 /* Ambient */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "declare"); } - else if (node.parent.kind === 202 /* ClassDeclaration */) { + else if (node.parent.kind === 204 /* ClassDeclaration */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_class_element, "declare"); } - else if (node.kind === 130 /* Parameter */) { + else if (node.kind === 131 /* Parameter */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "declare"); } - else if (ts.isInAmbientContext(node.parent) && node.parent.kind === 207 /* ModuleBlock */) { + else if (ts.isInAmbientContext(node.parent) && node.parent.kind === 209 /* ModuleBlock */) { return grammarErrorOnNode(modifier, ts.Diagnostics.A_declare_modifier_cannot_be_used_in_an_already_ambient_context); } flags |= 2 /* Ambient */; @@ -21989,7 +23727,7 @@ var ts; break; } } - if (node.kind === 136 /* Constructor */) { + if (node.kind === 137 /* Constructor */) { if (flags & 128 /* Static */) { return grammarErrorOnNode(lastStatic, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "static"); } @@ -22000,13 +23738,10 @@ var ts; return grammarErrorOnNode(lastPrivate, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "private"); } } - else if ((node.kind === 210 /* ImportDeclaration */ || node.kind === 209 /* ImportEqualsDeclaration */) && flags & 2 /* Ambient */) { + else if ((node.kind === 212 /* ImportDeclaration */ || node.kind === 211 /* ImportEqualsDeclaration */) && flags & 2 /* Ambient */) { return grammarErrorOnNode(lastDeclare, ts.Diagnostics.A_declare_modifier_cannot_be_used_with_an_import_declaration, "declare"); } - else if (node.kind === 203 /* InterfaceDeclaration */ && flags & 2 /* Ambient */) { - return grammarErrorOnNode(lastDeclare, ts.Diagnostics.A_declare_modifier_cannot_be_used_with_an_interface_declaration, "declare"); - } - else if (node.kind === 130 /* Parameter */ && (flags & 112 /* AccessibilityModifier */) && ts.isBindingPattern(node.name)) { + else if (node.kind === 131 /* Parameter */ && (flags & 112 /* AccessibilityModifier */) && ts.isBindingPattern(node.name)) { return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_may_not_be_a_binding_pattern); } } @@ -22070,7 +23805,7 @@ var ts; checkGrammarParameterList(node.parameters) || checkGrammarArrowFunction(node, file); } function checkGrammarArrowFunction(node, file) { - if (node.kind === 164 /* ArrowFunction */) { + if (node.kind === 166 /* ArrowFunction */) { var arrowFunction = node; var startLine = ts.getLineAndCharacterOfPosition(file, arrowFunction.equalsGreaterThanToken.pos).line; var endLine = ts.getLineAndCharacterOfPosition(file, arrowFunction.equalsGreaterThanToken.end).line; @@ -22105,7 +23840,7 @@ var ts; if (!parameter.type) { return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_must_have_a_type_annotation); } - if (parameter.type.kind !== 122 /* StringKeyword */ && parameter.type.kind !== 120 /* NumberKeyword */) { + if (parameter.type.kind !== 123 /* StringKeyword */ && parameter.type.kind !== 121 /* NumberKeyword */) { return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_must_be_string_or_number); } if (!node.type) { @@ -22138,7 +23873,7 @@ var ts; var sourceFile = ts.getSourceFileOfNode(node); for (var _i = 0; _i < arguments.length; _i++) { var arg = arguments[_i]; - if (arg.kind === 176 /* OmittedExpression */) { + if (arg.kind === 178 /* OmittedExpression */) { return grammarErrorAtPos(sourceFile, arg.pos, 0, ts.Diagnostics.Argument_expression_expected); } } @@ -22212,23 +23947,30 @@ var ts; } function checkGrammarComputedPropertyName(node) { // If node is not a computedPropertyName, just skip the grammar checking - if (node.kind !== 128 /* ComputedPropertyName */) { + if (node.kind !== 129 /* ComputedPropertyName */) { return false; } var computedPropertyName = node; - if (computedPropertyName.expression.kind === 170 /* BinaryExpression */ && computedPropertyName.expression.operatorToken.kind === 23 /* CommaToken */) { + if (computedPropertyName.expression.kind === 172 /* BinaryExpression */ && computedPropertyName.expression.operatorToken.kind === 23 /* CommaToken */) { return grammarErrorOnNode(computedPropertyName.expression, ts.Diagnostics.A_comma_expression_is_not_allowed_in_a_computed_property_name); } } function checkGrammarForGenerator(node) { if (node.asteriskToken) { - return grammarErrorOnNode(node.asteriskToken, ts.Diagnostics.Generators_are_not_currently_supported); + ts.Debug.assert(node.kind === 203 /* FunctionDeclaration */ || + node.kind === 165 /* FunctionExpression */ || + node.kind === 136 /* 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); + } + if (languageVersion < 2 /* ES6 */) { + return grammarErrorOnNode(node.asteriskToken, ts.Diagnostics.Generators_are_only_available_when_targeting_ECMAScript_6_or_higher); + } } } - function checkGrammarFunctionName(name) { - // It is a SyntaxError if the identifier eval or arguments appears within a FormalParameterList of a strict mode FunctionDeclaration or FunctionExpression (13.1)) - return checkGrammarEvalOrArgumentsInStrictMode(name, name); - } function checkGrammarForInvalidQuestionMark(node, questionToken, message) { if (questionToken) { return grammarErrorOnNode(questionToken, message); @@ -22240,14 +23982,13 @@ var ts; var GetAccessor = 2; var SetAccesor = 4; var GetOrSetAccessor = GetAccessor | SetAccesor; - var inStrictMode = (node.parserContextFlags & 1 /* StrictMode */) !== 0; for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { var prop = _a[_i]; - var name_13 = prop.name; - if (prop.kind === 176 /* OmittedExpression */ || - name_13.kind === 128 /* ComputedPropertyName */) { + var name_15 = prop.name; + if (prop.kind === 178 /* OmittedExpression */ || + name_15.kind === 129 /* ComputedPropertyName */) { // If the name is not a ComputedPropertyName, the grammar checking will skip it - checkGrammarComputedPropertyName(name_13); + checkGrammarComputedPropertyName(name_15); continue; } // ECMA-262 11.1.5 Object Initialiser @@ -22259,46 +24000,44 @@ var ts; // 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 === 225 /* PropertyAssignment */ || prop.kind === 226 /* ShorthandPropertyAssignment */) { + if (prop.kind === 227 /* PropertyAssignment */ || prop.kind === 228 /* ShorthandPropertyAssignment */) { // Grammar checking for computedPropertName and shorthandPropertyAssignment checkGrammarForInvalidQuestionMark(prop, prop.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional); - if (name_13.kind === 7 /* NumericLiteral */) { - checkGrammarNumericLiteral(name_13); + if (name_15.kind === 7 /* NumericLiteral */) { + checkGrammarNumericLiteral(name_15); } currentKind = Property; } - else if (prop.kind === 135 /* MethodDeclaration */) { + else if (prop.kind === 136 /* MethodDeclaration */) { currentKind = Property; } - else if (prop.kind === 137 /* GetAccessor */) { + else if (prop.kind === 138 /* GetAccessor */) { currentKind = GetAccessor; } - else if (prop.kind === 138 /* SetAccessor */) { + else if (prop.kind === 139 /* SetAccessor */) { currentKind = SetAccesor; } else { ts.Debug.fail("Unexpected syntax kind:" + prop.kind); } - if (!ts.hasProperty(seen, name_13.text)) { - seen[name_13.text] = currentKind; + if (!ts.hasProperty(seen, name_15.text)) { + seen[name_15.text] = currentKind; } else { - var existingKind = seen[name_13.text]; + var existingKind = seen[name_15.text]; if (currentKind === Property && existingKind === Property) { - if (inStrictMode) { - grammarErrorOnNode(name_13, ts.Diagnostics.An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode); - } + continue; } else if ((currentKind & GetOrSetAccessor) && (existingKind & GetOrSetAccessor)) { if (existingKind !== GetOrSetAccessor && currentKind !== existingKind) { - seen[name_13.text] = currentKind | existingKind; + seen[name_15.text] = currentKind | existingKind; } else { - return grammarErrorOnNode(name_13, ts.Diagnostics.An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name); + return grammarErrorOnNode(name_15, ts.Diagnostics.An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name); } } else { - return grammarErrorOnNode(name_13, ts.Diagnostics.An_object_literal_cannot_have_property_and_accessor_with_the_same_name); + return grammarErrorOnNode(name_15, ts.Diagnostics.An_object_literal_cannot_have_property_and_accessor_with_the_same_name); } } } @@ -22307,24 +24046,24 @@ var ts; if (checkGrammarStatementInAmbientContext(forInOrOfStatement)) { return true; } - if (forInOrOfStatement.initializer.kind === 200 /* VariableDeclarationList */) { + if (forInOrOfStatement.initializer.kind === 202 /* VariableDeclarationList */) { var variableList = forInOrOfStatement.initializer; if (!checkGrammarVariableDeclarationList(variableList)) { if (variableList.declarations.length > 1) { - var diagnostic = forInOrOfStatement.kind === 188 /* ForInStatement */ + var diagnostic = forInOrOfStatement.kind === 190 /* 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 = variableList.declarations[0]; if (firstDeclaration.initializer) { - var diagnostic = forInOrOfStatement.kind === 188 /* ForInStatement */ + var diagnostic = forInOrOfStatement.kind === 190 /* 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 === 188 /* ForInStatement */ + var diagnostic = forInOrOfStatement.kind === 190 /* 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); @@ -22347,10 +24086,10 @@ var ts; else if (accessor.typeParameters) { return grammarErrorOnNode(accessor.name, ts.Diagnostics.An_accessor_cannot_have_type_parameters); } - else if (kind === 137 /* GetAccessor */ && accessor.parameters.length) { + else if (kind === 138 /* GetAccessor */ && accessor.parameters.length) { return grammarErrorOnNode(accessor.name, ts.Diagnostics.A_get_accessor_cannot_have_parameters); } - else if (kind === 138 /* SetAccessor */) { + else if (kind === 139 /* SetAccessor */) { if (accessor.type) { return grammarErrorOnNode(accessor.name, ts.Diagnostics.A_set_accessor_cannot_have_a_return_type_annotation); } @@ -22375,7 +24114,7 @@ var ts; } } function checkGrammarForNonSymbolComputedProperty(node, message) { - if (node.kind === 128 /* ComputedPropertyName */ && !ts.isWellKnownSymbolSyntactically(node.expression)) { + if (node.kind === 129 /* ComputedPropertyName */ && !ts.isWellKnownSymbolSyntactically(node.expression)) { return grammarErrorOnNode(node, message); } } @@ -22385,7 +24124,7 @@ var ts; checkGrammarForGenerator(node)) { return true; } - if (node.parent.kind === 155 /* ObjectLiteralExpression */) { + if (node.parent.kind === 157 /* ObjectLiteralExpression */) { if (checkGrammarForInvalidQuestionMark(node, node.questionToken, ts.Diagnostics.A_class_member_cannot_be_declared_optional)) { return true; } @@ -22393,7 +24132,7 @@ var ts; return grammarErrorAtPos(getSourceFile(node), node.end - 1, ";".length, ts.Diagnostics._0_expected, "{"); } } - if (node.parent.kind === 202 /* ClassDeclaration */) { + if (node.parent.kind === 204 /* ClassDeclaration */) { if (checkGrammarForInvalidQuestionMark(node, node.questionToken, ts.Diagnostics.A_class_member_cannot_be_declared_optional)) { return true; } @@ -22409,22 +24148,22 @@ var ts; 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 === 203 /* InterfaceDeclaration */) { + else if (node.parent.kind === 205 /* 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 === 146 /* TypeLiteral */) { + else if (node.parent.kind === 148 /* TypeLiteral */) { return checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_a_type_literal_must_directly_refer_to_a_built_in_symbol); } } function isIterationStatement(node, lookInLabeledStatements) { switch (node.kind) { - case 187 /* ForStatement */: - case 188 /* ForInStatement */: - case 189 /* ForOfStatement */: - case 185 /* DoStatement */: - case 186 /* WhileStatement */: + case 189 /* ForStatement */: + case 190 /* ForInStatement */: + case 191 /* ForOfStatement */: + case 187 /* DoStatement */: + case 188 /* WhileStatement */: return true; - case 195 /* LabeledStatement */: + case 197 /* LabeledStatement */: return lookInLabeledStatements && isIterationStatement(node.statement, lookInLabeledStatements); } return false; @@ -22436,11 +24175,11 @@ var ts; return grammarErrorOnNode(node, ts.Diagnostics.Jump_target_cannot_cross_function_boundary); } switch (current.kind) { - case 195 /* LabeledStatement */: + case 197 /* 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 === 190 /* ContinueStatement */ + var isMisplacedContinueLabel = node.kind === 192 /* ContinueStatement */ && !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); @@ -22448,8 +24187,8 @@ var ts; return false; } break; - case 194 /* SwitchStatement */: - if (node.kind === 191 /* BreakStatement */ && !node.label) { + case 196 /* SwitchStatement */: + if (node.kind === 193 /* BreakStatement */ && !node.label) { // unlabeled break within switch statement - ok return false; } @@ -22464,13 +24203,13 @@ var ts; current = current.parent; } if (node.label) { - var message = node.kind === 191 /* BreakStatement */ + var message = node.kind === 193 /* 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 === 191 /* BreakStatement */ + var message = node.kind === 193 /* 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); @@ -22482,7 +24221,7 @@ var ts; if (node !== ts.lastOrUndefined(elements)) { return grammarErrorOnNode(node, ts.Diagnostics.A_rest_element_must_be_last_in_an_array_destructuring_pattern); } - if (node.name.kind === 152 /* ArrayBindingPattern */ || node.name.kind === 151 /* ObjectBindingPattern */) { + if (node.name.kind === 154 /* ArrayBindingPattern */ || node.name.kind === 153 /* ObjectBindingPattern */) { return grammarErrorOnNode(node.name, ts.Diagnostics.A_rest_element_cannot_contain_a_binding_pattern); } if (node.initializer) { @@ -22490,12 +24229,9 @@ var ts; return grammarErrorAtPos(ts.getSourceFileOfNode(node), node.initializer.pos - 1, 1, ts.Diagnostics.A_rest_element_cannot_have_an_initializer); } } - // It is a SyntaxError if a VariableDeclaration or VariableDeclarationNoIn occurs within strict code - // and its Identifier is eval or arguments - return checkGrammarEvalOrArgumentsInStrictMode(node, node.name); } function checkGrammarVariableDeclaration(node) { - if (node.parent.parent.kind !== 188 /* ForInStatement */ && node.parent.parent.kind !== 189 /* ForOfStatement */) { + if (node.parent.parent.kind !== 190 /* ForInStatement */ && node.parent.parent.kind !== 191 /* ForOfStatement */) { if (ts.isInAmbientContext(node)) { if (node.initializer) { // Error on equals token which immediate precedes the initializer @@ -22519,8 +24255,7 @@ var ts; // 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)) || - checkGrammarEvalOrArgumentsInStrictMode(node, node.name); + return checkLetConstNames && checkGrammarNameInLetOrConstDeclarations(node.name); } function checkGrammarNameInLetOrConstDeclarations(name) { if (name.kind === 65 /* Identifier */) { @@ -22532,7 +24267,7 @@ var ts; var elements = name.elements; for (var _i = 0; _i < elements.length; _i++) { var element = elements[_i]; - if (element.kind !== 176 /* OmittedExpression */) { + if (element.kind !== 178 /* OmittedExpression */) { checkGrammarNameInLetOrConstDeclarations(element.name); } } @@ -22549,15 +24284,15 @@ var ts; } function allowLetAndConstDeclarations(parent) { switch (parent.kind) { - case 184 /* IfStatement */: - case 185 /* DoStatement */: - case 186 /* WhileStatement */: - case 193 /* WithStatement */: - case 187 /* ForStatement */: - case 188 /* ForInStatement */: - case 189 /* ForOfStatement */: + case 186 /* IfStatement */: + case 187 /* DoStatement */: + case 188 /* WhileStatement */: + case 195 /* WithStatement */: + case 189 /* ForStatement */: + case 190 /* ForInStatement */: + case 191 /* ForOfStatement */: return false; - case 195 /* LabeledStatement */: + case 197 /* LabeledStatement */: return allowLetAndConstDeclarations(parent.parent); } return true; @@ -22573,7 +24308,7 @@ var ts; } } function isIntegerLiteral(expression) { - if (expression.kind === 168 /* PrefixUnaryExpression */) { + if (expression.kind === 170 /* PrefixUnaryExpression */) { var unaryExpression = expression; if (unaryExpression.operator === 33 /* PlusToken */ || unaryExpression.operator === 34 /* MinusToken */) { expression = unaryExpression.operand; @@ -22602,7 +24337,7 @@ var ts; // 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 === 128 /* ComputedPropertyName */) { + if (node.name.kind === 129 /* ComputedPropertyName */) { hasError = grammarErrorOnNode(node.name, ts.Diagnostics.Computed_property_names_are_not_allowed_in_enums); } else if (inAmbientContext) { @@ -22644,26 +24379,6 @@ var ts; return true; } } - function checkGrammarEvalOrArgumentsInStrictMode(contextNode, name) { - if (name && name.kind === 65 /* Identifier */) { - var identifier = name; - if (contextNode && (contextNode.parserContextFlags & 1 /* StrictMode */) && isEvalOrArgumentsIdentifier(identifier)) { - var nameText = ts.declarationNameToString(identifier); - // We check first if the name is inside class declaration or class expression; if so give explicit message - // otherwise report generic error message. - // reportGrammarErrorInClassDeclaration only return true if grammar error is successfully reported and false otherwise - var reportErrorInClassDeclaration = reportStrictModeGrammarErrorInClassDeclaration(identifier, ts.Diagnostics.Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode, nameText); - if (!reportErrorInClassDeclaration) { - return grammarErrorOnNode(identifier, ts.Diagnostics.Invalid_use_of_0_in_strict_mode, nameText); - } - return reportErrorInClassDeclaration; - } - } - } - function isEvalOrArgumentsIdentifier(node) { - return node.kind === 65 /* Identifier */ && - (node.text === "eval" || node.text === "arguments"); - } 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); @@ -22675,18 +24390,18 @@ var ts; } } function checkGrammarProperty(node) { - if (node.parent.kind === 202 /* ClassDeclaration */) { + if (node.parent.kind === 204 /* ClassDeclaration */) { if (checkGrammarForInvalidQuestionMark(node, node.questionToken, ts.Diagnostics.A_class_member_cannot_be_declared_optional) || 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 === 203 /* InterfaceDeclaration */) { + else if (node.parent.kind === 205 /* InterfaceDeclaration */) { if (checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_an_interface_must_directly_refer_to_a_built_in_symbol)) { return true; } } - else if (node.parent.kind === 146 /* TypeLiteral */) { + else if (node.parent.kind === 148 /* 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; } @@ -22706,11 +24421,11 @@ var ts; // export_opt ExternalImportDeclaration // export_opt AmbientDeclaration // - if (node.kind === 203 /* InterfaceDeclaration */ || - node.kind === 210 /* ImportDeclaration */ || - node.kind === 209 /* ImportEqualsDeclaration */ || - node.kind === 216 /* ExportDeclaration */ || - node.kind === 215 /* ExportAssignment */ || + if (node.kind === 205 /* InterfaceDeclaration */ || + node.kind === 212 /* ImportDeclaration */ || + node.kind === 211 /* ImportEqualsDeclaration */ || + node.kind === 218 /* ExportDeclaration */ || + node.kind === 217 /* ExportAssignment */ || (node.flags & 2 /* Ambient */) || (node.flags & (1 /* Export */ | 256 /* Default */))) { return false; @@ -22720,7 +24435,7 @@ var ts; function checkGrammarTopLevelElementsForRequiredDeclareModifier(file) { for (var _i = 0, _a = file.statements; _i < _a.length; _i++) { var decl = _a[_i]; - if (ts.isDeclaration(decl) || decl.kind === 181 /* VariableStatement */) { + if (ts.isDeclaration(decl) || decl.kind === 183 /* VariableStatement */) { if (checkGrammarTopLevelElementForRequiredDeclareModifier(decl)) { return true; } @@ -22746,7 +24461,7 @@ var ts; // to prevent noisyness. 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 === 180 /* Block */ || node.parent.kind === 207 /* ModuleBlock */ || node.parent.kind === 228 /* SourceFile */) { + if (node.parent.kind === 182 /* Block */ || node.parent.kind === 209 /* ModuleBlock */ || node.parent.kind === 230 /* SourceFile */) { var links_1 = getNodeLinks(node.parent); // Check if the containing block ever report this error if (!links_1.hasReportedStatementInAmbientContext) { @@ -22759,13 +24474,8 @@ var ts; } function checkGrammarNumericLiteral(node) { // Grammar checking - if (node.flags & 16384 /* OctalLiteral */) { - if (node.parserContextFlags & 1 /* StrictMode */) { - return grammarErrorOnNode(node, ts.Diagnostics.Octal_literals_are_not_allowed_in_strict_mode); - } - else if (languageVersion >= 1 /* ES5 */) { - return grammarErrorOnNode(node, ts.Diagnostics.Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher); - } + if (node.flags & 16384 /* OctalLiteral */ && languageVersion >= 1 /* ES5 */) { + return grammarErrorOnNode(node, ts.Diagnostics.Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher); } } function grammarErrorAfterFirstToken(node, message, arg0, arg1, arg2) { @@ -22776,8 +24486,6 @@ var ts; return true; } } - initializeTypeChecker(); - return checker; } ts.createTypeChecker = createTypeChecker; })(ts || (ts = {})); @@ -22836,7 +24544,7 @@ var ts; var oldWriter = writer; ts.forEach(moduleElementDeclarationEmitInfo, function (aliasEmitInfo) { if (aliasEmitInfo.isVisible) { - ts.Debug.assert(aliasEmitInfo.node.kind === 210 /* ImportDeclaration */); + ts.Debug.assert(aliasEmitInfo.node.kind === 212 /* ImportDeclaration */); createAndSetNewTextWriterWithSymbolWriter(); ts.Debug.assert(aliasEmitInfo.indent === 0); writeImportDeclaration(aliasEmitInfo.node); @@ -22912,10 +24620,10 @@ var ts; var oldWriter = writer; ts.forEach(nodes, function (declaration) { var nodeToCheck; - if (declaration.kind === 199 /* VariableDeclaration */) { + if (declaration.kind === 201 /* VariableDeclaration */) { nodeToCheck = declaration.parent.parent; } - else if (declaration.kind === 213 /* NamedImports */ || declaration.kind === 214 /* ImportSpecifier */ || declaration.kind === 211 /* ImportClause */) { + else if (declaration.kind === 215 /* NamedImports */ || declaration.kind === 216 /* ImportSpecifier */ || declaration.kind === 213 /* ImportClause */) { ts.Debug.fail("We should be getting ImportDeclaration instead to write"); } else { @@ -22933,7 +24641,7 @@ var ts; // Writing of function bar would mark alias declaration foo as visible but we haven't yet visited that declaration so do nothing, // we would write alias foo declaration when we visit it since it would now be marked as visible if (moduleElementEmitInfo) { - if (moduleElementEmitInfo.node.kind === 210 /* ImportDeclaration */) { + if (moduleElementEmitInfo.node.kind === 212 /* ImportDeclaration */) { // we have to create asynchronous output only after we have collected complete information // because it is possible to enable multiple bindings as asynchronously visible moduleElementEmitInfo.isVisible = true; @@ -22943,12 +24651,12 @@ var ts; for (var declarationIndent = moduleElementEmitInfo.indent; declarationIndent; declarationIndent--) { increaseIndent(); } - if (nodeToCheck.kind === 206 /* ModuleDeclaration */) { + if (nodeToCheck.kind === 208 /* ModuleDeclaration */) { ts.Debug.assert(asynchronousSubModuleDeclarationEmitInfo === undefined); asynchronousSubModuleDeclarationEmitInfo = []; } writeModuleElement(nodeToCheck); - if (nodeToCheck.kind === 206 /* ModuleDeclaration */) { + if (nodeToCheck.kind === 208 /* ModuleDeclaration */) { moduleElementEmitInfo.subModuleElementDeclarationEmitInfo = asynchronousSubModuleDeclarationEmitInfo; asynchronousSubModuleDeclarationEmitInfo = undefined; } @@ -23041,41 +24749,41 @@ var ts; function emitType(type) { switch (type.kind) { case 112 /* AnyKeyword */: - case 122 /* StringKeyword */: - case 120 /* NumberKeyword */: + case 123 /* StringKeyword */: + case 121 /* NumberKeyword */: case 113 /* BooleanKeyword */: - case 123 /* SymbolKeyword */: + case 124 /* SymbolKeyword */: case 99 /* VoidKeyword */: case 8 /* StringLiteral */: return writeTextOfNode(currentSourceFile, type); - case 177 /* ExpressionWithTypeArguments */: + case 179 /* ExpressionWithTypeArguments */: return emitExpressionWithTypeArguments(type); - case 142 /* TypeReference */: + case 144 /* TypeReference */: return emitTypeReference(type); - case 145 /* TypeQuery */: + case 147 /* TypeQuery */: return emitTypeQuery(type); - case 147 /* ArrayType */: + case 149 /* ArrayType */: return emitArrayType(type); - case 148 /* TupleType */: + case 150 /* TupleType */: return emitTupleType(type); - case 149 /* UnionType */: + case 151 /* UnionType */: return emitUnionType(type); - case 150 /* ParenthesizedType */: + case 152 /* ParenthesizedType */: return emitParenType(type); - case 143 /* FunctionType */: - case 144 /* ConstructorType */: + case 145 /* FunctionType */: + case 146 /* ConstructorType */: return emitSignatureDeclarationWithJsDocComments(type); - case 146 /* TypeLiteral */: + case 148 /* TypeLiteral */: return emitTypeLiteral(type); case 65 /* Identifier */: return emitEntityName(type); - case 127 /* QualifiedName */: + case 128 /* QualifiedName */: return emitEntityName(type); } function emitEntityName(entityName) { var visibilityResult = resolver.isEntityNameVisible(entityName, // Aliases can be written asynchronously so use correct enclosing declaration - entityName.parent.kind === 209 /* ImportEqualsDeclaration */ ? entityName.parent : enclosingDeclaration); + entityName.parent.kind === 211 /* ImportEqualsDeclaration */ ? entityName.parent : enclosingDeclaration); handleSymbolAccessibilityError(visibilityResult); writeEntityName(entityName); function writeEntityName(entityName) { @@ -23083,8 +24791,8 @@ var ts; writeTextOfNode(currentSourceFile, entityName); } else { - var left = entityName.kind === 127 /* QualifiedName */ ? entityName.left : entityName.expression; - var right = entityName.kind === 127 /* QualifiedName */ ? entityName.right : entityName.name; + var left = entityName.kind === 128 /* QualifiedName */ ? entityName.left : entityName.expression; + var right = entityName.kind === 128 /* QualifiedName */ ? entityName.right : entityName.name; writeEntityName(left); write("."); writeTextOfNode(currentSourceFile, right); @@ -23093,7 +24801,7 @@ var ts; } function emitExpressionWithTypeArguments(node) { if (ts.isSupportedExpressionWithTypeArguments(node)) { - ts.Debug.assert(node.expression.kind === 65 /* Identifier */ || node.expression.kind === 156 /* PropertyAccessExpression */); + ts.Debug.assert(node.expression.kind === 65 /* Identifier */ || node.expression.kind === 158 /* PropertyAccessExpression */); emitEntityName(node.expression); if (node.typeArguments) { write("<"); @@ -23159,9 +24867,9 @@ var ts; } var count = 0; while (true) { - var name_14 = baseName + "_" + (++count); - if (!ts.hasProperty(currentSourceFile.identifiers, name_14)) { - return name_14; + var name_16 = baseName + "_" + (++count); + if (!ts.hasProperty(currentSourceFile.identifiers, name_16)) { + return name_16; } } } @@ -23205,10 +24913,10 @@ var ts; if (isModuleElementVisible) { writeModuleElement(node); } - else if (node.kind === 209 /* ImportEqualsDeclaration */ || - (node.parent.kind === 228 /* SourceFile */ && ts.isExternalModule(currentSourceFile))) { + else if (node.kind === 211 /* ImportEqualsDeclaration */ || + (node.parent.kind === 230 /* SourceFile */ && ts.isExternalModule(currentSourceFile))) { var isVisible; - if (asynchronousSubModuleDeclarationEmitInfo && node.parent.kind !== 228 /* SourceFile */) { + if (asynchronousSubModuleDeclarationEmitInfo && node.parent.kind !== 230 /* SourceFile */) { // Import declaration of another module that is visited async so lets put it in right spot asynchronousSubModuleDeclarationEmitInfo.push({ node: node, @@ -23218,7 +24926,7 @@ var ts; }); } else { - if (node.kind === 210 /* ImportDeclaration */) { + if (node.kind === 212 /* ImportDeclaration */) { var importDeclaration = node; if (importDeclaration.importClause) { isVisible = (importDeclaration.importClause.name && resolver.isDeclarationVisible(importDeclaration.importClause)) || @@ -23236,23 +24944,23 @@ var ts; } function writeModuleElement(node) { switch (node.kind) { - case 201 /* FunctionDeclaration */: + case 203 /* FunctionDeclaration */: return writeFunctionDeclaration(node); - case 181 /* VariableStatement */: + case 183 /* VariableStatement */: return writeVariableStatement(node); - case 203 /* InterfaceDeclaration */: + case 205 /* InterfaceDeclaration */: return writeInterfaceDeclaration(node); - case 202 /* ClassDeclaration */: + case 204 /* ClassDeclaration */: return writeClassDeclaration(node); - case 204 /* TypeAliasDeclaration */: + case 206 /* TypeAliasDeclaration */: return writeTypeAliasDeclaration(node); - case 205 /* EnumDeclaration */: + case 207 /* EnumDeclaration */: return writeEnumDeclaration(node); - case 206 /* ModuleDeclaration */: + case 208 /* ModuleDeclaration */: return writeModuleDeclaration(node); - case 209 /* ImportEqualsDeclaration */: + case 211 /* ImportEqualsDeclaration */: return writeImportEqualsDeclaration(node); - case 210 /* ImportDeclaration */: + case 212 /* ImportDeclaration */: return writeImportDeclaration(node); default: ts.Debug.fail("Unknown symbol kind"); @@ -23268,7 +24976,7 @@ var ts; if (node.flags & 256 /* Default */) { write("default "); } - else if (node.kind !== 203 /* InterfaceDeclaration */) { + else if (node.kind !== 205 /* InterfaceDeclaration */) { write("declare "); } } @@ -23314,7 +25022,7 @@ var ts; } function isVisibleNamedBinding(namedBindings) { if (namedBindings) { - if (namedBindings.kind === 212 /* NamespaceImport */) { + if (namedBindings.kind === 214 /* NamespaceImport */) { return resolver.isDeclarationVisible(namedBindings); } else { @@ -23342,7 +25050,7 @@ var ts; // If the default binding was emitted, write the separated write(", "); } - if (node.importClause.namedBindings.kind === 212 /* NamespaceImport */) { + if (node.importClause.namedBindings.kind === 214 /* NamespaceImport */) { write("* as "); writeTextOfNode(currentSourceFile, node.importClause.namedBindings.name); } @@ -23393,9 +25101,14 @@ var ts; function writeModuleDeclaration(node) { emitJsDocComments(node); emitModuleElementDeclarationFlags(node); - write("module "); + if (node.flags & 32768 /* Namespace */) { + write("namespace "); + } + else { + write("module "); + } writeTextOfNode(currentSourceFile, node.name); - while (node.body.kind !== 207 /* ModuleBlock */) { + while (node.body.kind !== 209 /* ModuleBlock */) { node = node.body; write("."); writeTextOfNode(currentSourceFile, node.name); @@ -23456,7 +25169,7 @@ var ts; writeLine(); } function isPrivateMethodTypeParameter(node) { - return node.parent.kind === 135 /* MethodDeclaration */ && (node.parent.flags & 32 /* Private */); + return node.parent.kind === 136 /* MethodDeclaration */ && (node.parent.flags & 32 /* Private */); } function emitTypeParameters(typeParameters) { function emitTypeParameter(node) { @@ -23467,15 +25180,15 @@ var ts; // If there is constraint present and this is not a type parameter of the private method emit the constraint if (node.constraint && !isPrivateMethodTypeParameter(node)) { write(" extends "); - if (node.parent.kind === 143 /* FunctionType */ || - node.parent.kind === 144 /* ConstructorType */ || - (node.parent.parent && node.parent.parent.kind === 146 /* TypeLiteral */)) { - ts.Debug.assert(node.parent.kind === 135 /* MethodDeclaration */ || - node.parent.kind === 134 /* MethodSignature */ || - node.parent.kind === 143 /* FunctionType */ || - node.parent.kind === 144 /* ConstructorType */ || - node.parent.kind === 139 /* CallSignature */ || - node.parent.kind === 140 /* ConstructSignature */); + if (node.parent.kind === 145 /* FunctionType */ || + node.parent.kind === 146 /* ConstructorType */ || + (node.parent.parent && node.parent.parent.kind === 148 /* TypeLiteral */)) { + ts.Debug.assert(node.parent.kind === 136 /* MethodDeclaration */ || + node.parent.kind === 135 /* MethodSignature */ || + node.parent.kind === 145 /* FunctionType */ || + node.parent.kind === 146 /* ConstructorType */ || + node.parent.kind === 140 /* CallSignature */ || + node.parent.kind === 141 /* ConstructSignature */); emitType(node.constraint); } else { @@ -23486,31 +25199,31 @@ var ts; // Type parameter constraints are named by user so we should always be able to name it var diagnosticMessage; switch (node.parent.kind) { - case 202 /* ClassDeclaration */: + case 204 /* ClassDeclaration */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_class_has_or_is_using_private_name_1; break; - case 203 /* InterfaceDeclaration */: + case 205 /* InterfaceDeclaration */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1; break; - case 140 /* ConstructSignature */: + case 141 /* ConstructSignature */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1; break; - case 139 /* CallSignature */: + case 140 /* CallSignature */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1; break; - case 135 /* MethodDeclaration */: - case 134 /* MethodSignature */: + case 136 /* MethodDeclaration */: + case 135 /* MethodSignature */: if (node.parent.flags & 128 /* Static */) { diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1; } - else if (node.parent.parent.kind === 202 /* ClassDeclaration */) { + else if (node.parent.parent.kind === 204 /* ClassDeclaration */) { diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1; } else { diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1; } break; - case 201 /* FunctionDeclaration */: + case 203 /* FunctionDeclaration */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_function_has_or_is_using_private_name_1; break; default: @@ -23541,7 +25254,7 @@ var ts; function getHeritageClauseVisibilityError(symbolAccesibilityResult) { var diagnosticMessage; // Heritage clause is written by user so it can always be named - if (node.parent.parent.kind === 202 /* ClassDeclaration */) { + if (node.parent.parent.kind === 204 /* ClassDeclaration */) { // Class or Interface implemented/extended is inaccessible diagnosticMessage = isImplementsList ? ts.Diagnostics.Implements_clause_of_exported_class_0_has_or_is_using_private_name_1 : @@ -23622,7 +25335,7 @@ var ts; function emitVariableDeclaration(node) { // If we are emitting property it isn't moduleElement and hence we already know it needs to be emitted // so there is no check needed to see if declaration is visible - if (node.kind !== 199 /* VariableDeclaration */ || resolver.isDeclarationVisible(node)) { + if (node.kind !== 201 /* VariableDeclaration */ || resolver.isDeclarationVisible(node)) { if (ts.isBindingPattern(node.name)) { emitBindingPattern(node.name); } @@ -23632,10 +25345,10 @@ var ts; // what we want, namely the name expression enclosed in brackets. writeTextOfNode(currentSourceFile, node.name); // If optional property emit ? - if ((node.kind === 133 /* PropertyDeclaration */ || node.kind === 132 /* PropertySignature */) && ts.hasQuestionToken(node)) { + if ((node.kind === 134 /* PropertyDeclaration */ || node.kind === 133 /* PropertySignature */) && ts.hasQuestionToken(node)) { write("?"); } - if ((node.kind === 133 /* PropertyDeclaration */ || node.kind === 132 /* PropertySignature */) && node.parent.kind === 146 /* TypeLiteral */) { + if ((node.kind === 134 /* PropertyDeclaration */ || node.kind === 133 /* PropertySignature */) && node.parent.kind === 148 /* TypeLiteral */) { emitTypeOfVariableDeclarationFromTypeLiteral(node); } else if (!(node.flags & 32 /* Private */)) { @@ -23644,14 +25357,14 @@ var ts; } } function getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccesibilityResult) { - if (node.kind === 199 /* VariableDeclaration */) { + if (node.kind === 201 /* VariableDeclaration */) { return symbolAccesibilityResult.errorModuleName ? symbolAccesibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : ts.Diagnostics.Exported_variable_0_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Exported_variable_0_has_or_is_using_private_name_1; } - else if (node.kind === 133 /* PropertyDeclaration */ || node.kind === 132 /* PropertySignature */) { + else if (node.kind === 134 /* PropertyDeclaration */ || node.kind === 133 /* PropertySignature */) { // TODO(jfreeman): Deal with computed properties in error reporting. if (node.flags & 128 /* Static */) { return symbolAccesibilityResult.errorModuleName ? @@ -23660,7 +25373,7 @@ var ts; ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_private_name_1; } - else if (node.parent.kind === 202 /* ClassDeclaration */) { + else if (node.parent.kind === 204 /* ClassDeclaration */) { return symbolAccesibilityResult.errorModuleName ? symbolAccesibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : @@ -23692,7 +25405,7 @@ var ts; var elements = []; for (var _i = 0, _a = bindingPattern.elements; _i < _a.length; _i++) { var element = _a[_i]; - if (element.kind !== 176 /* OmittedExpression */) { + if (element.kind !== 178 /* OmittedExpression */) { elements.push(element); } } @@ -23762,7 +25475,7 @@ var ts; var type = getTypeAnnotationFromAccessor(node); if (!type) { // couldn't get type for the first accessor, try the another one - var anotherAccessor = node.kind === 137 /* GetAccessor */ ? accessors.setAccessor : accessors.getAccessor; + var anotherAccessor = node.kind === 138 /* GetAccessor */ ? accessors.setAccessor : accessors.getAccessor; type = getTypeAnnotationFromAccessor(anotherAccessor); if (type) { accessorWithTypeAnnotation = anotherAccessor; @@ -23775,7 +25488,7 @@ var ts; } function getTypeAnnotationFromAccessor(accessor) { if (accessor) { - return accessor.kind === 137 /* GetAccessor */ + return accessor.kind === 138 /* GetAccessor */ ? accessor.type // Getter - return type : accessor.parameters.length > 0 ? accessor.parameters[0].type // Setter parameter type @@ -23784,7 +25497,7 @@ var ts; } function getAccessorDeclarationTypeVisibilityError(symbolAccesibilityResult) { var diagnosticMessage; - if (accessorWithTypeAnnotation.kind === 138 /* SetAccessor */) { + if (accessorWithTypeAnnotation.kind === 139 /* SetAccessor */) { // Setters have to have type named and cannot infer it so, the type should always be named if (accessorWithTypeAnnotation.parent.flags & 128 /* Static */) { diagnosticMessage = symbolAccesibilityResult.errorModuleName ? @@ -23834,17 +25547,17 @@ var ts; // so no need to verify if the declaration is visible if (!resolver.isImplementationOfOverload(node)) { emitJsDocComments(node); - if (node.kind === 201 /* FunctionDeclaration */) { + if (node.kind === 203 /* FunctionDeclaration */) { emitModuleElementDeclarationFlags(node); } - else if (node.kind === 135 /* MethodDeclaration */) { + else if (node.kind === 136 /* MethodDeclaration */) { emitClassMemberDeclarationFlags(node); } - if (node.kind === 201 /* FunctionDeclaration */) { + if (node.kind === 203 /* FunctionDeclaration */) { write("function "); writeTextOfNode(currentSourceFile, node.name); } - else if (node.kind === 136 /* Constructor */) { + else if (node.kind === 137 /* Constructor */) { write("constructor"); } else { @@ -23862,11 +25575,11 @@ var ts; } function emitSignatureDeclaration(node) { // Construct signature or constructor type write new Signature - if (node.kind === 140 /* ConstructSignature */ || node.kind === 144 /* ConstructorType */) { + if (node.kind === 141 /* ConstructSignature */ || node.kind === 146 /* ConstructorType */) { write("new "); } emitTypeParameters(node.typeParameters); - if (node.kind === 141 /* IndexSignature */) { + if (node.kind === 142 /* IndexSignature */) { write("["); } else { @@ -23876,22 +25589,22 @@ var ts; enclosingDeclaration = node; // Parameters emitCommaList(node.parameters, emitParameterDeclaration); - if (node.kind === 141 /* IndexSignature */) { + if (node.kind === 142 /* IndexSignature */) { write("]"); } else { write(")"); } // If this is not a constructor and is not private, emit the return type - var isFunctionTypeOrConstructorType = node.kind === 143 /* FunctionType */ || node.kind === 144 /* ConstructorType */; - if (isFunctionTypeOrConstructorType || node.parent.kind === 146 /* TypeLiteral */) { + var isFunctionTypeOrConstructorType = node.kind === 145 /* FunctionType */ || node.kind === 146 /* ConstructorType */; + if (isFunctionTypeOrConstructorType || node.parent.kind === 148 /* TypeLiteral */) { // Emit type literal signature return type only if specified if (node.type) { write(isFunctionTypeOrConstructorType ? " => " : ": "); emitType(node.type); } } - else if (node.kind !== 136 /* Constructor */ && !(node.flags & 32 /* Private */)) { + else if (node.kind !== 137 /* Constructor */ && !(node.flags & 32 /* Private */)) { writeReturnTypeAtSignature(node, getReturnTypeVisibilityError); } enclosingDeclaration = prevEnclosingDeclaration; @@ -23902,26 +25615,26 @@ var ts; function getReturnTypeVisibilityError(symbolAccesibilityResult) { var diagnosticMessage; switch (node.kind) { - case 140 /* ConstructSignature */: + case 141 /* ConstructSignature */: // Interfaces cannot have return types that cannot be named diagnosticMessage = symbolAccesibilityResult.errorModuleName ? ts.Diagnostics.Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0; break; - case 139 /* CallSignature */: + case 140 /* CallSignature */: // Interfaces cannot have return types that cannot be named diagnosticMessage = symbolAccesibilityResult.errorModuleName ? ts.Diagnostics.Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0; break; - case 141 /* IndexSignature */: + case 142 /* IndexSignature */: // Interfaces cannot have return types that cannot be named diagnosticMessage = symbolAccesibilityResult.errorModuleName ? ts.Diagnostics.Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0; break; - case 135 /* MethodDeclaration */: - case 134 /* MethodSignature */: + case 136 /* MethodDeclaration */: + case 135 /* MethodSignature */: if (node.flags & 128 /* Static */) { diagnosticMessage = symbolAccesibilityResult.errorModuleName ? symbolAccesibilityResult.accessibility === 2 /* CannotBeNamed */ ? @@ -23929,7 +25642,7 @@ var ts; ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0; } - else if (node.parent.kind === 202 /* ClassDeclaration */) { + else if (node.parent.kind === 204 /* ClassDeclaration */) { diagnosticMessage = symbolAccesibilityResult.errorModuleName ? symbolAccesibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : @@ -23943,7 +25656,7 @@ var ts; ts.Diagnostics.Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0; } break; - case 201 /* FunctionDeclaration */: + case 203 /* FunctionDeclaration */: diagnosticMessage = symbolAccesibilityResult.errorModuleName ? symbolAccesibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : @@ -23978,9 +25691,9 @@ var ts; write("?"); } decreaseIndent(); - if (node.parent.kind === 143 /* FunctionType */ || - node.parent.kind === 144 /* ConstructorType */ || - node.parent.parent.kind === 146 /* TypeLiteral */) { + if (node.parent.kind === 145 /* FunctionType */ || + node.parent.kind === 146 /* ConstructorType */ || + node.parent.parent.kind === 148 /* TypeLiteral */) { emitTypeOfVariableDeclarationFromTypeLiteral(node); } else if (!(node.parent.flags & 32 /* Private */)) { @@ -23996,24 +25709,24 @@ var ts; } function getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccesibilityResult) { switch (node.parent.kind) { - case 136 /* Constructor */: + case 137 /* Constructor */: return symbolAccesibilityResult.errorModuleName ? symbolAccesibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1; - case 140 /* ConstructSignature */: + case 141 /* ConstructSignature */: // Interfaces cannot have parameter types that cannot be named return symbolAccesibilityResult.errorModuleName ? ts.Diagnostics.Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1; - case 139 /* CallSignature */: + case 140 /* CallSignature */: // Interfaces cannot have parameter types that cannot be named return symbolAccesibilityResult.errorModuleName ? ts.Diagnostics.Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1; - case 135 /* MethodDeclaration */: - case 134 /* MethodSignature */: + case 136 /* MethodDeclaration */: + case 135 /* MethodSignature */: if (node.parent.flags & 128 /* Static */) { return symbolAccesibilityResult.errorModuleName ? symbolAccesibilityResult.accessibility === 2 /* CannotBeNamed */ ? @@ -24021,7 +25734,7 @@ var ts; ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1; } - else if (node.parent.parent.kind === 202 /* ClassDeclaration */) { + else if (node.parent.parent.kind === 204 /* ClassDeclaration */) { return symbolAccesibilityResult.errorModuleName ? symbolAccesibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : @@ -24034,7 +25747,7 @@ var ts; ts.Diagnostics.Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1; } - case 201 /* FunctionDeclaration */: + case 203 /* FunctionDeclaration */: return symbolAccesibilityResult.errorModuleName ? symbolAccesibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : @@ -24046,12 +25759,12 @@ var ts; } function emitBindingPattern(bindingPattern) { // We have to explicitly emit square bracket and bracket because these tokens are not store inside the node. - if (bindingPattern.kind === 151 /* ObjectBindingPattern */) { + if (bindingPattern.kind === 153 /* ObjectBindingPattern */) { write("{"); emitCommaList(bindingPattern.elements, emitBindingElement); write("}"); } - else if (bindingPattern.kind === 152 /* ArrayBindingPattern */) { + else if (bindingPattern.kind === 154 /* ArrayBindingPattern */) { write("["); var elements = bindingPattern.elements; emitCommaList(elements, emitBindingElement); @@ -24070,7 +25783,7 @@ var ts; typeName: bindingElement.name } : undefined; } - if (bindingElement.kind === 176 /* OmittedExpression */) { + if (bindingElement.kind === 178 /* OmittedExpression */) { // If bindingElement is an omittedExpression (i.e. containing elision), // we will emit blank space (although this may differ from users' original code, // it allows emitSeparatedList to write separator appropriately) @@ -24079,7 +25792,7 @@ var ts; // emit : function foo([ , x, , ]) {} write(" "); } - else if (bindingElement.kind === 153 /* BindingElement */) { + else if (bindingElement.kind === 155 /* BindingElement */) { if (bindingElement.propertyName) { // bindingElement has propertyName property in the following case: // { y: [a,b,c] ...} -> bindingPattern will have a property called propertyName for "y" @@ -24120,40 +25833,40 @@ var ts; } function emitNode(node) { switch (node.kind) { - case 201 /* FunctionDeclaration */: - case 206 /* ModuleDeclaration */: - case 209 /* ImportEqualsDeclaration */: - case 203 /* InterfaceDeclaration */: - case 202 /* ClassDeclaration */: - case 204 /* TypeAliasDeclaration */: - case 205 /* EnumDeclaration */: + case 203 /* FunctionDeclaration */: + case 208 /* ModuleDeclaration */: + case 211 /* ImportEqualsDeclaration */: + case 205 /* InterfaceDeclaration */: + case 204 /* ClassDeclaration */: + case 206 /* TypeAliasDeclaration */: + case 207 /* EnumDeclaration */: return emitModuleElement(node, isModuleElementVisible(node)); - case 181 /* VariableStatement */: + case 183 /* VariableStatement */: return emitModuleElement(node, isVariableStatementVisible(node)); - case 210 /* ImportDeclaration */: + case 212 /* ImportDeclaration */: // Import declaration without import clause is visible, otherwise it is not visible return emitModuleElement(node, !node.importClause); - case 216 /* ExportDeclaration */: + case 218 /* ExportDeclaration */: return emitExportDeclaration(node); - case 136 /* Constructor */: - case 135 /* MethodDeclaration */: - case 134 /* MethodSignature */: + case 137 /* Constructor */: + case 136 /* MethodDeclaration */: + case 135 /* MethodSignature */: return writeFunctionDeclaration(node); - case 140 /* ConstructSignature */: - case 139 /* CallSignature */: - case 141 /* IndexSignature */: + case 141 /* ConstructSignature */: + case 140 /* CallSignature */: + case 142 /* IndexSignature */: return emitSignatureDeclarationWithJsDocComments(node); - case 137 /* GetAccessor */: - case 138 /* SetAccessor */: + case 138 /* GetAccessor */: + case 139 /* SetAccessor */: return emitAccessorDeclaration(node); - case 133 /* PropertyDeclaration */: - case 132 /* PropertySignature */: + case 134 /* PropertyDeclaration */: + case 133 /* PropertySignature */: return emitPropertyDeclaration(node); - case 227 /* EnumMember */: + case 229 /* EnumMember */: return emitEnumMemberDeclaration(node); - case 215 /* ExportAssignment */: + case 217 /* ExportAssignment */: return emitExportAssignment(node); - case 228 /* SourceFile */: + case 230 /* SourceFile */: return emitSourceFile(node); } } @@ -24214,7 +25927,7 @@ var ts; // 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) { // emit output for the __extends helper function - var extendsHelper = "\nvar __extends = (this && this.__extends) || function (d, b) {\n for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];\n function __() { this.constructor = d; }\n __.prototype = b.prototype;\n d.prototype = new __();\n};"; + var extendsHelper = "\nvar __extends = (this && this.__extends) || function (d, b) {\n for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n};"; // emit output for the __decorate helper function var decorateHelper = "\nvar __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") return Reflect.decorate(decorators, target, key, desc);\n switch (arguments.length) {\n case 2: return decorators.reduceRight(function(o, d) { return (d && d(o)) || o; }, target);\n case 3: return decorators.reduceRight(function(o, d) { return (d && d(target, key)), void 0; }, void 0);\n case 4: return decorators.reduceRight(function(o, d) { return (d && d(target, key, o)) || o; }, desc);\n }\n};"; // emit output for the __metadata helper function @@ -24290,7 +26003,6 @@ var ts; var exportFunctionForFile; var generatedNameSet = {}; var nodeToGeneratedName = []; - var blockScopedVariableToGeneratedName; var computedPropertyNamesToGeneratedNames; var extendsEmitted = false; var decorateEmitted = false; @@ -24370,9 +26082,9 @@ var ts; tempFlags++; // Skip over 'i' and 'n' if (count !== 8 && count !== 13) { - var name_15 = count < 26 ? "_" + String.fromCharCode(97 /* a */ + count) : "_" + (count - 26); - if (isUniqueName(name_15)) { - return name_15; + var name_17 = count < 26 ? "_" + String.fromCharCode(97 /* a */ + count) : "_" + (count - 26); + if (isUniqueName(name_17)) { + return name_17; } } } @@ -24395,73 +26107,40 @@ var ts; i++; } } - function assignGeneratedName(node, name) { - nodeToGeneratedName[ts.getNodeId(node)] = ts.unescapeIdentifier(name); - } - function generateNameForFunctionOrClassDeclaration(node) { - if (!node.name) { - assignGeneratedName(node, makeUniqueName("default")); - } - } function generateNameForModuleOrEnum(node) { - if (node.name.kind === 65 /* Identifier */) { - var name_16 = node.name.text; - // Use module/enum name itself if it is unique, otherwise make a unique variation - assignGeneratedName(node, isUniqueLocalName(name_16, node) ? name_16 : makeUniqueName(name_16)); - } + var name = node.name.text; + // Use module/enum name itself if it is unique, otherwise make a unique variation + return isUniqueLocalName(name, node) ? name : makeUniqueName(name); } function generateNameForImportOrExportDeclaration(node) { var expr = ts.getExternalModuleName(node); var baseName = expr.kind === 8 /* StringLiteral */ ? ts.escapeIdentifier(ts.makeIdentifierFromModuleName(expr.text)) : "module"; - assignGeneratedName(node, makeUniqueName(baseName)); + return makeUniqueName(baseName); } - function generateNameForImportDeclaration(node) { - if (node.importClause) { - generateNameForImportOrExportDeclaration(node); - } - } - function generateNameForExportDeclaration(node) { - if (node.moduleSpecifier) { - generateNameForImportOrExportDeclaration(node); - } - } - function generateNameForExportAssignment(node) { - if (node.expression && node.expression.kind !== 65 /* Identifier */) { - assignGeneratedName(node, makeUniqueName("default")); - } + function generateNameForExportDefault() { + return makeUniqueName("default"); } function generateNameForNode(node) { switch (node.kind) { - case 201 /* FunctionDeclaration */: - case 202 /* ClassDeclaration */: - case 175 /* ClassExpression */: - generateNameForFunctionOrClassDeclaration(node); - break; - case 206 /* ModuleDeclaration */: - generateNameForModuleOrEnum(node); - generateNameForNode(node.body); - break; - case 205 /* EnumDeclaration */: - generateNameForModuleOrEnum(node); - break; - case 210 /* ImportDeclaration */: - generateNameForImportDeclaration(node); - break; - case 216 /* ExportDeclaration */: - generateNameForExportDeclaration(node); - break; - case 215 /* ExportAssignment */: - generateNameForExportAssignment(node); - break; + case 65 /* Identifier */: + return makeUniqueName(node.text); + case 208 /* ModuleDeclaration */: + case 207 /* EnumDeclaration */: + return generateNameForModuleOrEnum(node); + case 212 /* ImportDeclaration */: + case 218 /* ExportDeclaration */: + return generateNameForImportOrExportDeclaration(node); + case 203 /* FunctionDeclaration */: + case 204 /* ClassDeclaration */: + case 177 /* ClassExpression */: + case 217 /* ExportAssignment */: + return generateNameForExportDefault(); } } function getGeneratedNameForNode(node) { - var nodeId = ts.getNodeId(node); - if (!nodeToGeneratedName[nodeId]) { - generateNameForNode(node); - } - return nodeToGeneratedName[nodeId]; + var id = ts.getNodeId(node); + return nodeToGeneratedName[id] || (nodeToGeneratedName[id] = ts.unescapeIdentifier(generateNameForNode(node))); } function initializeEmitterWithSourceMaps() { var sourceMapDir; // The directory in which sourcemap will be @@ -24490,7 +26169,7 @@ var ts; } var prevEncodedEmittedColumn = lastEncodedSourceMapSpan.emittedColumn; // Line/Comma delimiters - if (lastEncodedSourceMapSpan.emittedLine == lastRecordedSourceMapSpan.emittedLine) { + if (lastEncodedSourceMapSpan.emittedLine === lastRecordedSourceMapSpan.emittedLine) { // Emit comma to separate the entry if (sourceMapData.sourceMapMappings) { sourceMapData.sourceMapMappings += ","; @@ -24559,8 +26238,8 @@ var ts; var emittedColumn = writer.getColumn(); // If this location wasn't recorded or the location in source is going backwards, record the span if (!lastRecordedSourceMapSpan || - lastRecordedSourceMapSpan.emittedLine != emittedLine || - lastRecordedSourceMapSpan.emittedColumn != emittedColumn || + lastRecordedSourceMapSpan.emittedLine !== emittedLine || + lastRecordedSourceMapSpan.emittedColumn !== emittedColumn || (lastRecordedSourceMapSpan.sourceIndex === sourceMapSourceIndex && (lastRecordedSourceMapSpan.sourceLine > sourceLinePos.line || (lastRecordedSourceMapSpan.sourceLine === sourceLinePos.line && lastRecordedSourceMapSpan.sourceColumn > sourceLinePos.character)))) { @@ -24626,8 +26305,8 @@ var ts; // Child scopes are always shown with a dot (even if they have no name), // unless it is a computed property. Then it is shown with brackets, // but the brackets are included in the name. - var name_17 = node.name; - if (!name_17 || name_17.kind !== 128 /* ComputedPropertyName */) { + var name_18 = node.name; + if (!name_18 || name_18.kind !== 129 /* ComputedPropertyName */) { scopeName = "." + scopeName; } scopeName = sourceMapData.sourceMapNames[parentIndex] + scopeName; @@ -24645,21 +26324,21 @@ var ts; // The scope was already given a name use it recordScopeNameStart(scopeName); } - else if (node.kind === 201 /* FunctionDeclaration */ || - node.kind === 163 /* FunctionExpression */ || - node.kind === 135 /* MethodDeclaration */ || - node.kind === 134 /* MethodSignature */ || - node.kind === 137 /* GetAccessor */ || - node.kind === 138 /* SetAccessor */ || - node.kind === 206 /* ModuleDeclaration */ || - node.kind === 202 /* ClassDeclaration */ || - node.kind === 205 /* EnumDeclaration */) { + else if (node.kind === 203 /* FunctionDeclaration */ || + node.kind === 165 /* FunctionExpression */ || + node.kind === 136 /* MethodDeclaration */ || + node.kind === 135 /* MethodSignature */ || + node.kind === 138 /* GetAccessor */ || + node.kind === 139 /* SetAccessor */ || + node.kind === 208 /* ModuleDeclaration */ || + node.kind === 204 /* ClassDeclaration */ || + node.kind === 207 /* EnumDeclaration */) { // Declaration and has associated name use it if (node.name) { - var name_18 = node.name; + var name_19 = node.name; // For computed property names, the text will include the brackets - scopeName = name_18.kind === 128 /* ComputedPropertyName */ - ? ts.getTextOfNode(name_18) + scopeName = name_19.kind === 129 /* ComputedPropertyName */ + ? ts.getTextOfNode(name_19) : node.name.text; } recordScopeNameStart(scopeName); @@ -24763,19 +26442,19 @@ var ts; else { sourceMapDir = ts.getDirectoryPath(ts.normalizePath(jsFilePath)); } - function emitNodeWithSourceMap(node, allowGeneratedIdentifiers) { + function emitNodeWithSourceMap(node) { if (node) { if (ts.nodeIsSynthesized(node)) { - return emitNodeWithoutSourceMap(node, false); + return emitNodeWithoutSourceMap(node); } - if (node.kind != 228 /* SourceFile */) { + if (node.kind !== 230 /* SourceFile */) { recordEmitNodeStartSpan(node); - emitNodeWithoutSourceMap(node, allowGeneratedIdentifiers); + emitNodeWithoutSourceMap(node); recordEmitNodeEndSpan(node); } else { recordNewSourceFileStart(node); - emitNodeWithoutSourceMap(node, false); + emitNodeWithoutSourceMap(node); } } } @@ -25031,10 +26710,10 @@ var ts; write("("); emit(tempVariable); // Now we emit the expressions - if (node.template.kind === 172 /* TemplateExpression */) { + if (node.template.kind === 174 /* TemplateExpression */) { ts.forEach(node.template.templateSpans, function (templateSpan) { write(", "); - var needsParens = templateSpan.expression.kind === 170 /* BinaryExpression */ + var needsParens = templateSpan.expression.kind === 172 /* BinaryExpression */ && templateSpan.expression.operatorToken.kind === 23 /* CommaToken */; emitParenthesizedIf(templateSpan.expression, needsParens); }); @@ -25069,7 +26748,7 @@ var ts; // ("abc" + 1) << (2 + "") // rather than // "abc" + (1 << 2) + "" - var needsParens = templateSpan.expression.kind !== 162 /* ParenthesizedExpression */ + var needsParens = templateSpan.expression.kind !== 164 /* ParenthesizedExpression */ && comparePrecedenceToBinaryPlus(templateSpan.expression) !== 1 /* GreaterThan */; if (i > 0 || headEmitted) { // If this is the first span and the head was not emitted, then this templateSpan's @@ -25111,11 +26790,11 @@ var ts; } function templateNeedsParens(template, parent) { switch (parent.kind) { - case 158 /* CallExpression */: - case 159 /* NewExpression */: + case 160 /* CallExpression */: + case 161 /* NewExpression */: return parent.expression === template; - case 160 /* TaggedTemplateExpression */: - case 162 /* ParenthesizedExpression */: + case 162 /* TaggedTemplateExpression */: + case 164 /* ParenthesizedExpression */: return false; default: return comparePrecedenceToBinaryPlus(parent) !== -1 /* LessThan */; @@ -25136,7 +26815,7 @@ var ts; // TODO (drosen): Note that we need to account for the upcoming 'yield' and // spread ('...') unary operators that are anticipated for ES6. switch (expression.kind) { - case 170 /* BinaryExpression */: + case 172 /* BinaryExpression */: switch (expression.operatorToken.kind) { case 35 /* AsteriskToken */: case 36 /* SlashToken */: @@ -25148,8 +26827,8 @@ var ts; default: return -1 /* LessThan */; } - case 173 /* YieldExpression */: - case 171 /* ConditionalExpression */: + case 175 /* YieldExpression */: + case 173 /* ConditionalExpression */: return -1 /* LessThan */; default: return 1 /* GreaterThan */; @@ -25164,11 +26843,11 @@ var ts; // In a sense, it does not actually emit identifiers as much as it declares a name for a specific property. // For example, this is utilized when feeding in a result to Object.defineProperty. function emitExpressionForPropertyName(node) { - ts.Debug.assert(node.kind !== 153 /* BindingElement */); + ts.Debug.assert(node.kind !== 155 /* BindingElement */); if (node.kind === 8 /* StringLiteral */) { emitLiteral(node); } - else if (node.kind === 128 /* ComputedPropertyName */) { + else if (node.kind === 129 /* ComputedPropertyName */) { // if this is a decorated computed property, we will need to capture the result // of the property expression so that we can apply decorators later. This is to ensure // we don't introduce unintended side effects: @@ -25209,75 +26888,126 @@ var ts; write("\""); } } - function isNotExpressionIdentifier(node) { + function isExpressionIdentifier(node) { var parent = node.parent; switch (parent.kind) { - case 130 /* Parameter */: - case 199 /* VariableDeclaration */: - case 153 /* BindingElement */: - case 133 /* PropertyDeclaration */: - case 132 /* PropertySignature */: - case 225 /* PropertyAssignment */: - case 226 /* ShorthandPropertyAssignment */: - case 227 /* EnumMember */: - case 135 /* MethodDeclaration */: - case 134 /* MethodSignature */: - case 201 /* FunctionDeclaration */: - case 137 /* GetAccessor */: - case 138 /* SetAccessor */: - case 163 /* FunctionExpression */: - case 202 /* ClassDeclaration */: - case 203 /* InterfaceDeclaration */: - case 205 /* EnumDeclaration */: - case 206 /* ModuleDeclaration */: - case 209 /* ImportEqualsDeclaration */: - case 211 /* ImportClause */: - case 212 /* NamespaceImport */: - return parent.name === node; - case 214 /* ImportSpecifier */: - case 218 /* ExportSpecifier */: - return parent.name === node || parent.propertyName === node; - case 191 /* BreakStatement */: - case 190 /* ContinueStatement */: - case 215 /* ExportAssignment */: - return false; - case 195 /* LabeledStatement */: - return node.parent.label === node; + case 156 /* ArrayLiteralExpression */: + case 172 /* BinaryExpression */: + case 160 /* CallExpression */: + case 223 /* CaseClause */: + case 129 /* ComputedPropertyName */: + case 173 /* ConditionalExpression */: + case 132 /* Decorator */: + case 167 /* DeleteExpression */: + case 187 /* DoStatement */: + case 159 /* ElementAccessExpression */: + case 217 /* ExportAssignment */: + case 185 /* ExpressionStatement */: + case 179 /* ExpressionWithTypeArguments */: + case 189 /* ForStatement */: + case 190 /* ForInStatement */: + case 191 /* ForOfStatement */: + case 186 /* IfStatement */: + case 161 /* NewExpression */: + case 164 /* ParenthesizedExpression */: + case 171 /* PostfixUnaryExpression */: + case 170 /* PrefixUnaryExpression */: + case 194 /* ReturnStatement */: + case 228 /* ShorthandPropertyAssignment */: + case 176 /* SpreadElementExpression */: + case 196 /* SwitchStatement */: + case 162 /* TaggedTemplateExpression */: + case 180 /* TemplateSpan */: + case 198 /* ThrowStatement */: + case 163 /* TypeAssertionExpression */: + case 168 /* TypeOfExpression */: + case 169 /* VoidExpression */: + case 188 /* WhileStatement */: + case 195 /* WithStatement */: + case 175 /* YieldExpression */: + return true; + case 155 /* BindingElement */: + case 229 /* EnumMember */: + case 131 /* Parameter */: + case 227 /* PropertyAssignment */: + case 134 /* PropertyDeclaration */: + case 201 /* VariableDeclaration */: + return parent.initializer === node; + case 158 /* PropertyAccessExpression */: + return parent.expression === node; + case 166 /* ArrowFunction */: + case 165 /* FunctionExpression */: + return parent.body === node; + case 211 /* ImportEqualsDeclaration */: + return parent.moduleReference === node; + case 128 /* QualifiedName */: + return parent.left === node; } + return false; } function emitExpressionIdentifier(node) { - var substitution = resolver.getExpressionNameSubstitution(node, getGeneratedNameForNode); - if (substitution) { - write(substitution); + var container = resolver.getReferencedExportContainer(node); + if (container) { + if (container.kind === 230 /* SourceFile */) { + // Identifier references module export + if (languageVersion < 2 /* ES6 */ && compilerOptions.module !== 4 /* System */) { + write("exports."); + } + } + else { + // Identifier references namespace export + write(getGeneratedNameForNode(container)); + write("."); + } } - else { - writeTextOfNode(currentSourceFile, node); - } - } - function getGeneratedNameForIdentifier(node) { - if (ts.nodeIsSynthesized(node) || !blockScopedVariableToGeneratedName) { - return undefined; - } - var variableId = resolver.getBlockScopedVariableId(node); - if (variableId === undefined) { - return undefined; - } - return blockScopedVariableToGeneratedName[variableId]; - } - function emitIdentifier(node, allowGeneratedIdentifiers) { - if (allowGeneratedIdentifiers) { - var generatedName = getGeneratedNameForIdentifier(node); - if (generatedName) { - write(generatedName); + else if (languageVersion < 2 /* ES6 */) { + var declaration = resolver.getReferencedImportDeclaration(node); + if (declaration) { + if (declaration.kind === 213 /* ImportClause */) { + // Identifier references default import + write(getGeneratedNameForNode(declaration.parent)); + write(languageVersion === 0 /* ES3 */ ? '["default"]' : ".default"); + return; + } + else if (declaration.kind === 216 /* ImportSpecifier */) { + // Identifier references named import + write(getGeneratedNameForNode(declaration.parent.parent.parent)); + write("."); + writeTextOfNode(currentSourceFile, declaration.propertyName || declaration.name); + return; + } + } + declaration = resolver.getReferencedNestedRedeclaration(node); + if (declaration) { + write(getGeneratedNameForNode(declaration.name)); return; } } + writeTextOfNode(currentSourceFile, node); + } + function isNameOfNestedRedeclaration(node) { + if (languageVersion < 2 /* ES6 */) { + var parent_7 = node.parent; + switch (parent_7.kind) { + case 155 /* BindingElement */: + case 204 /* ClassDeclaration */: + case 207 /* EnumDeclaration */: + case 201 /* VariableDeclaration */: + return parent_7.name === node && resolver.isNestedRedeclaration(parent_7); + } + } + return false; + } + function emitIdentifier(node) { if (!node.parent) { write(node.text); } - else if (!isNotExpressionIdentifier(node)) { + else if (isExpressionIdentifier(node)) { emitExpressionIdentifier(node); } + else if (isNameOfNestedRedeclaration(node)) { + write(getGeneratedNameForNode(node)); + } else { writeTextOfNode(currentSourceFile, node); } @@ -25318,7 +27048,7 @@ var ts; } function emitBindingElement(node) { if (node.propertyName) { - emit(node.propertyName, false); + emit(node.propertyName); write(": "); } if (node.dotDotDotToken) { @@ -25349,41 +27079,41 @@ var ts; function needsParenthesisForPropertyAccessOrInvocation(node) { switch (node.kind) { case 65 /* Identifier */: - case 154 /* ArrayLiteralExpression */: - case 156 /* PropertyAccessExpression */: - case 157 /* ElementAccessExpression */: - case 158 /* CallExpression */: - case 162 /* ParenthesizedExpression */: + case 156 /* ArrayLiteralExpression */: + case 158 /* PropertyAccessExpression */: + case 159 /* ElementAccessExpression */: + case 160 /* CallExpression */: + case 164 /* ParenthesizedExpression */: // This list is not exhaustive and only includes those cases that are relevant // to the check in emitArrayLiteral. More cases can be added as needed. return false; } return true; } - function emitListWithSpread(elements, alwaysCopy, multiLine, trailingComma) { + function emitListWithSpread(elements, needsUniqueCopy, multiLine, trailingComma, useConcat) { var pos = 0; var group = 0; var length = elements.length; while (pos < length) { // Emit using the pattern .concat(, , ...) - if (group === 1) { + if (group === 1 && useConcat) { write(".concat("); } - else if (group > 1) { + else if (group > 0) { write(", "); } var e = elements[pos]; - if (e.kind === 174 /* SpreadElementExpression */) { + if (e.kind === 176 /* SpreadElementExpression */) { e = e.expression; emitParenthesizedIf(e, group === 0 && needsParenthesisForPropertyAccessOrInvocation(e)); pos++; - if (pos === length && group === 0 && alwaysCopy && e.kind !== 154 /* ArrayLiteralExpression */) { + if (pos === length && group === 0 && needsUniqueCopy && e.kind !== 156 /* ArrayLiteralExpression */) { write(".slice()"); } } else { var i = pos; - while (i < length && elements[i].kind !== 174 /* SpreadElementExpression */) { + while (i < length && elements[i].kind !== 176 /* SpreadElementExpression */) { i++; } write("["); @@ -25400,11 +27130,13 @@ var ts; group++; } if (group > 1) { - write(")"); + if (useConcat) { + write(")"); + } } } function isSpreadElementExpression(node) { - return node.kind === 174 /* SpreadElementExpression */; + return node.kind === 176 /* SpreadElementExpression */; } function emitArrayLiteral(node) { var elements = node.elements; @@ -25418,7 +27150,7 @@ var ts; } else { emitListWithSpread(elements, true, (node.flags & 512 /* MultiLine */) !== 0, - /*trailingComma*/ elements.hasTrailingComma); + /*trailingComma*/ elements.hasTrailingComma, true); } } function emitObjectLiteralBody(node, numElements) { @@ -25474,7 +27206,7 @@ var ts; writeComma(); var property = properties[i]; emitStart(property); - if (property.kind === 137 /* GetAccessor */ || property.kind === 138 /* SetAccessor */) { + if (property.kind === 138 /* GetAccessor */ || property.kind === 139 /* SetAccessor */) { // TODO (drosen): Reconcile with 'emitMemberFunctions'. var accessors = ts.getAllAccessorDeclarations(node.properties, property); if (property !== accessors.firstAccessor) { @@ -25526,13 +27258,13 @@ var ts; emitMemberAccessForPropertyName(property.name); emitEnd(property.name); write(" = "); - if (property.kind === 225 /* PropertyAssignment */) { + if (property.kind === 227 /* PropertyAssignment */) { emit(property.initializer); } - else if (property.kind === 226 /* ShorthandPropertyAssignment */) { + else if (property.kind === 228 /* ShorthandPropertyAssignment */) { emitExpressionIdentifier(property.name); } - else if (property.kind === 135 /* MethodDeclaration */) { + else if (property.kind === 136 /* MethodDeclaration */) { emitFunctionDeclaration(property); } else { @@ -25566,7 +27298,7 @@ var ts; // Everything until that point can be emitted as part of the initial object literal. var numInitialNonComputedProperties = numProperties; for (var i = 0, n = properties.length; i < n; i++) { - if (properties[i].name.kind === 128 /* ComputedPropertyName */) { + if (properties[i].name.kind === 129 /* ComputedPropertyName */) { numInitialNonComputedProperties = i; break; } @@ -25582,26 +27314,31 @@ var ts; emitObjectLiteralBody(node, properties.length); } function createBinaryExpression(left, operator, right, startsOnNewLine) { - var result = ts.createSynthesizedNode(170 /* BinaryExpression */, startsOnNewLine); + var result = ts.createSynthesizedNode(172 /* BinaryExpression */, startsOnNewLine); result.operatorToken = ts.createSynthesizedNode(operator); result.left = left; result.right = right; return result; } function createPropertyAccessExpression(expression, name) { - var result = ts.createSynthesizedNode(156 /* PropertyAccessExpression */); + var result = ts.createSynthesizedNode(158 /* PropertyAccessExpression */); result.expression = parenthesizeForAccess(expression); result.dotToken = ts.createSynthesizedNode(20 /* DotToken */); result.name = name; return result; } function createElementAccessExpression(expression, argumentExpression) { - var result = ts.createSynthesizedNode(157 /* ElementAccessExpression */); + var result = ts.createSynthesizedNode(159 /* ElementAccessExpression */); result.expression = parenthesizeForAccess(expression); result.argumentExpression = argumentExpression; return result; } function parenthesizeForAccess(expr) { + // When diagnosing whether the expression needs parentheses, the decision should be based + // on the innermost expression in a chain of nested type assertions. + while (expr.kind === 163 /* TypeAssertionExpression */) { + expr = expr.expression; + } // isLeftHandSideExpression is almost the correct criterion for when it is not necessary // to parenthesize the expression before a dot. The known exceptions are: // @@ -25610,10 +27347,12 @@ var ts; // NumberLiteral // 1.x -> not the same as (1).x // - if (ts.isLeftHandSideExpression(expr) && expr.kind !== 159 /* NewExpression */ && expr.kind !== 7 /* NumericLiteral */) { + if (ts.isLeftHandSideExpression(expr) && + expr.kind !== 161 /* NewExpression */ && + expr.kind !== 7 /* NumericLiteral */) { return expr; } - var node = ts.createSynthesizedNode(162 /* ParenthesizedExpression */); + var node = ts.createSynthesizedNode(164 /* ParenthesizedExpression */); node.expression = expr; return node; } @@ -25626,50 +27365,43 @@ var ts; if (languageVersion >= 2 /* ES6 */ && node.asteriskToken) { write("*"); } - emit(node.name, false); + emit(node.name); if (languageVersion < 2 /* ES6 */) { write(": function "); } emitSignatureAndBody(node); } function emitPropertyAssignment(node) { - emit(node.name, false); + emit(node.name); write(": "); emit(node.initializer); } + // Return true if identifier resolves to an exported member of a namespace + function isNamespaceExportReference(node) { + var container = resolver.getReferencedExportContainer(node); + return container && container.kind !== 230 /* SourceFile */; + } function emitShorthandPropertyAssignment(node) { - emit(node.name, false); - // If short-hand property has a prefix, then regardless of the target version, we will emit it as normal property assignment. For example: - // module m { - // export let y; - // } - // module m { - // export let obj = { y }; - // } - // The short-hand property in obj need to emit as such ... = { y : m.y } regardless of the TargetScript version - if (languageVersion < 2 /* ES6 */) { + // The name property of a short-hand property assignment is considered an expression position, so here + // we manually emit the identifier to avoid rewriting. + writeTextOfNode(currentSourceFile, node.name); + // If emitting pre-ES6 code, or if the name requires rewriting when resolved as an expression identifier, + // we emit a normal property assignment. For example: + // module m { + // export let y; + // } + // module m { + // let obj = { y }; + // } + // Here we need to emit obj = { y : m.y } regardless of the output target. + if (languageVersion < 2 /* ES6 */ || isNamespaceExportReference(node.name)) { // Emit identifier as an identifier write(": "); - var generatedName = getGeneratedNameForIdentifier(node.name); - if (generatedName) { - write(generatedName); - } - else { - // Even though this is stored as identifier treat it as an expression - // Short-hand, { x }, is equivalent of normal form { x: x } - emitExpressionIdentifier(node.name); - } - } - else if (resolver.getExpressionNameSubstitution(node.name, getGeneratedNameForNode)) { - // Emit identifier as an identifier - write(": "); - // Even though this is stored as identifier treat it as an expression - // Short-hand, { x }, is equivalent of normal form { x: x } - emitExpressionIdentifier(node.name); + emit(node.name); } } function tryEmitConstantValue(node) { - if (compilerOptions.separateCompilation) { + if (compilerOptions.isolatedModules) { // do not inline enum values in separate compilation mode return false; } @@ -25677,7 +27409,7 @@ var ts; if (constantValue !== undefined) { write(constantValue.toString()); if (!compilerOptions.removeComments) { - var propertyName = node.kind === 156 /* PropertyAccessExpression */ ? ts.declarationNameToString(node.name) : ts.getTextOfNode(node.argumentExpression); + var propertyName = node.kind === 158 /* PropertyAccessExpression */ ? ts.declarationNameToString(node.name) : ts.getTextOfNode(node.argumentExpression); write(" /* " + propertyName + " */"); } return true; @@ -25711,7 +27443,7 @@ var ts; var indentedBeforeDot = indentIfOnDifferentLines(node, node.expression, node.dotToken); write("."); var indentedAfterDot = indentIfOnDifferentLines(node, node.dotToken, node.name); - emit(node.name, false); + emit(node.name); decreaseIndentIf(indentedBeforeDot, indentedAfterDot); } function emitQualifiedName(node) { @@ -25729,10 +27461,10 @@ var ts; write("]"); } function hasSpreadElement(elements) { - return ts.forEach(elements, function (e) { return e.kind === 174 /* SpreadElementExpression */; }); + return ts.forEach(elements, function (e) { return e.kind === 176 /* SpreadElementExpression */; }); } function skipParentheses(node) { - while (node.kind === 162 /* ParenthesizedExpression */ || node.kind === 161 /* TypeAssertionExpression */) { + while (node.kind === 164 /* ParenthesizedExpression */ || node.kind === 163 /* TypeAssertionExpression */) { node = node.expression; } return node; @@ -25753,13 +27485,13 @@ var ts; function emitCallWithSpread(node) { var target; var expr = skipParentheses(node.expression); - if (expr.kind === 156 /* PropertyAccessExpression */) { + if (expr.kind === 158 /* PropertyAccessExpression */) { // Target will be emitted as "this" argument target = emitCallTarget(expr.expression); write("."); emit(expr.name); } - else if (expr.kind === 157 /* ElementAccessExpression */) { + else if (expr.kind === 159 /* ElementAccessExpression */) { // Target will be emitted as "this" argument target = emitCallTarget(expr.expression); write("["); @@ -25789,7 +27521,7 @@ var ts; write("void 0"); } write(", "); - emitListWithSpread(node.arguments, false, false, false); + emitListWithSpread(node.arguments, false, false, false, true); write(")"); } function emitCallExpression(node) { @@ -25804,7 +27536,7 @@ var ts; } else { emit(node.expression); - superCall = node.expression.kind === 156 /* PropertyAccessExpression */ && node.expression.expression.kind === 91 /* SuperKeyword */; + superCall = node.expression.kind === 158 /* PropertyAccessExpression */ && node.expression.expression.kind === 91 /* SuperKeyword */; } if (superCall && languageVersion < 2 /* ES6 */) { write(".call("); @@ -25823,11 +27555,40 @@ var ts; } function emitNewExpression(node) { write("new "); - emit(node.expression); - if (node.arguments) { + // Spread operator logic is supported in new expressions in ES5 using a combination + // of Function.prototype.bind() and Function.prototype.apply(). + // + // Example: + // + // var args = [1, 2, 3, 4, 5]; + // new Array(...args); + // + // is compiled into the following ES5: + // + // var args = [1, 2, 3, 4, 5]; + // new (Array.bind.apply(Array, [void 0].concat(args))); + // + // The 'thisArg' to 'bind' is ignored when invoking the result of 'bind' with 'new', + // Thus, we set it to undefined ('void 0'). + if (languageVersion === 1 /* ES5 */ && + node.arguments && + hasSpreadElement(node.arguments)) { write("("); - emitCommaList(node.arguments); - write(")"); + var target = emitCallTarget(node.expression); + write(".bind.apply("); + emit(target); + write(", [void 0].concat("); + emitListWithSpread(node.arguments, false, false, false, false); + write(")))"); + write("()"); + } + else { + emit(node.expression); + if (node.arguments) { + write("("); + emitCommaList(node.arguments); + write(")"); + } } } function emitTaggedTemplateExpression(node) { @@ -25841,12 +27602,15 @@ var ts; } } function emitParenExpression(node) { - if (!node.parent || node.parent.kind !== 164 /* ArrowFunction */) { - if (node.expression.kind === 161 /* TypeAssertionExpression */) { + // 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 (!ts.nodeIsSynthesized(node) && node.parent.kind !== 166 /* ArrowFunction */) { + if (node.expression.kind === 163 /* TypeAssertionExpression */) { var operand = node.expression.expression; // Make sure we consider all nested cast expressions, e.g.: // (-A).x; - while (operand.kind == 161 /* TypeAssertionExpression */) { + while (operand.kind === 163 /* TypeAssertionExpression */) { operand = operand.expression; } // We have an expression of the form: (SubExpr) @@ -25857,14 +27621,14 @@ var ts; // (typeof A).toString() should be emitted as (typeof A).toString() and not typeof A.toString() // new (A()) should be emitted as new (A()) and not new A() // (function foo() { })() should be emitted as an IIF (function foo(){})() and not declaration function foo(){} () - if (operand.kind !== 168 /* PrefixUnaryExpression */ && - operand.kind !== 167 /* VoidExpression */ && - operand.kind !== 166 /* TypeOfExpression */ && - operand.kind !== 165 /* DeleteExpression */ && - operand.kind !== 169 /* PostfixUnaryExpression */ && - operand.kind !== 159 /* NewExpression */ && - !(operand.kind === 158 /* CallExpression */ && node.parent.kind === 159 /* NewExpression */) && - !(operand.kind === 163 /* FunctionExpression */ && node.parent.kind === 158 /* CallExpression */)) { + if (operand.kind !== 170 /* PrefixUnaryExpression */ && + operand.kind !== 169 /* VoidExpression */ && + operand.kind !== 168 /* TypeOfExpression */ && + operand.kind !== 167 /* DeleteExpression */ && + operand.kind !== 171 /* PostfixUnaryExpression */ && + operand.kind !== 161 /* NewExpression */ && + !(operand.kind === 160 /* CallExpression */ && node.parent.kind === 161 /* NewExpression */) && + !(operand.kind === 165 /* FunctionExpression */ && node.parent.kind === 160 /* CallExpression */)) { emit(operand); return; } @@ -25893,7 +27657,7 @@ var ts; if (!isCurrentFileSystemExternalModule() || node.kind !== 65 /* Identifier */ || ts.nodeIsSynthesized(node)) { return false; } - var isVariableDeclarationOrBindingElement = node.parent && (node.parent.kind === 199 /* VariableDeclaration */ || node.parent.kind === 153 /* BindingElement */); + var isVariableDeclarationOrBindingElement = node.parent && (node.parent.kind === 201 /* VariableDeclaration */ || node.parent.kind === 155 /* BindingElement */); var targetDeclaration = isVariableDeclarationOrBindingElement ? node.parent : resolver.getReferencedValueDeclaration(node); @@ -25923,7 +27687,7 @@ var ts; // the resulting expression a prefix increment operation. And in the second, it will make the resulting // expression a prefix increment whose operand is a plus expression - (++(+x)) // The same is true of minus of course. - if (node.operand.kind === 168 /* PrefixUnaryExpression */) { + if (node.operand.kind === 170 /* PrefixUnaryExpression */) { var operand = node.operand; if (node.operator === 33 /* PlusToken */ && (operand.operator === 33 /* PlusToken */ || operand.operator === 38 /* PlusPlusToken */)) { write(" "); @@ -25979,10 +27743,10 @@ var ts; } var current = node; while (current) { - if (current.kind === 228 /* SourceFile */) { + if (current.kind === 230 /* SourceFile */) { return !isExported || ((ts.getCombinedNodeFlags(node) & 1 /* Export */) !== 0); } - else if (ts.isFunctionLike(current) || current.kind === 207 /* ModuleBlock */) { + else if (ts.isFunctionLike(current) || current.kind === 209 /* ModuleBlock */) { return false; } else { @@ -25992,8 +27756,8 @@ var ts; } function emitBinaryExpression(node) { if (languageVersion < 2 /* ES6 */ && node.operatorToken.kind === 53 /* EqualsToken */ && - (node.left.kind === 155 /* ObjectLiteralExpression */ || node.left.kind === 154 /* ArrayLiteralExpression */)) { - emitDestructuring(node, node.parent.kind === 183 /* ExpressionStatement */); + (node.left.kind === 157 /* ObjectLiteralExpression */ || node.left.kind === 156 /* ArrayLiteralExpression */)) { + emitDestructuring(node, node.parent.kind === 185 /* ExpressionStatement */); } else { var exportChanged = node.operatorToken.kind >= 53 /* FirstAssignment */ && @@ -26045,7 +27809,7 @@ var ts; } } function isSingleLineEmptyBlock(node) { - if (node && node.kind === 180 /* Block */) { + if (node && node.kind === 182 /* Block */) { var block = node; return block.statements.length === 0 && nodeEndIsOnSameLineAsNodeStart(block, block); } @@ -26060,12 +27824,12 @@ var ts; emitToken(14 /* OpenBraceToken */, node.pos); increaseIndent(); scopeEmitStart(node.parent); - if (node.kind === 207 /* ModuleBlock */) { - ts.Debug.assert(node.parent.kind === 206 /* ModuleDeclaration */); + if (node.kind === 209 /* ModuleBlock */) { + ts.Debug.assert(node.parent.kind === 208 /* ModuleDeclaration */); emitCaptureThisForNodeIfNecessary(node.parent); } emitLines(node.statements); - if (node.kind === 207 /* ModuleBlock */) { + if (node.kind === 209 /* ModuleBlock */) { emitTempDeclarations(true); } decreaseIndent(); @@ -26074,7 +27838,7 @@ var ts; scopeEmitEnd(); } function emitEmbeddedStatement(node) { - if (node.kind === 180 /* Block */) { + if (node.kind === 182 /* Block */) { write(" "); emit(node); } @@ -26086,7 +27850,7 @@ var ts; } } function emitExpressionStatement(node) { - emitParenthesizedIf(node.expression, node.expression.kind === 164 /* ArrowFunction */); + emitParenthesizedIf(node.expression, node.expression.kind === 166 /* ArrowFunction */); write(";"); } function emitIfStatement(node) { @@ -26099,7 +27863,7 @@ var ts; if (node.elseStatement) { writeLine(); emitToken(76 /* ElseKeyword */, node.thenStatement.end); - if (node.elseStatement.kind === 184 /* IfStatement */) { + if (node.elseStatement.kind === 186 /* IfStatement */) { write(" "); emit(node.elseStatement); } @@ -26111,7 +27875,7 @@ var ts; function emitDoStatement(node) { write("do"); emitEmbeddedStatement(node.statement); - if (node.statement.kind === 180 /* Block */) { + if (node.statement.kind === 182 /* Block */) { write(" "); } else { @@ -26127,9 +27891,10 @@ var ts; write(")"); emitEmbeddedStatement(node.statement); } - /* Returns true if start of variable declaration list was emitted. - * Return false if nothing was written - this can happen for source file level variable declarations - * in system modules - such variable declarations are hoisted. + /** + * Returns true if start of variable declaration list was emitted. + * Returns false if nothing was written - this can happen for source file level variable declarations + * in system modules where such variable declarations are hoisted. */ function tryEmitStartOfVariableDeclarationList(decl, startPos) { if (shouldHoistVariable(decl, true)) { @@ -26185,7 +27950,7 @@ var ts; var endPos = emitToken(82 /* ForKeyword */, node.pos); write(" "); endPos = emitToken(16 /* OpenParenToken */, endPos); - if (node.initializer && node.initializer.kind === 200 /* VariableDeclarationList */) { + if (node.initializer && node.initializer.kind === 202 /* VariableDeclarationList */) { var variableDeclarationList = node.initializer; var startIsEmitted = tryEmitStartOfVariableDeclarationList(variableDeclarationList, endPos); if (startIsEmitted) { @@ -26206,13 +27971,13 @@ var ts; emitEmbeddedStatement(node.statement); } function emitForInOrForOfStatement(node) { - if (languageVersion < 2 /* ES6 */ && node.kind === 189 /* ForOfStatement */) { + if (languageVersion < 2 /* ES6 */ && node.kind === 191 /* ForOfStatement */) { return emitDownLevelForOfStatement(node); } var endPos = emitToken(82 /* ForKeyword */, node.pos); write(" "); endPos = emitToken(16 /* OpenParenToken */, endPos); - if (node.initializer.kind === 200 /* VariableDeclarationList */) { + if (node.initializer.kind === 202 /* VariableDeclarationList */) { var variableDeclarationList = node.initializer; if (variableDeclarationList.declarations.length >= 1) { tryEmitStartOfVariableDeclarationList(variableDeclarationList, endPos); @@ -26222,7 +27987,7 @@ var ts; else { emit(node.initializer); } - if (node.kind === 188 /* ForInStatement */) { + if (node.kind === 190 /* ForInStatement */) { write(" in "); } else { @@ -26307,7 +28072,7 @@ var ts; // let v = _a[_i]; var rhsIterationValue = createElementAccessExpression(rhsReference, counter); emitStart(node.initializer); - if (node.initializer.kind === 200 /* VariableDeclarationList */) { + if (node.initializer.kind === 202 /* VariableDeclarationList */) { write("var "); var variableDeclarationList = node.initializer; if (variableDeclarationList.declarations.length > 0) { @@ -26337,7 +28102,7 @@ var ts; // Initializer is an expression. Emit the expression in the body, so that it's // evaluated on every iteration. var assignmentExpression = createBinaryExpression(node.initializer, 53 /* EqualsToken */, rhsIterationValue, false); - if (node.initializer.kind === 154 /* ArrayLiteralExpression */ || node.initializer.kind === 155 /* ObjectLiteralExpression */) { + if (node.initializer.kind === 156 /* ArrayLiteralExpression */ || node.initializer.kind === 157 /* ObjectLiteralExpression */) { // This is a destructuring pattern, so call emitDestructuring instead of emit. Calling emit will not work, because it will cause // the BinaryExpression to be passed in instead of the expression statement, which will cause emitDestructuring to crash. emitDestructuring(assignmentExpression, true, undefined); @@ -26348,7 +28113,7 @@ var ts; } emitEnd(node.initializer); write(";"); - if (node.statement.kind === 180 /* Block */) { + if (node.statement.kind === 182 /* Block */) { emitLines(node.statement.statements); } else { @@ -26360,7 +28125,7 @@ var ts; write("}"); } function emitBreakOrContinueStatement(node) { - emitToken(node.kind === 191 /* BreakStatement */ ? 66 /* BreakKeyword */ : 71 /* ContinueKeyword */, node.pos); + emitToken(node.kind === 193 /* BreakStatement */ ? 66 /* BreakKeyword */ : 71 /* ContinueKeyword */, node.pos); emitOptional(" ", node.label); write(";"); } @@ -26405,7 +28170,7 @@ var ts; ts.getLineOfLocalPosition(currentSourceFile, ts.skipTrivia(currentSourceFile.text, node2.pos)); } function emitCaseOrDefaultClause(node) { - if (node.kind === 221 /* CaseClause */) { + if (node.kind === 223 /* CaseClause */) { write("case "); emit(node.expression); write(":"); @@ -26460,7 +28225,7 @@ var ts; function getContainingModule(node) { do { node = node.parent; - } while (node && node.kind !== 206 /* ModuleDeclaration */); + } while (node && node.kind !== 208 /* ModuleDeclaration */); return node; } function emitContainingModuleName(node) { @@ -26485,7 +28250,7 @@ var ts; function createVoidZero() { var zero = ts.createSynthesizedNode(7 /* NumericLiteral */); zero.text = "0"; - var result = ts.createSynthesizedNode(167 /* VoidExpression */); + var result = ts.createSynthesizedNode(169 /* VoidExpression */); result.expression = zero; return result; } @@ -26561,15 +28326,15 @@ var ts; // Also temporary variables should be explicitly allocated for source level declarations when module target is system // because actual variable declarations are hoisted var canDefineTempVariablesInPlace = false; - if (root.kind === 199 /* VariableDeclaration */) { + if (root.kind === 201 /* VariableDeclaration */) { var isExported = ts.getCombinedNodeFlags(root) & 1 /* Export */; var isSourceLevelForSystemModuleKind = shouldHoistDeclarationInSystemJsModule(root); canDefineTempVariablesInPlace = !isExported && !isSourceLevelForSystemModuleKind; } - else if (root.kind === 130 /* Parameter */) { + else if (root.kind === 131 /* Parameter */) { canDefineTempVariablesInPlace = true; } - if (root.kind === 170 /* BinaryExpression */) { + if (root.kind === 172 /* BinaryExpression */) { emitAssignmentExpression(root); } else { @@ -26580,8 +28345,7 @@ var ts; if (emitCount++) { write(", "); } - renameNonTopLevelLetAndConst(name); - var isVariableDeclarationOrBindingElement = name.parent && (name.parent.kind === 199 /* VariableDeclaration */ || name.parent.kind === 153 /* BindingElement */); + var isVariableDeclarationOrBindingElement = name.parent && (name.parent.kind === 201 /* VariableDeclaration */ || name.parent.kind === 155 /* BindingElement */); var exportChanged = isNameOfExportedSourceLevelDeclarationInSystemExternalModule(name); if (exportChanged) { write(exportFunctionForFile + "(\""); @@ -26616,14 +28380,14 @@ var ts; // we need to generate a temporary variable value = ensureIdentifier(value); // Return the expression 'value === void 0 ? defaultValue : value' - var equals = ts.createSynthesizedNode(170 /* BinaryExpression */); + var equals = ts.createSynthesizedNode(172 /* BinaryExpression */); equals.left = value; equals.operatorToken = ts.createSynthesizedNode(30 /* EqualsEqualsEqualsToken */); equals.right = createVoidZero(); return createConditionalExpression(equals, defaultValue, value); } function createConditionalExpression(condition, whenTrue, whenFalse) { - var cond = ts.createSynthesizedNode(171 /* ConditionalExpression */); + var cond = ts.createSynthesizedNode(173 /* ConditionalExpression */); cond.condition = condition; cond.questionToken = ts.createSynthesizedNode(50 /* QuestionToken */); cond.whenTrue = whenTrue; @@ -26637,13 +28401,17 @@ var ts; return node; } function createPropertyAccessForDestructuringProperty(object, propName) { - if (propName.kind !== 65 /* Identifier */) { - return createElementAccessExpression(object, propName); + // We create a synthetic copy of the identifier in order to avoid the rewriting that might + // otherwise occur when the identifier is emitted. + var syntheticName = ts.createSynthesizedNode(propName.kind); + syntheticName.text = propName.text; + if (syntheticName.kind !== 65 /* Identifier */) { + return createElementAccessExpression(object, syntheticName); } - return createPropertyAccessExpression(object, propName); + return createPropertyAccessExpression(object, syntheticName); } function createSliceCall(value, sliceIndex) { - var call = ts.createSynthesizedNode(158 /* CallExpression */); + var call = ts.createSynthesizedNode(160 /* CallExpression */); var sliceIdentifier = ts.createSynthesizedNode(65 /* Identifier */); sliceIdentifier.text = "slice"; call.expression = createPropertyAccessExpression(value, sliceIdentifier); @@ -26660,9 +28428,8 @@ var ts; } for (var _a = 0; _a < properties.length; _a++) { var p = properties[_a]; - if (p.kind === 225 /* PropertyAssignment */ || p.kind === 226 /* ShorthandPropertyAssignment */) { - // TODO(andersh): Computed property support - var propName = (p.name); + if (p.kind === 227 /* PropertyAssignment */ || p.kind === 228 /* ShorthandPropertyAssignment */) { + var propName = p.name; emitDestructuringAssignment(p.initializer || propName, createPropertyAccessForDestructuringProperty(value, propName)); } } @@ -26676,8 +28443,8 @@ var ts; } for (var i = 0; i < elements.length; i++) { var e = elements[i]; - if (e.kind !== 176 /* OmittedExpression */) { - if (e.kind !== 174 /* SpreadElementExpression */) { + if (e.kind !== 178 /* OmittedExpression */) { + if (e.kind !== 176 /* SpreadElementExpression */) { emitDestructuringAssignment(e, createElementAccessExpression(value, createNumericLiteral(i))); } else if (i === elements.length - 1) { @@ -26687,14 +28454,14 @@ var ts; } } function emitDestructuringAssignment(target, value) { - if (target.kind === 170 /* BinaryExpression */ && target.operatorToken.kind === 53 /* EqualsToken */) { + if (target.kind === 172 /* BinaryExpression */ && target.operatorToken.kind === 53 /* EqualsToken */) { value = createDefaultValueCheck(value, target.right); target = target.left; } - if (target.kind === 155 /* ObjectLiteralExpression */) { + if (target.kind === 157 /* ObjectLiteralExpression */) { emitObjectLiteralAssignment(target, value); } - else if (target.kind === 154 /* ArrayLiteralExpression */) { + else if (target.kind === 156 /* ArrayLiteralExpression */) { emitArrayLiteralAssignment(target, value); } else { @@ -26708,14 +28475,14 @@ var ts; emitDestructuringAssignment(target, value); } else { - if (root.parent.kind !== 162 /* ParenthesizedExpression */) { + if (root.parent.kind !== 164 /* ParenthesizedExpression */) { write("("); } value = ensureIdentifier(value); emitDestructuringAssignment(target, value); write(", "); emit(value); - if (root.parent.kind !== 162 /* ParenthesizedExpression */) { + if (root.parent.kind !== 164 /* ParenthesizedExpression */) { write(")"); } } @@ -26739,12 +28506,12 @@ var ts; } for (var i = 0; i < elements.length; i++) { var element = elements[i]; - if (pattern.kind === 151 /* ObjectBindingPattern */) { + if (pattern.kind === 153 /* ObjectBindingPattern */) { // Rewrite element to a declaration with an initializer that fetches property var propName = element.propertyName || element.name; emitBindingElement(element, createPropertyAccessForDestructuringProperty(value, propName)); } - else if (element.kind !== 176 /* OmittedExpression */) { + else if (element.kind !== 178 /* OmittedExpression */) { if (!element.dotDotDotToken) { // Rewrite element to a declaration that accesses array element at index i emitBindingElement(element, createElementAccessExpression(value, createNumericLiteral(i))); @@ -26771,7 +28538,6 @@ var ts; } } else { - renameNonTopLevelLetAndConst(node.name); var initializer = node.initializer; if (!initializer && languageVersion < 2 /* ES6 */) { // downlevel emit for non-initialized let bindings defined in loops @@ -26784,8 +28550,8 @@ var ts; (getCombinedFlagsForIdentifier(node.name) & 4096 /* Let */); // NOTE: default initialization should not be added to let bindings in for-in\for-of statements if (isUninitializedLet && - node.parent.parent.kind !== 188 /* ForInStatement */ && - node.parent.parent.kind !== 189 /* ForOfStatement */) { + node.parent.parent.kind !== 190 /* ForInStatement */ && + node.parent.parent.kind !== 191 /* ForOfStatement */) { initializer = createVoidZero(); } } @@ -26803,7 +28569,7 @@ var ts; } } function emitExportVariableAssignments(node) { - if (node.kind === 176 /* OmittedExpression */) { + if (node.kind === 178 /* OmittedExpression */) { return; } var name = node.name; @@ -26815,56 +28581,15 @@ var ts; } } function getCombinedFlagsForIdentifier(node) { - if (!node.parent || (node.parent.kind !== 199 /* VariableDeclaration */ && node.parent.kind !== 153 /* BindingElement */)) { + if (!node.parent || (node.parent.kind !== 201 /* VariableDeclaration */ && node.parent.kind !== 155 /* BindingElement */)) { return 0; } return ts.getCombinedNodeFlags(node.parent); } - function renameNonTopLevelLetAndConst(node) { - // do not rename if - // - language version is ES6+ - // - node is synthesized - // - node is not identifier (can happen when tree is malformed) - // - node is definitely not name of variable declaration. - // it still can be part of parameter declaration, this check will be done next - if (languageVersion >= 2 /* ES6 */ || - ts.nodeIsSynthesized(node) || - node.kind !== 65 /* Identifier */ || - (node.parent.kind !== 199 /* VariableDeclaration */ && node.parent.kind !== 153 /* BindingElement */)) { - return; - } - var combinedFlags = getCombinedFlagsForIdentifier(node); - if (((combinedFlags & 12288 /* BlockScoped */) === 0) || combinedFlags & 1 /* Export */) { - // do not rename exported or non-block scoped variables - return; - } - // here it is known that node is a block scoped variable - var list = ts.getAncestor(node, 200 /* VariableDeclarationList */); - if (list.parent.kind === 181 /* VariableStatement */) { - var isSourceFileLevelBinding = list.parent.parent.kind === 228 /* SourceFile */; - var isModuleLevelBinding = list.parent.parent.kind === 207 /* ModuleBlock */; - var isFunctionLevelBinding = list.parent.parent.kind === 180 /* Block */ && ts.isFunctionLike(list.parent.parent.parent); - if (isSourceFileLevelBinding || isModuleLevelBinding || isFunctionLevelBinding) { - return; - } - } - var blockScopeContainer = ts.getEnclosingBlockScopeContainer(node); - var parent = blockScopeContainer.kind === 228 /* SourceFile */ - ? blockScopeContainer - : blockScopeContainer.parent; - if (resolver.resolvesToSomeValue(parent, node.text)) { - var variableId = resolver.getBlockScopedVariableId(node); - if (!blockScopedVariableToGeneratedName) { - blockScopedVariableToGeneratedName = []; - } - var generatedName = makeUniqueName(node.text); - blockScopedVariableToGeneratedName[variableId] = generatedName; - } - } function isES6ExportedDeclaration(node) { return !!(node.flags & 1 /* Export */) && languageVersion >= 2 /* ES6 */ && - node.parent.kind === 228 /* SourceFile */; + node.parent.kind === 230 /* SourceFile */; } function emitVariableStatement(node) { var startIsEmitted = false; @@ -26892,15 +28617,35 @@ var ts; ts.forEach(node.declarationList.declarations, emitExportVariableAssignments); } } + function shouldEmitLeadingAndTrailingCommentsForVariableStatement(node) { + // If we're not exporting the variables, there's nothing special here. + // Always emit comments for these nodes. + if (!(node.flags & 1 /* Export */)) { + return true; + } + // If we are exporting, but it's a top-level ES6 module exports, + // we'll emit the declaration list verbatim, so emit comments too. + if (isES6ExportedDeclaration(node)) { + return true; + } + // Otherwise, only emit if we have at least one initializer present. + for (var _a = 0, _b = node.declarationList.declarations; _a < _b.length; _a++) { + var declaration = _b[_a]; + if (declaration.initializer) { + return true; + } + } + return false; + } function emitParameter(node) { if (languageVersion < 2 /* ES6 */) { if (ts.isBindingPattern(node.name)) { - var name_19 = createTempVariable(0 /* Auto */); + var name_20 = createTempVariable(0 /* Auto */); if (!tempParameters) { tempParameters = []; } - tempParameters.push(name_19); - emit(name_19); + tempParameters.push(name_20); + emit(name_20); } else { emit(node.name); @@ -26949,7 +28694,7 @@ var ts; } } function emitRestParameter(node) { - if (languageVersion < 2 /* ES6 */ && ts.hasRestParameters(node)) { + if (languageVersion < 2 /* ES6 */ && ts.hasRestParameter(node)) { var restIndex = node.parameters.length - 1; var restParam = node.parameters[restIndex]; // A rest parameter cannot have a binding pattern, so let's just ignore it if it does. @@ -26991,12 +28736,12 @@ var ts; } } function emitAccessor(node) { - write(node.kind === 137 /* GetAccessor */ ? "get " : "set "); - emit(node.name, false); + write(node.kind === 138 /* GetAccessor */ ? "get " : "set "); + emit(node.name); emitSignatureAndBody(node); } function shouldEmitAsArrowFunction(node) { - return node.kind === 164 /* ArrowFunction */ && languageVersion >= 2 /* ES6 */; + return node.kind === 166 /* ArrowFunction */ && languageVersion >= 2 /* ES6 */; } function emitDeclarationName(node) { if (node.name) { @@ -27007,11 +28752,11 @@ var ts; } } function shouldEmitFunctionName(node) { - if (node.kind === 163 /* FunctionExpression */) { + if (node.kind === 165 /* FunctionExpression */) { // Emit name if one is present return !!node.name; } - if (node.kind === 201 /* FunctionDeclaration */) { + if (node.kind === 203 /* FunctionDeclaration */) { // Emit name if one is present, or emit generated name in down-level case (for export default case) return !!node.name || languageVersion < 2 /* ES6 */; } @@ -27020,7 +28765,7 @@ var ts; if (ts.nodeIsMissing(node.body)) { return emitOnlyPinnedOrTripleSlashComments(node); } - if (node.kind !== 135 /* MethodDeclaration */ && node.kind !== 134 /* MethodSignature */) { + if (node.kind !== 136 /* MethodDeclaration */ && node.kind !== 135 /* MethodSignature */) { // Methods will emit the comments as part of emitting method declaration emitLeadingComments(node); } @@ -27043,10 +28788,10 @@ var ts; emitDeclarationName(node); } emitSignatureAndBody(node); - if (languageVersion < 2 /* ES6 */ && node.kind === 201 /* FunctionDeclaration */ && node.parent === currentSourceFile && node.name) { + if (languageVersion < 2 /* ES6 */ && node.kind === 203 /* FunctionDeclaration */ && node.parent === currentSourceFile && node.name) { emitExportMemberAssignments(node.name); } - if (node.kind !== 135 /* MethodDeclaration */ && node.kind !== 134 /* MethodSignature */) { + if (node.kind !== 136 /* MethodDeclaration */ && node.kind !== 135 /* MethodSignature */) { emitTrailingComments(node); } } @@ -27063,7 +28808,7 @@ var ts; write("("); if (node) { var parameters = node.parameters; - var omitCount = languageVersion < 2 /* ES6 */ && ts.hasRestParameters(node) ? 1 : 0; + var omitCount = languageVersion < 2 /* ES6 */ && ts.hasRestParameter(node) ? 1 : 0; emitList(parameters, 0, parameters.length - omitCount, false, false); } write(")"); @@ -27097,7 +28842,7 @@ var ts; // in that case. write(" { }"); } - else if (node.body.kind === 180 /* Block */) { + else if (node.body.kind === 182 /* Block */) { emitBlockFunctionBody(node, node.body); } else { @@ -27128,10 +28873,10 @@ var ts; write(" "); // Unwrap all type assertions. var current = body; - while (current.kind === 161 /* TypeAssertionExpression */) { + while (current.kind === 163 /* TypeAssertionExpression */) { current = current.expression; } - emitParenthesizedIf(body, current.kind === 155 /* ObjectLiteralExpression */); + emitParenthesizedIf(body, current.kind === 157 /* ObjectLiteralExpression */); } function emitDownLevelExpressionFunctionBody(node, body) { write(" {"); @@ -27207,9 +28952,9 @@ var ts; function findInitialSuperCall(ctor) { if (ctor.body) { var statement = ctor.body.statements[0]; - if (statement && statement.kind === 183 /* ExpressionStatement */) { + if (statement && statement.kind === 185 /* ExpressionStatement */) { var expr = statement.expression; - if (expr && expr.kind === 158 /* CallExpression */) { + if (expr && expr.kind === 160 /* CallExpression */) { var func = expr.expression; if (func && func.kind === 91 /* SuperKeyword */) { return statement; @@ -27241,7 +28986,7 @@ var ts; emitNodeWithoutSourceMap(memberName); write("]"); } - else if (memberName.kind === 128 /* ComputedPropertyName */) { + else if (memberName.kind === 129 /* ComputedPropertyName */) { emitComputedPropertyName(memberName); } else { @@ -27253,7 +28998,7 @@ var ts; var properties = []; for (var _a = 0, _b = node.members; _a < _b.length; _a++) { var member = _b[_a]; - if (member.kind === 133 /* PropertyDeclaration */ && isStatic === ((member.flags & 128 /* Static */) !== 0) && member.initializer) { + if (member.kind === 134 /* PropertyDeclaration */ && isStatic === ((member.flags & 128 /* Static */) !== 0) && member.initializer) { properties.push(member); } } @@ -27293,11 +29038,11 @@ var ts; } function emitMemberFunctionsForES5AndLower(node) { ts.forEach(node.members, function (member) { - if (member.kind === 179 /* SemicolonClassElement */) { + if (member.kind === 181 /* SemicolonClassElement */) { writeLine(); write(";"); } - else if (member.kind === 135 /* MethodDeclaration */ || node.kind === 134 /* MethodSignature */) { + else if (member.kind === 136 /* MethodDeclaration */ || node.kind === 135 /* MethodSignature */) { if (!member.body) { return emitOnlyPinnedOrTripleSlashComments(member); } @@ -27316,7 +29061,7 @@ var ts; write(";"); emitTrailingComments(member); } - else if (member.kind === 137 /* GetAccessor */ || member.kind === 138 /* SetAccessor */) { + else if (member.kind === 138 /* GetAccessor */ || member.kind === 139 /* SetAccessor */) { var accessors = ts.getAllAccessorDeclarations(node.members, member); if (member === accessors.firstAccessor) { writeLine(); @@ -27366,22 +29111,22 @@ var ts; function emitMemberFunctionsForES6AndHigher(node) { for (var _a = 0, _b = node.members; _a < _b.length; _a++) { var member = _b[_a]; - if ((member.kind === 135 /* MethodDeclaration */ || node.kind === 134 /* MethodSignature */) && !member.body) { + if ((member.kind === 136 /* MethodDeclaration */ || node.kind === 135 /* MethodSignature */) && !member.body) { emitOnlyPinnedOrTripleSlashComments(member); } - else if (member.kind === 135 /* MethodDeclaration */ || - member.kind === 137 /* GetAccessor */ || - member.kind === 138 /* SetAccessor */) { + else if (member.kind === 136 /* MethodDeclaration */ || + member.kind === 138 /* GetAccessor */ || + member.kind === 139 /* SetAccessor */) { writeLine(); emitLeadingComments(member); emitStart(member); if (member.flags & 128 /* Static */) { write("static "); } - if (member.kind === 137 /* GetAccessor */) { + if (member.kind === 138 /* GetAccessor */) { write("get "); } - else if (member.kind === 138 /* SetAccessor */) { + else if (member.kind === 139 /* SetAccessor */) { write("set "); } if (member.asteriskToken) { @@ -27392,7 +29137,7 @@ var ts; emitEnd(member); emitTrailingComments(member); } - else if (member.kind === 179 /* SemicolonClassElement */) { + else if (member.kind === 181 /* SemicolonClassElement */) { writeLine(); write(";"); } @@ -27417,11 +29162,11 @@ var ts; var hasInstancePropertyWithInitializer = false; // Emit the constructor overload pinned comments ts.forEach(node.members, function (member) { - if (member.kind === 136 /* Constructor */ && !member.body) { + if (member.kind === 137 /* Constructor */ && !member.body) { emitOnlyPinnedOrTripleSlashComments(member); } // Check if there is any non-static property assignment - if (member.kind === 133 /* PropertyDeclaration */ && member.initializer && (member.flags & 128 /* Static */) === 0) { + if (member.kind === 134 /* PropertyDeclaration */ && member.initializer && (member.flags & 128 /* Static */) === 0) { hasInstancePropertyWithInitializer = true; } }); @@ -27529,7 +29274,7 @@ var ts; } function emitClassLikeDeclarationForES6AndHigher(node) { var thisNodeIsDecorated = ts.nodeIsDecorated(node); - if (node.kind === 202 /* ClassDeclaration */) { + if (node.kind === 204 /* ClassDeclaration */) { if (thisNodeIsDecorated) { // To preserve the correct runtime semantics when decorators are applied to the class, // the emit needs to follow one of the following rules: @@ -27609,7 +29354,7 @@ var ts; // This keeps the expression as an expression, while ensuring that the static parts // of it have been initialized by the time it is used. var staticProperties = getInitializedProperties(node, true); - var isClassExpressionWithStaticProperties = staticProperties.length > 0 && node.kind === 175 /* ClassExpression */; + var isClassExpressionWithStaticProperties = staticProperties.length > 0 && node.kind === 177 /* ClassExpression */; var tempVariable; if (isClassExpressionWithStaticProperties) { tempVariable = createAndRecordTempVariable(0 /* Auto */); @@ -27693,7 +29438,7 @@ var ts; } } function emitClassLikeDeclarationBelowES6(node) { - if (node.kind === 202 /* ClassDeclaration */) { + if (node.kind === 204 /* ClassDeclaration */) { // source file level classes in system modules are hoisted so 'var's for them are already defined if (!shouldHoistDeclarationInSystemJsModule(node)) { write("var "); @@ -27752,11 +29497,11 @@ var ts; emit(baseTypeNode.expression); } write(")"); - if (node.kind === 202 /* ClassDeclaration */) { + if (node.kind === 204 /* ClassDeclaration */) { write(";"); } emitEnd(node); - if (node.kind === 202 /* ClassDeclaration */) { + if (node.kind === 204 /* ClassDeclaration */) { emitExportMemberAssignment(node); } if (languageVersion < 2 /* ES6 */ && node.parent === currentSourceFile && node.name) { @@ -27848,7 +29593,7 @@ var ts; else { decorators = member.decorators; // we only decorate the parameters here if this is a method - if (member.kind === 135 /* MethodDeclaration */) { + if (member.kind === 136 /* MethodDeclaration */) { functionLikeMember = member; } } @@ -27886,7 +29631,7 @@ var ts; // writeLine(); emitStart(member); - if (member.kind !== 133 /* PropertyDeclaration */) { + if (member.kind !== 134 /* PropertyDeclaration */) { write("Object.defineProperty("); emitStart(member.name); emitClassMemberPrefix(node, member); @@ -27916,7 +29661,7 @@ var ts; write(", "); emitExpressionForPropertyName(member.name); emitEnd(member.name); - if (member.kind !== 133 /* PropertyDeclaration */) { + if (member.kind !== 134 /* PropertyDeclaration */) { write(", Object.getOwnPropertyDescriptor("); emitStart(member.name); emitClassMemberPrefix(node, member); @@ -27958,10 +29703,10 @@ var ts; // The caller should have already tested whether the node has decorators and whether the emitDecoratorMetadata // compiler option is set. switch (node.kind) { - case 135 /* MethodDeclaration */: - case 137 /* GetAccessor */: - case 138 /* SetAccessor */: - case 133 /* PropertyDeclaration */: + case 136 /* MethodDeclaration */: + case 138 /* GetAccessor */: + case 139 /* SetAccessor */: + case 134 /* PropertyDeclaration */: return true; } return false; @@ -27971,7 +29716,7 @@ var ts; // The caller should have already tested whether the node has decorators and whether the emitDecoratorMetadata // compiler option is set. switch (node.kind) { - case 135 /* MethodDeclaration */: + case 136 /* MethodDeclaration */: return true; } return false; @@ -27981,9 +29726,9 @@ var ts; // The caller should have already tested whether the node has decorators and whether the emitDecoratorMetadata // compiler option is set. switch (node.kind) { - case 202 /* ClassDeclaration */: - case 135 /* MethodDeclaration */: - case 138 /* SetAccessor */: + case 204 /* ClassDeclaration */: + case 136 /* MethodDeclaration */: + case 139 /* SetAccessor */: return true; } return false; @@ -27994,7 +29739,7 @@ var ts; var argumentsWritten = 0; if (compilerOptions.emitDecoratorMetadata) { if (shouldEmitTypeMetadata(node)) { - var serializedType = resolver.serializeTypeOfNode(node, getGeneratedNameForNode); + var serializedType = resolver.serializeTypeOfNode(node); if (serializedType) { if (writeComma) { write(", "); @@ -28007,7 +29752,7 @@ var ts; } } if (shouldEmitParamTypesMetadata(node)) { - var serializedTypes = resolver.serializeParameterTypesOfNode(node, getGeneratedNameForNode); + var serializedTypes = resolver.serializeParameterTypesOfNode(node); if (serializedTypes) { if (writeComma || argumentsWritten) { write(", "); @@ -28025,7 +29770,7 @@ var ts; } } if (shouldEmitReturnTypeMetadata(node)) { - var serializedType = resolver.serializeReturnTypeOfNode(node, getGeneratedNameForNode); + var serializedType = resolver.serializeReturnTypeOfNode(node); if (serializedType) { if (writeComma || argumentsWritten) { write(", "); @@ -28066,7 +29811,7 @@ var ts; } function shouldEmitEnumDeclaration(node) { var isConstEnum = ts.isConst(node); - return !isConstEnum || compilerOptions.preserveConstEnums || compilerOptions.separateCompilation; + return !isConstEnum || compilerOptions.preserveConstEnums || compilerOptions.isolatedModules; } function emitEnumDeclaration(node) { // const enums are completely erased during compilation. @@ -28125,7 +29870,7 @@ var ts; emitDeclarationName(node); write("\", "); emitDeclarationName(node); - write(")"); + write(");"); } emitExportMemberAssignments(node.name); } @@ -28159,13 +29904,13 @@ var ts; } } function getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration) { - if (moduleDeclaration.body.kind === 206 /* ModuleDeclaration */) { + if (moduleDeclaration.body.kind === 208 /* ModuleDeclaration */) { var recursiveInnerModule = getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration.body); return recursiveInnerModule || moduleDeclaration.body; } } function shouldEmitModuleDeclaration(node) { - return ts.isInstantiatedModule(node, compilerOptions.preserveConstEnums || compilerOptions.separateCompilation); + return ts.isInstantiatedModule(node, compilerOptions.preserveConstEnums || compilerOptions.isolatedModules); } function isModuleMergedWithES6Class(node) { return languageVersion === 2 /* ES6 */ && !!(resolver.getNodeCheckFlags(node) & 2048 /* LexicalModuleMergesWithClass */); @@ -28195,7 +29940,7 @@ var ts; write(getGeneratedNameForNode(node)); emitEnd(node.name); write(") "); - if (node.body.kind === 207 /* ModuleBlock */) { + if (node.body.kind === 209 /* ModuleBlock */) { var saveTempFlags = tempFlags; var saveTempVariables = tempVariables; tempFlags = 0; @@ -28235,7 +29980,7 @@ var ts; emitDeclarationName(node); write("\", "); emitDeclarationName(node); - write(")"); + write(");"); } emitExportMemberAssignments(node.name); } @@ -28253,16 +29998,16 @@ var ts; } } function getNamespaceDeclarationNode(node) { - if (node.kind === 209 /* ImportEqualsDeclaration */) { + if (node.kind === 211 /* ImportEqualsDeclaration */) { return node; } var importClause = node.importClause; - if (importClause && importClause.namedBindings && importClause.namedBindings.kind === 212 /* NamespaceImport */) { + if (importClause && importClause.namedBindings && importClause.namedBindings.kind === 214 /* NamespaceImport */) { return importClause.namedBindings; } } function isDefaultImport(node) { - return node.kind === 210 /* ImportDeclaration */ && node.importClause && !!node.importClause.name; + return node.kind === 212 /* ImportDeclaration */ && node.importClause && !!node.importClause.name; } function emitExportImportAssignments(node) { if (ts.isAliasSymbolDeclaration(node) && resolver.isValueAliasDeclaration(node)) { @@ -28290,7 +30035,7 @@ var ts; if (shouldEmitNamedBindings) { emitLeadingComments(node.importClause.namedBindings); emitStart(node.importClause.namedBindings); - if (node.importClause.namedBindings.kind === 212 /* NamespaceImport */) { + if (node.importClause.namedBindings.kind === 214 /* NamespaceImport */) { write("* as "); emit(node.importClause.namedBindings.name); } @@ -28316,7 +30061,7 @@ var ts; } function emitExternalImportDeclaration(node) { if (ts.contains(externalImports, node)) { - var isExportedImport = node.kind === 209 /* ImportEqualsDeclaration */ && (node.flags & 1 /* Export */) !== 0; + var isExportedImport = node.kind === 211 /* ImportEqualsDeclaration */ && (node.flags & 1 /* Export */) !== 0; var namespaceDeclaration = getNamespaceDeclarationNode(node); if (compilerOptions.module !== 2 /* AMD */) { emitLeadingComments(node); @@ -28335,7 +30080,7 @@ var ts; // import { x, y } from "foo" // import d, * as x from "foo" // import d, { x, y } from "foo" - var isNakedImport = 210 /* ImportDeclaration */ && !node.importClause; + var isNakedImport = 212 /* ImportDeclaration */ && !node.importClause; if (!isNakedImport) { write("var "); write(getGeneratedNameForNode(node)); @@ -28499,8 +30244,8 @@ var ts; write("export default "); var expression = node.expression; emit(expression); - if (expression.kind !== 201 /* FunctionDeclaration */ && - expression.kind !== 202 /* ClassDeclaration */) { + if (expression.kind !== 203 /* FunctionDeclaration */ && + expression.kind !== 204 /* ClassDeclaration */) { write(";"); } emitEnd(node); @@ -28536,7 +30281,7 @@ var ts; for (var _a = 0, _b = sourceFile.statements; _a < _b.length; _a++) { var node = _b[_a]; switch (node.kind) { - case 210 /* ImportDeclaration */: + case 212 /* ImportDeclaration */: if (!node.importClause || resolver.isReferencedAliasDeclaration(node.importClause, true)) { // import "mod" @@ -28546,13 +30291,13 @@ var ts; externalImports.push(node); } break; - case 209 /* ImportEqualsDeclaration */: - if (node.moduleReference.kind === 220 /* ExternalModuleReference */ && resolver.isReferencedAliasDeclaration(node)) { + case 211 /* ImportEqualsDeclaration */: + if (node.moduleReference.kind === 222 /* ExternalModuleReference */ && resolver.isReferencedAliasDeclaration(node)) { // import x = require("mod") where x is referenced externalImports.push(node); } break; - case 216 /* ExportDeclaration */: + case 218 /* ExportDeclaration */: if (node.moduleSpecifier) { if (!node.exportClause) { // export * from "mod" @@ -28568,12 +30313,12 @@ var ts; // export { x, y } for (var _c = 0, _d = node.exportClause.elements; _c < _d.length; _c++) { var specifier = _d[_c]; - var name_20 = (specifier.propertyName || specifier.name).text; - (exportSpecifiers[name_20] || (exportSpecifiers[name_20] = [])).push(specifier); + var name_21 = (specifier.propertyName || specifier.name).text; + (exportSpecifiers[name_21] || (exportSpecifiers[name_21] = [])).push(specifier); } } break; - case 215 /* ExportAssignment */: + case 217 /* ExportAssignment */: if (node.isExportEquals && !exportEquals) { // export = x exportEquals = node; @@ -28594,13 +30339,16 @@ var ts; write("}"); } } - function getLocalNameForExternalImport(importNode) { - var namespaceDeclaration = getNamespaceDeclarationNode(importNode); - if (namespaceDeclaration && !isDefaultImport(importNode)) { + function getLocalNameForExternalImport(node) { + var namespaceDeclaration = getNamespaceDeclarationNode(node); + if (namespaceDeclaration && !isDefaultImport(node)) { return ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, namespaceDeclaration.name); } - else { - return getGeneratedNameForNode(importNode); + if (node.kind === 212 /* ImportDeclaration */ && node.importClause) { + return getGeneratedNameForNode(node); + } + if (node.kind === 218 /* ExportDeclaration */ && node.moduleSpecifier) { + return getGeneratedNameForNode(node); } } function getExternalModuleNameText(importNode) { @@ -28619,8 +30367,8 @@ var ts; for (var _a = 0; _a < externalImports.length; _a++) { var importNode = externalImports[_a]; // do not create variable declaration for exports and imports that lack import clause - var skipNode = importNode.kind === 216 /* ExportDeclaration */ || - (importNode.kind === 210 /* ImportDeclaration */ && !importNode.importClause); + var skipNode = importNode.kind === 218 /* ExportDeclaration */ || + (importNode.kind === 212 /* ImportDeclaration */ && !importNode.importClause); if (skipNode) { continue; } @@ -28653,7 +30401,7 @@ var ts; var hasExportDeclarationWithExportClause = false; for (var _a = 0; _a < externalImports.length; _a++) { var externalImport = externalImports[_a]; - if (externalImport.kind === 216 /* ExportDeclaration */ && externalImport.exportClause) { + if (externalImport.kind === 218 /* ExportDeclaration */ && externalImport.exportClause) { hasExportDeclarationWithExportClause = true; break; } @@ -28685,7 +30433,7 @@ var ts; } for (var _d = 0; _d < externalImports.length; _d++) { var externalImport = externalImports[_d]; - if (externalImport.kind !== 216 /* ExportDeclaration */) { + if (externalImport.kind !== 218 /* ExportDeclaration */) { continue; } var exportDecl = externalImport; @@ -28769,12 +30517,12 @@ var ts; var seen = {}; for (var i = 0; i < hoistedVars.length; ++i) { var local = hoistedVars[i]; - var name_21 = local.kind === 65 /* Identifier */ + var name_22 = local.kind === 65 /* Identifier */ ? local : local.name; - if (name_21) { + if (name_22) { // do not emit duplicate entries (in case of declaration merging) in the list of hoisted variables - var text = ts.unescapeIdentifier(name_21.text); + var text = ts.unescapeIdentifier(name_22.text); if (ts.hasProperty(seen, text)) { continue; } @@ -28785,7 +30533,7 @@ var ts; if (i !== 0) { write(", "); } - if (local.kind === 202 /* ClassDeclaration */ || local.kind === 206 /* ModuleDeclaration */ || local.kind === 205 /* EnumDeclaration */) { + if (local.kind === 204 /* ClassDeclaration */ || local.kind === 208 /* ModuleDeclaration */ || local.kind === 207 /* EnumDeclaration */) { emitDeclarationName(local); } else { @@ -28819,21 +30567,21 @@ var ts; if (node.flags & 2 /* Ambient */) { return; } - if (node.kind === 201 /* FunctionDeclaration */) { + if (node.kind === 203 /* FunctionDeclaration */) { if (!hoistedFunctionDeclarations) { hoistedFunctionDeclarations = []; } hoistedFunctionDeclarations.push(node); return; } - if (node.kind === 202 /* ClassDeclaration */) { + if (node.kind === 204 /* ClassDeclaration */) { if (!hoistedVars) { hoistedVars = []; } hoistedVars.push(node); return; } - if (node.kind === 205 /* EnumDeclaration */) { + if (node.kind === 207 /* EnumDeclaration */) { if (shouldEmitEnumDeclaration(node)) { if (!hoistedVars) { hoistedVars = []; @@ -28842,7 +30590,7 @@ var ts; } return; } - if (node.kind === 206 /* ModuleDeclaration */) { + if (node.kind === 208 /* ModuleDeclaration */) { if (shouldEmitModuleDeclaration(node)) { if (!hoistedVars) { hoistedVars = []; @@ -28851,17 +30599,17 @@ var ts; } return; } - if (node.kind === 199 /* VariableDeclaration */ || node.kind === 153 /* BindingElement */) { + if (node.kind === 201 /* VariableDeclaration */ || node.kind === 155 /* BindingElement */) { if (shouldHoistVariable(node, false)) { - var name_22 = node.name; - if (name_22.kind === 65 /* Identifier */) { + var name_23 = node.name; + if (name_23.kind === 65 /* Identifier */) { if (!hoistedVars) { hoistedVars = []; } - hoistedVars.push(name_22); + hoistedVars.push(name_23); } else { - ts.forEachChild(name_22, visit); + ts.forEachChild(name_23, visit); } } return; @@ -28885,7 +30633,7 @@ var ts; // if block scoped variables are nested in some another block then // no other functions can use them except ones that are defined at least in the same block return (ts.getCombinedNodeFlags(node) & 12288 /* BlockScoped */) === 0 || - ts.getEnclosingBlockScopeContainer(node).kind === 228 /* SourceFile */; + ts.getEnclosingBlockScopeContainer(node).kind === 230 /* SourceFile */; } function isCurrentFileSystemExternalModule() { return compilerOptions.module === 4 /* System */ && ts.isExternalModule(currentSourceFile); @@ -28938,10 +30686,10 @@ var ts; emitSetters(exportStarFunction); writeLine(); emitExecute(node, startIndex); - emitTempDeclarations(true); decreaseIndent(); writeLine(); write("}"); // return + emitTempDeclarations(true); } function emitSetters(exportStarFunction) { write("setters:["); @@ -28956,21 +30704,21 @@ var ts; var parameterName = "_" + importVariableName; write("function (" + parameterName + ") {"); switch (importNode.kind) { - case 210 /* ImportDeclaration */: + case 212 /* ImportDeclaration */: if (!importNode.importClause) { // 'import "..."' case // module is imported only for side-effects, setter body will be empty break; } // fall-through - case 209 /* ImportEqualsDeclaration */: + case 211 /* ImportEqualsDeclaration */: ts.Debug.assert(importVariableName !== ""); increaseIndent(); writeLine(); // save import into the local write(importVariableName + " = " + parameterName + ";"); writeLine(); - var defaultName = importNode.kind === 210 /* ImportDeclaration */ + var defaultName = importNode.kind === 212 /* ImportDeclaration */ ? importNode.importClause.name : importNode.name; if (defaultName) { @@ -28982,10 +30730,10 @@ var ts; emitExportMemberAssignments(defaultName); writeLine(); } - if (importNode.kind === 210 /* ImportDeclaration */ && + if (importNode.kind === 212 /* ImportDeclaration */ && importNode.importClause.namedBindings) { var namedBindings = importNode.importClause.namedBindings; - if (namedBindings.kind === 212 /* NamespaceImport */) { + if (namedBindings.kind === 214 /* NamespaceImport */) { // emit re-export for namespace // import * as n from 'foo' // export {n} @@ -29005,7 +30753,7 @@ var ts; } decreaseIndent(); break; - case 216 /* ExportDeclaration */: + case 218 /* ExportDeclaration */: ts.Debug.assert(importVariableName !== ""); increaseIndent(); if (importNode.exportClause) { @@ -29048,10 +30796,10 @@ var ts; // - imports/exports are not emitted for system modules // - function declarations are not emitted because they were already hoisted switch (statement.kind) { - case 216 /* ExportDeclaration */: - case 210 /* ImportDeclaration */: - case 209 /* ImportEqualsDeclaration */: - case 201 /* FunctionDeclaration */: + case 218 /* ExportDeclaration */: + case 212 /* ImportDeclaration */: + case 211 /* ImportEqualsDeclaration */: + case 203 /* FunctionDeclaration */: continue; } writeLine(); @@ -29074,7 +30822,11 @@ var ts; ts.Debug.assert(!exportFunctionForFile); // make sure that name of 'exports' function does not conflict with existing identifiers exportFunctionForFile = makeUniqueName("exports"); - write("System.register(["); + write("System.register("); + if (node.moduleName) { + write("\"" + node.moduleName + "\", "); + } + write("["); for (var i = 0; i < externalImports.length; ++i) { var text = getExternalModuleNameText(externalImports[i]); if (i !== 0) { @@ -29154,8 +30906,8 @@ var ts; collectExternalModuleInfo(node); writeLine(); write("define("); - if (node.amdModuleName) { - write("\"" + node.amdModuleName + "\", "); + if (node.moduleName) { + write("\"" + node.moduleName + "\", "); } emitAMDDependencies(node, true); write(") {"); @@ -29265,7 +31017,7 @@ var ts; paramEmitted = true; } } - if (ts.isExternalModule(node) || compilerOptions.separateCompilation) { + if (ts.isExternalModule(node) || compilerOptions.isolatedModules) { if (languageVersion >= 2 /* ES6 */) { emitES6Module(node, startIndex); } @@ -29293,7 +31045,7 @@ var ts; } emitLeadingComments(node.endOfFileToken); } - function emitNodeWithoutSourceMap(node, allowGeneratedIdentifiers) { + function emitNodeWithoutSourceMap(node) { if (!node) { return; } @@ -29304,7 +31056,7 @@ var ts; if (emitComments) { emitLeadingComments(node); } - emitJavaScriptWorker(node, allowGeneratedIdentifiers); + emitJavaScriptWorker(node); if (emitComments) { emitTrailingComments(node); } @@ -29313,18 +31065,20 @@ var ts; switch (node.kind) { // All of these entities are emitted in a specialized fashion. As such, we allow // the specialized methods for each to handle the comments on the nodes. - case 203 /* InterfaceDeclaration */: - case 201 /* FunctionDeclaration */: - case 210 /* ImportDeclaration */: - case 209 /* ImportEqualsDeclaration */: - case 204 /* TypeAliasDeclaration */: - case 215 /* ExportAssignment */: + case 205 /* InterfaceDeclaration */: + case 203 /* FunctionDeclaration */: + case 212 /* ImportDeclaration */: + case 211 /* ImportEqualsDeclaration */: + case 206 /* TypeAliasDeclaration */: + case 217 /* ExportAssignment */: return false; - case 206 /* ModuleDeclaration */: + case 183 /* VariableStatement */: + return shouldEmitLeadingAndTrailingCommentsForVariableStatement(node); + case 208 /* ModuleDeclaration */: // Only emit the leading/trailing comments for a module if we're actually // emitting the module as well. return shouldEmitModuleDeclaration(node); - case 205 /* EnumDeclaration */: + case 207 /* EnumDeclaration */: // Only emit the leading/trailing comments for an enum if we're actually // emitting the module as well. return shouldEmitEnumDeclaration(node); @@ -29333,9 +31087,9 @@ var ts; // then we don't want to emit comments when we emit the body. It will have already // been taken care of when we emitted the 'return' statement for the function // expression body. - if (node.kind !== 180 /* Block */ && + if (node.kind !== 182 /* Block */ && node.parent && - node.parent.kind === 164 /* ArrowFunction */ && + node.parent.kind === 166 /* ArrowFunction */ && node.parent.body === node && compilerOptions.target <= 1 /* ES5 */) { return false; @@ -29343,19 +31097,18 @@ var ts; // Emit comments for everything else. return true; } - function emitJavaScriptWorker(node, allowGeneratedIdentifiers) { - if (allowGeneratedIdentifiers === void 0) { allowGeneratedIdentifiers = true; } + function emitJavaScriptWorker(node) { // Check if the node can be emitted regardless of the ScriptTarget switch (node.kind) { case 65 /* Identifier */: - return emitIdentifier(node, allowGeneratedIdentifiers); - case 130 /* Parameter */: + return emitIdentifier(node); + case 131 /* Parameter */: return emitParameter(node); - case 135 /* MethodDeclaration */: - case 134 /* MethodSignature */: + case 136 /* MethodDeclaration */: + case 135 /* MethodSignature */: return emitMethod(node); - case 137 /* GetAccessor */: - case 138 /* SetAccessor */: + case 138 /* GetAccessor */: + case 139 /* SetAccessor */: return emitAccessor(node); case 93 /* ThisKeyword */: return emitThis(node); @@ -29375,131 +31128,131 @@ var ts; case 12 /* TemplateMiddle */: case 13 /* TemplateTail */: return emitLiteral(node); - case 172 /* TemplateExpression */: + case 174 /* TemplateExpression */: return emitTemplateExpression(node); - case 178 /* TemplateSpan */: + case 180 /* TemplateSpan */: return emitTemplateSpan(node); - case 127 /* QualifiedName */: + case 128 /* QualifiedName */: return emitQualifiedName(node); - case 151 /* ObjectBindingPattern */: + case 153 /* ObjectBindingPattern */: return emitObjectBindingPattern(node); - case 152 /* ArrayBindingPattern */: + case 154 /* ArrayBindingPattern */: return emitArrayBindingPattern(node); - case 153 /* BindingElement */: + case 155 /* BindingElement */: return emitBindingElement(node); - case 154 /* ArrayLiteralExpression */: + case 156 /* ArrayLiteralExpression */: return emitArrayLiteral(node); - case 155 /* ObjectLiteralExpression */: + case 157 /* ObjectLiteralExpression */: return emitObjectLiteral(node); - case 225 /* PropertyAssignment */: + case 227 /* PropertyAssignment */: return emitPropertyAssignment(node); - case 226 /* ShorthandPropertyAssignment */: + case 228 /* ShorthandPropertyAssignment */: return emitShorthandPropertyAssignment(node); - case 128 /* ComputedPropertyName */: + case 129 /* ComputedPropertyName */: return emitComputedPropertyName(node); - case 156 /* PropertyAccessExpression */: + case 158 /* PropertyAccessExpression */: return emitPropertyAccess(node); - case 157 /* ElementAccessExpression */: + case 159 /* ElementAccessExpression */: return emitIndexedAccess(node); - case 158 /* CallExpression */: + case 160 /* CallExpression */: return emitCallExpression(node); - case 159 /* NewExpression */: + case 161 /* NewExpression */: return emitNewExpression(node); - case 160 /* TaggedTemplateExpression */: + case 162 /* TaggedTemplateExpression */: return emitTaggedTemplateExpression(node); - case 161 /* TypeAssertionExpression */: + case 163 /* TypeAssertionExpression */: return emit(node.expression); - case 162 /* ParenthesizedExpression */: + case 164 /* ParenthesizedExpression */: return emitParenExpression(node); - case 201 /* FunctionDeclaration */: - case 163 /* FunctionExpression */: - case 164 /* ArrowFunction */: + case 203 /* FunctionDeclaration */: + case 165 /* FunctionExpression */: + case 166 /* ArrowFunction */: return emitFunctionDeclaration(node); - case 165 /* DeleteExpression */: + case 167 /* DeleteExpression */: return emitDeleteExpression(node); - case 166 /* TypeOfExpression */: + case 168 /* TypeOfExpression */: return emitTypeOfExpression(node); - case 167 /* VoidExpression */: + case 169 /* VoidExpression */: return emitVoidExpression(node); - case 168 /* PrefixUnaryExpression */: + case 170 /* PrefixUnaryExpression */: return emitPrefixUnaryExpression(node); - case 169 /* PostfixUnaryExpression */: + case 171 /* PostfixUnaryExpression */: return emitPostfixUnaryExpression(node); - case 170 /* BinaryExpression */: + case 172 /* BinaryExpression */: return emitBinaryExpression(node); - case 171 /* ConditionalExpression */: + case 173 /* ConditionalExpression */: return emitConditionalExpression(node); - case 174 /* SpreadElementExpression */: + case 176 /* SpreadElementExpression */: return emitSpreadElementExpression(node); - case 173 /* YieldExpression */: + case 175 /* YieldExpression */: return emitYieldExpression(node); - case 176 /* OmittedExpression */: + case 178 /* OmittedExpression */: return; - case 180 /* Block */: - case 207 /* ModuleBlock */: + case 182 /* Block */: + case 209 /* ModuleBlock */: return emitBlock(node); - case 181 /* VariableStatement */: + case 183 /* VariableStatement */: return emitVariableStatement(node); - case 182 /* EmptyStatement */: + case 184 /* EmptyStatement */: return write(";"); - case 183 /* ExpressionStatement */: + case 185 /* ExpressionStatement */: return emitExpressionStatement(node); - case 184 /* IfStatement */: + case 186 /* IfStatement */: return emitIfStatement(node); - case 185 /* DoStatement */: + case 187 /* DoStatement */: return emitDoStatement(node); - case 186 /* WhileStatement */: + case 188 /* WhileStatement */: return emitWhileStatement(node); - case 187 /* ForStatement */: + case 189 /* ForStatement */: return emitForStatement(node); - case 189 /* ForOfStatement */: - case 188 /* ForInStatement */: + case 191 /* ForOfStatement */: + case 190 /* ForInStatement */: return emitForInOrForOfStatement(node); - case 190 /* ContinueStatement */: - case 191 /* BreakStatement */: + case 192 /* ContinueStatement */: + case 193 /* BreakStatement */: return emitBreakOrContinueStatement(node); - case 192 /* ReturnStatement */: + case 194 /* ReturnStatement */: return emitReturnStatement(node); - case 193 /* WithStatement */: + case 195 /* WithStatement */: return emitWithStatement(node); - case 194 /* SwitchStatement */: + case 196 /* SwitchStatement */: return emitSwitchStatement(node); - case 221 /* CaseClause */: - case 222 /* DefaultClause */: + case 223 /* CaseClause */: + case 224 /* DefaultClause */: return emitCaseOrDefaultClause(node); - case 195 /* LabeledStatement */: + case 197 /* LabeledStatement */: return emitLabelledStatement(node); - case 196 /* ThrowStatement */: + case 198 /* ThrowStatement */: return emitThrowStatement(node); - case 197 /* TryStatement */: + case 199 /* TryStatement */: return emitTryStatement(node); - case 224 /* CatchClause */: + case 226 /* CatchClause */: return emitCatchClause(node); - case 198 /* DebuggerStatement */: + case 200 /* DebuggerStatement */: return emitDebuggerStatement(node); - case 199 /* VariableDeclaration */: + case 201 /* VariableDeclaration */: return emitVariableDeclaration(node); - case 175 /* ClassExpression */: + case 177 /* ClassExpression */: return emitClassExpression(node); - case 202 /* ClassDeclaration */: + case 204 /* ClassDeclaration */: return emitClassDeclaration(node); - case 203 /* InterfaceDeclaration */: + case 205 /* InterfaceDeclaration */: return emitInterfaceDeclaration(node); - case 205 /* EnumDeclaration */: + case 207 /* EnumDeclaration */: return emitEnumDeclaration(node); - case 227 /* EnumMember */: + case 229 /* EnumMember */: return emitEnumMember(node); - case 206 /* ModuleDeclaration */: + case 208 /* ModuleDeclaration */: return emitModuleDeclaration(node); - case 210 /* ImportDeclaration */: + case 212 /* ImportDeclaration */: return emitImportDeclaration(node); - case 209 /* ImportEqualsDeclaration */: + case 211 /* ImportEqualsDeclaration */: return emitImportEqualsDeclaration(node); - case 216 /* ExportDeclaration */: + case 218 /* ExportDeclaration */: return emitExportDeclaration(node); - case 215 /* ExportAssignment */: + case 217 /* ExportAssignment */: return emitExportAssignment(node); - case 228 /* SourceFile */: + case 230 /* SourceFile */: return emitSourceFileNode(node); } } @@ -29531,7 +31284,7 @@ var ts; function getLeadingCommentsToEmit(node) { // Emit the leading comments only if the parent's pos doesn't match because parent should take care of emitting these comments if (node.parent) { - if (node.parent.kind === 228 /* SourceFile */ || node.pos !== node.parent.pos) { + if (node.parent.kind === 230 /* SourceFile */ || node.pos !== node.parent.pos) { if (hasDetachedComments(node.pos)) { // get comments without detached comments return getLeadingCommentsWithoutDetachedComments(); @@ -29546,7 +31299,7 @@ var ts; function getTrailingCommentsToEmit(node) { // Emit the trailing comments only if the parent's pos doesn't match because parent should take care of emitting these comments if (node.parent) { - if (node.parent.kind === 228 /* SourceFile */ || node.end !== node.parent.end) { + if (node.parent.kind === 230 /* SourceFile */ || node.end !== node.parent.end) { return ts.getTrailingCommentRanges(currentSourceFile.text, node.end); } } @@ -29656,9 +31409,7 @@ var ts; /* @internal */ ts.ioReadTime = 0; /* @internal */ ts.ioWriteTime = 0; /** The version of the TypeScript compiler release */ - ts.version = "1.5.2"; - var carriageReturnLineFeed = "\r\n"; - var lineFeed = "\n"; + ts.version = "1.5.3"; function findConfigFile(searchPath) { var fileName = "tsconfig.json"; while (true) { @@ -29732,9 +31483,7 @@ var ts; } } } - var newLine = options.newLine === 0 /* CarriageReturnLineFeed */ ? carriageReturnLineFeed : - options.newLine === 1 /* LineFeed */ ? lineFeed : - ts.sys.newLine; + var newLine = ts.getNewLineCharacter(options); return { getSourceFile: getSourceFile, getDefaultLibFileName: function (options) { return ts.combinePaths(ts.getDirectoryPath(ts.normalizePath(ts.sys.getExecutingFilePath())), ts.getDefaultLibFileName(options)); }, @@ -29747,7 +31496,7 @@ var ts; } ts.createCompilerHost = createCompilerHost; function getPreEmitDiagnostics(program, sourceFile) { - var diagnostics = program.getSyntacticDiagnostics(sourceFile).concat(program.getGlobalDiagnostics()).concat(program.getSemanticDiagnostics(sourceFile)); + var diagnostics = program.getOptionsDiagnostics().concat(program.getSyntacticDiagnostics(sourceFile), program.getGlobalDiagnostics(), program.getSemanticDiagnostics(sourceFile)); if (program.getCompilerOptions().declaration) { diagnostics.concat(program.getDeclarationDiagnostics(sourceFile)); } @@ -29780,16 +31529,21 @@ var ts; function createProgram(rootNames, options, host) { var program; var files = []; - var filesByName = {}; var diagnostics = ts.createDiagnosticCollection(); - var seenNoDefaultLib = options.noLib; var commonSourceDirectory; var diagnosticsProducingTypeChecker; var noDiagnosticsTypeChecker; + var classifiableNames; + var skipDefaultLib = options.noLib; var start = new Date().getTime(); host = host || createCompilerHost(options); + var filesByName = ts.createFileMap(function (fileName) { return host.getCanonicalFileName(fileName); }); ts.forEach(rootNames, function (name) { return processRootFile(name, false); }); - if (!seenNoDefaultLib) { + // Do not process the default library if: + // - The '--noLib' flag is used. + // - A 'no-default-lib' reference comment is encountered in + // processing the root files. + if (!skipDefaultLib) { processRootFile(host.getDefaultLibFileName(options), true); } verifyCompilerOptions(); @@ -29799,10 +31553,12 @@ var ts; getSourceFiles: function () { return files; }, getCompilerOptions: function () { return options; }, getSyntacticDiagnostics: getSyntacticDiagnostics, + getOptionsDiagnostics: getOptionsDiagnostics, getGlobalDiagnostics: getGlobalDiagnostics, getSemanticDiagnostics: getSemanticDiagnostics, getDeclarationDiagnostics: getDeclarationDiagnostics, getTypeChecker: getTypeChecker, + getClassifiableNames: getClassifiableNames, getDiagnosticsProducingTypeChecker: getDiagnosticsProducingTypeChecker, getCommonSourceDirectory: function () { return commonSourceDirectory; }, emit: emit, @@ -29813,6 +31569,18 @@ var ts; getTypeCount: function () { return getDiagnosticsProducingTypeChecker().getTypeCount(); } }; return program; + function getClassifiableNames() { + if (!classifiableNames) { + // Initialize a checker so that all our files are bound. + getTypeChecker(); + classifiableNames = {}; + for (var _i = 0; _i < files.length; _i++) { + var sourceFile = files[_i]; + ts.copyMap(sourceFile.classifiableNames, classifiableNames); + } + } + return classifiableNames; + } function getEmitHost(writeFileCallback) { return { getCanonicalFileName: function (fileName) { return host.getCanonicalFileName(fileName); }, @@ -29852,8 +31620,7 @@ var ts; return emitResult; } function getSourceFile(fileName) { - fileName = host.getCanonicalFileName(ts.normalizeSlashes(fileName)); - return ts.hasProperty(filesByName, fileName) ? filesByName[fileName] : undefined; + return filesByName.get(fileName); } function getDiagnosticsHelper(sourceFile, getDiagnostics) { if (sourceFile) { @@ -29893,13 +31660,16 @@ var ts; return ts.getDeclarationDiagnostics(getEmitHost(writeFile), resolver, sourceFile); } } - function getGlobalDiagnostics() { - var typeChecker = getDiagnosticsProducingTypeChecker(); + function getOptionsDiagnostics() { var allDiagnostics = []; - ts.addRange(allDiagnostics, typeChecker.getGlobalDiagnostics()); ts.addRange(allDiagnostics, diagnostics.getGlobalDiagnostics()); return ts.sortAndDeduplicateDiagnostics(allDiagnostics); } + function getGlobalDiagnostics() { + var allDiagnostics = []; + ts.addRange(allDiagnostics, getDiagnosticsProducingTypeChecker().getGlobalDiagnostics()); + return ts.sortAndDeduplicateDiagnostics(allDiagnostics); + } function hasExtension(fileName) { return ts.getBaseFileName(fileName).indexOf(".") >= 0; } @@ -29931,14 +31701,17 @@ var ts; } } else { - if (options.allowNonTsExtensions && !findSourceFile(fileName, isDefaultLib, refFile, refPos, refEnd)) { - diagnostic = ts.Diagnostics.File_0_not_found; - diagnosticArgument = [fileName]; - } - else if (!ts.forEach(ts.supportedExtensions, function (extension) { return findSourceFile(fileName + extension, isDefaultLib, refFile, refPos, refEnd); })) { - diagnostic = ts.Diagnostics.File_0_not_found; - fileName += ".ts"; - diagnosticArgument = [fileName]; + var nonTsFile = options.allowNonTsExtensions && findSourceFile(fileName, isDefaultLib, refFile, refPos, refEnd); + if (!nonTsFile) { + if (options.allowNonTsExtensions) { + diagnostic = ts.Diagnostics.File_0_not_found; + diagnosticArgument = [fileName]; + } + else if (!ts.forEach(ts.supportedExtensions, function (extension) { return findSourceFile(fileName + extension, isDefaultLib, refFile, refPos, refEnd); })) { + diagnostic = ts.Diagnostics.File_0_not_found; + fileName += ".ts"; + diagnosticArgument = [fileName]; + } } } if (diagnostic) { @@ -29953,18 +31726,18 @@ var ts; // Get source file from normalized fileName function findSourceFile(fileName, isDefaultLib, refFile, refStart, refLength) { var canonicalName = host.getCanonicalFileName(ts.normalizeSlashes(fileName)); - if (ts.hasProperty(filesByName, canonicalName)) { + if (filesByName.contains(canonicalName)) { // We've already looked for this file, use cached result return getSourceFileFromCache(fileName, canonicalName, false); } else { var normalizedAbsolutePath = ts.getNormalizedAbsolutePath(fileName, host.getCurrentDirectory()); var canonicalAbsolutePath = host.getCanonicalFileName(normalizedAbsolutePath); - if (ts.hasProperty(filesByName, canonicalAbsolutePath)) { + if (filesByName.contains(canonicalAbsolutePath)) { return getSourceFileFromCache(normalizedAbsolutePath, canonicalAbsolutePath, true); } // We haven't looked for this file, do so now and cache result - var file = filesByName[canonicalName] = host.getSourceFile(fileName, options.target, function (hostErrorMessage) { + var file = host.getSourceFile(fileName, options.target, function (hostErrorMessage) { if (refFile) { diagnostics.add(ts.createFileDiagnostic(refFile, refStart, refLength, ts.Diagnostics.Cannot_read_file_0_Colon_1, fileName, hostErrorMessage)); } @@ -29972,16 +31745,18 @@ var ts; diagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0_Colon_1, fileName, hostErrorMessage)); } }); + filesByName.set(canonicalName, file); if (file) { - seenNoDefaultLib = seenNoDefaultLib || file.hasNoDefaultLib; + skipDefaultLib = skipDefaultLib || file.hasNoDefaultLib; // Set the source file for normalized absolute path - filesByName[canonicalAbsolutePath] = file; + filesByName.set(canonicalAbsolutePath, file); if (!options.noResolve) { var basePath = ts.getDirectoryPath(fileName); processReferencedFiles(file, basePath); processImportedModules(file, basePath); } if (isDefaultLib) { + file.isDefaultLib = true; files.unshift(file); } else { @@ -29991,7 +31766,7 @@ var ts; return file; } function getSourceFileFromCache(fileName, canonicalName, useAbsolutePath) { - var file = filesByName[canonicalName]; + var file = filesByName.get(canonicalName); if (file && host.useCaseSensitiveFileNames()) { var sourceFileName = useAbsolutePath ? ts.getNormalizedAbsolutePath(file.fileName, host.getCurrentDirectory()) : file.fileName; if (canonicalName !== sourceFileName) { @@ -30009,7 +31784,7 @@ var ts; } function processImportedModules(file, basePath) { ts.forEach(file.statements, function (node) { - if (node.kind === 210 /* ImportDeclaration */ || node.kind === 209 /* ImportEqualsDeclaration */ || node.kind === 216 /* ExportDeclaration */) { + if (node.kind === 212 /* ImportDeclaration */ || node.kind === 211 /* ImportEqualsDeclaration */ || node.kind === 218 /* ExportDeclaration */) { var moduleNameExpr = ts.getExternalModuleName(node); if (moduleNameExpr && moduleNameExpr.kind === 8 /* StringLiteral */) { var moduleNameText = moduleNameExpr.text; @@ -30030,7 +31805,7 @@ var ts; } } } - else if (node.kind === 206 /* ModuleDeclaration */ && node.name.kind === 8 /* StringLiteral */ && (node.flags & 2 /* Ambient */ || ts.isDeclarationFile(file))) { + else if (node.kind === 208 /* ModuleDeclaration */ && node.name.kind === 8 /* StringLiteral */ && (node.flags & 2 /* Ambient */ || ts.isDeclarationFile(file))) { // TypeScript 1.0 spec (April 2014): 12.1.6 // An AmbientExternalModuleDeclaration declares an external module. // This type of declaration is permitted only in the global module. @@ -30108,18 +31883,18 @@ var ts; return allFilesBelongToPath; } function verifyCompilerOptions() { - if (options.separateCompilation) { + if (options.isolatedModules) { if (options.sourceMap) { - diagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_sourceMap_cannot_be_specified_with_option_separateCompilation)); + diagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_sourceMap_cannot_be_specified_with_option_isolatedModules)); } if (options.declaration) { - diagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_declaration_cannot_be_specified_with_option_separateCompilation)); + diagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_declaration_cannot_be_specified_with_option_isolatedModules)); } if (options.noEmitOnError) { - diagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_noEmitOnError_cannot_be_specified_with_option_separateCompilation)); + diagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_noEmitOnError_cannot_be_specified_with_option_isolatedModules)); } if (options.out) { - diagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_out_cannot_be_specified_with_option_separateCompilation)); + diagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_out_cannot_be_specified_with_option_isolatedModules)); } } if (options.inlineSourceMap) { @@ -30150,14 +31925,14 @@ var ts; } var languageVersion = options.target || 0 /* ES3 */; var firstExternalModuleSourceFile = ts.forEach(files, function (f) { return ts.isExternalModule(f) ? f : undefined; }); - if (options.separateCompilation) { + if (options.isolatedModules) { if (!options.module && languageVersion < 2 /* ES6 */) { - diagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_separateCompilation_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES6_or_higher)); + diagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES6_or_higher)); } var firstNonExternalModuleSourceFile = ts.forEach(files, function (f) { return !ts.isExternalModule(f) && !ts.isDeclarationFile(f) ? f : undefined; }); if (firstNonExternalModuleSourceFile) { var span = ts.getErrorSpanForNode(firstNonExternalModuleSourceFile, firstNonExternalModuleSourceFile); - diagnostics.add(ts.createFileDiagnostic(firstNonExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_compile_namespaces_when_the_separateCompilation_flag_is_provided)); + diagnostics.add(ts.createFileDiagnostic(firstNonExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided)); } } else if (firstExternalModuleSourceFile && languageVersion < 2 /* ES6 */ && !options.module) { @@ -30198,6 +31973,10 @@ var ts; diagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_noEmit_cannot_be_specified_with_option_declaration)); } } + if (options.emitDecoratorMetadata && + !options.experimentalDecorators) { + diagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_experimentalDecorators_must_also_be_specified_when_option_emitDecoratorMetadata_is_specified)); + } } } ts.createProgram = createProgram; @@ -30307,9 +32086,14 @@ var ts; name: "noResolve", type: "boolean" }, + { + name: "skipDefaultLibCheck", + type: "boolean" + }, { name: "out", type: "string", + isFilePath: true, description: ts.Diagnostics.Concatenate_and_emit_output_to_single_file, paramType: ts.Diagnostics.FILE }, @@ -30346,7 +32130,7 @@ var ts; paramType: ts.Diagnostics.LOCATION }, { - name: "separateCompilation", + name: "isolatedModules", type: "boolean" }, { @@ -30392,10 +32176,16 @@ var ts; type: "boolean", description: ts.Diagnostics.Watch_input_files }, + { + name: "experimentalDecorators", + type: "boolean", + description: ts.Diagnostics.Enables_experimental_support_for_ES7_decorators + }, { name: "emitDecoratorMetadata", type: "boolean", - experimental: true + experimental: true, + description: ts.Diagnostics.Enables_experimental_support_for_emitting_type_metadata_for_decorators } ]; function parseCommandLine(commandLine) { @@ -30540,7 +32330,7 @@ var ts; var errors = []; return { options: getCompilerOptions(), - fileNames: getFiles(), + fileNames: getFileNames(), errors: errors }; function getCompilerOptions() { @@ -30584,23 +32374,24 @@ var ts; } return options; } - function getFiles() { - var files = []; + function getFileNames() { + var fileNames = []; if (ts.hasProperty(json, "files")) { if (json["files"] instanceof Array) { - var files = ts.map(json["files"], function (s) { return ts.combinePaths(basePath, s); }); + fileNames = ts.map(json["files"], function (s) { return ts.combinePaths(basePath, s); }); } } else { - var sysFiles = host.readDirectory(basePath, ".ts"); + var exclude = json["exclude"] instanceof Array ? ts.map(json["exclude"], ts.normalizeSlashes) : undefined; + var sysFiles = host.readDirectory(basePath, ".ts", exclude); for (var i = 0; i < sysFiles.length; i++) { var name = sysFiles[i]; if (!ts.fileExtensionIs(name, ".d.ts") || !ts.contains(sysFiles, name.substr(0, name.length - 5) + ".ts")) { - files.push(name); + fileNames.push(name); } } } - return files; + return fileNames; } } ts.parseConfigFile = parseConfigFile; @@ -30677,7 +32468,7 @@ var ts; } } function autoCollapse(node) { - return ts.isFunctionBlock(node) && node.parent.kind !== 164 /* ArrowFunction */; + return ts.isFunctionBlock(node) && node.parent.kind !== 166 /* ArrowFunction */; } var depth = 0; var maxDepth = 20; @@ -30689,30 +32480,30 @@ var ts; addOutliningForLeadingCommentsForNode(n); } switch (n.kind) { - case 180 /* Block */: + case 182 /* Block */: if (!ts.isFunctionBlock(n)) { - var parent_6 = n.parent; + var parent_8 = n.parent; var openBrace = ts.findChildOfKind(n, 14 /* OpenBraceToken */, sourceFile); var closeBrace = ts.findChildOfKind(n, 15 /* CloseBraceToken */, sourceFile); // Check if the block is standalone, or 'attached' to some parent statement. // If the latter, we want to collaps the block, but consider its hint span // to be the entire span of the parent. - if (parent_6.kind === 185 /* DoStatement */ || - parent_6.kind === 188 /* ForInStatement */ || - parent_6.kind === 189 /* ForOfStatement */ || - parent_6.kind === 187 /* ForStatement */ || - parent_6.kind === 184 /* IfStatement */ || - parent_6.kind === 186 /* WhileStatement */ || - parent_6.kind === 193 /* WithStatement */ || - parent_6.kind === 224 /* CatchClause */) { - addOutliningSpan(parent_6, openBrace, closeBrace, autoCollapse(n)); + if (parent_8.kind === 187 /* DoStatement */ || + parent_8.kind === 190 /* ForInStatement */ || + parent_8.kind === 191 /* ForOfStatement */ || + parent_8.kind === 189 /* ForStatement */ || + parent_8.kind === 186 /* IfStatement */ || + parent_8.kind === 188 /* WhileStatement */ || + parent_8.kind === 195 /* WithStatement */ || + parent_8.kind === 226 /* CatchClause */) { + addOutliningSpan(parent_8, openBrace, closeBrace, autoCollapse(n)); break; } - if (parent_6.kind === 197 /* TryStatement */) { + if (parent_8.kind === 199 /* TryStatement */) { // Could be the try-block, or the finally-block. - var tryStatement = parent_6; + var tryStatement = parent_8; if (tryStatement.tryBlock === n) { - addOutliningSpan(parent_6, openBrace, closeBrace, autoCollapse(n)); + addOutliningSpan(parent_8, openBrace, closeBrace, autoCollapse(n)); break; } else if (tryStatement.finallyBlock === n) { @@ -30735,23 +32526,23 @@ var ts; break; } // Fallthrough. - case 207 /* ModuleBlock */: { + case 209 /* ModuleBlock */: { var openBrace = ts.findChildOfKind(n, 14 /* OpenBraceToken */, sourceFile); var closeBrace = ts.findChildOfKind(n, 15 /* CloseBraceToken */, sourceFile); addOutliningSpan(n.parent, openBrace, closeBrace, autoCollapse(n)); break; } - case 202 /* ClassDeclaration */: - case 203 /* InterfaceDeclaration */: - case 205 /* EnumDeclaration */: - case 155 /* ObjectLiteralExpression */: - case 208 /* CaseBlock */: { + case 204 /* ClassDeclaration */: + case 205 /* InterfaceDeclaration */: + case 207 /* EnumDeclaration */: + case 157 /* ObjectLiteralExpression */: + case 210 /* CaseBlock */: { var openBrace = ts.findChildOfKind(n, 14 /* OpenBraceToken */, sourceFile); var closeBrace = ts.findChildOfKind(n, 15 /* CloseBraceToken */, sourceFile); addOutliningSpan(n, openBrace, closeBrace, autoCollapse(n)); break; } - case 154 /* ArrayLiteralExpression */: + case 156 /* ArrayLiteralExpression */: var openBracket = ts.findChildOfKind(n, 18 /* OpenBracketToken */, sourceFile); var closeBracket = ts.findChildOfKind(n, 19 /* CloseBracketToken */, sourceFile); addOutliningSpan(n, openBracket, closeBracket, autoCollapse(n)); @@ -30779,12 +32570,12 @@ var ts; ts.forEach(program.getSourceFiles(), function (sourceFile) { cancellationToken.throwIfCancellationRequested(); var nameToDeclarations = sourceFile.getNamedDeclarations(); - for (var name_23 in nameToDeclarations) { - var declarations = ts.getProperty(nameToDeclarations, name_23); + for (var name_24 in nameToDeclarations) { + var declarations = ts.getProperty(nameToDeclarations, name_24); if (declarations) { // First do a quick check to see if the name of the declaration matches the // last portion of the (possibly) dotted name they're searching for. - var matches = patternMatcher.getMatchesForLastSegmentOfPattern(name_23); + var matches = patternMatcher.getMatchesForLastSegmentOfPattern(name_24); if (!matches) { continue; } @@ -30797,14 +32588,14 @@ var ts; if (!containers) { return undefined; } - matches = patternMatcher.getMatches(containers, name_23); + matches = patternMatcher.getMatches(containers, name_24); if (!matches) { continue; } } var fileName = sourceFile.fileName; var matchKind = bestMatchKind(matches); - rawItems.push({ name: name_23, fileName: fileName, matchKind: matchKind, isCaseSensitive: allMatchesAreCaseSensitive(matches), declaration: declaration }); + rawItems.push({ name: name_24, fileName: fileName, matchKind: matchKind, isCaseSensitive: allMatchesAreCaseSensitive(matches), declaration: declaration }); } } } @@ -30842,7 +32633,7 @@ var ts; if (text !== undefined) { containers.unshift(text); } - else if (declaration.name.kind === 128 /* ComputedPropertyName */) { + else if (declaration.name.kind === 129 /* ComputedPropertyName */) { return tryAddComputedPropertyName(declaration.name.expression, containers, true); } else { @@ -30863,7 +32654,7 @@ var ts; } return true; } - if (expression.kind === 156 /* PropertyAccessExpression */) { + if (expression.kind === 158 /* PropertyAccessExpression */) { var propertyAccess = expression; if (includeLastPortion) { containers.unshift(propertyAccess.name.text); @@ -30876,7 +32667,7 @@ var ts; var containers = []; // First, if we started with a computed property name, then add all but the last // portion into the container array. - if (declaration.name.kind === 128 /* ComputedPropertyName */) { + if (declaration.name.kind === 129 /* ComputedPropertyName */) { if (!tryAddComputedPropertyName(declaration.name.expression, containers, false)) { return undefined; } @@ -30952,17 +32743,17 @@ var ts; var current = node.parent; while (current) { switch (current.kind) { - case 206 /* ModuleDeclaration */: + case 208 /* ModuleDeclaration */: // If we have a module declared as A.B.C, it is more "intuitive" // to say it only has a single layer of depth do { current = current.parent; - } while (current.kind === 206 /* ModuleDeclaration */); + } while (current.kind === 208 /* ModuleDeclaration */); // fall through - case 202 /* ClassDeclaration */: - case 205 /* EnumDeclaration */: - case 203 /* InterfaceDeclaration */: - case 201 /* FunctionDeclaration */: + case 204 /* ClassDeclaration */: + case 207 /* EnumDeclaration */: + case 205 /* InterfaceDeclaration */: + case 203 /* FunctionDeclaration */: indent++; } current = current.parent; @@ -30973,21 +32764,21 @@ var ts; var childNodes = []; function visit(node) { switch (node.kind) { - case 181 /* VariableStatement */: + case 183 /* VariableStatement */: ts.forEach(node.declarationList.declarations, visit); break; - case 151 /* ObjectBindingPattern */: - case 152 /* ArrayBindingPattern */: + case 153 /* ObjectBindingPattern */: + case 154 /* ArrayBindingPattern */: ts.forEach(node.elements, visit); break; - case 216 /* ExportDeclaration */: + case 218 /* ExportDeclaration */: // Handle named exports case e.g.: // export {a, b as B} from "mod"; if (node.exportClause) { ts.forEach(node.exportClause.elements, visit); } break; - case 210 /* ImportDeclaration */: + case 212 /* ImportDeclaration */: var importClause = node.importClause; if (importClause) { // Handle default import case e.g.: @@ -30999,7 +32790,7 @@ var ts; // import * as NS from "mod"; // import {a, b as B} from "mod"; if (importClause.namedBindings) { - if (importClause.namedBindings.kind === 212 /* NamespaceImport */) { + if (importClause.namedBindings.kind === 214 /* NamespaceImport */) { childNodes.push(importClause.namedBindings); } else { @@ -31008,21 +32799,21 @@ var ts; } } break; - case 153 /* BindingElement */: - case 199 /* VariableDeclaration */: + case 155 /* BindingElement */: + case 201 /* VariableDeclaration */: if (ts.isBindingPattern(node.name)) { visit(node.name); break; } // Fall through - case 202 /* ClassDeclaration */: - case 205 /* EnumDeclaration */: - case 203 /* InterfaceDeclaration */: - case 206 /* ModuleDeclaration */: - case 201 /* FunctionDeclaration */: - case 209 /* ImportEqualsDeclaration */: - case 214 /* ImportSpecifier */: - case 218 /* ExportSpecifier */: + case 204 /* ClassDeclaration */: + case 207 /* EnumDeclaration */: + case 205 /* InterfaceDeclaration */: + case 208 /* ModuleDeclaration */: + case 203 /* FunctionDeclaration */: + case 211 /* ImportEqualsDeclaration */: + case 216 /* ImportSpecifier */: + case 220 /* ExportSpecifier */: childNodes.push(node); break; } @@ -31070,17 +32861,17 @@ var ts; for (var _i = 0; _i < nodes.length; _i++) { var node = nodes[_i]; switch (node.kind) { - case 202 /* ClassDeclaration */: - case 205 /* EnumDeclaration */: - case 203 /* InterfaceDeclaration */: + case 204 /* ClassDeclaration */: + case 207 /* EnumDeclaration */: + case 205 /* InterfaceDeclaration */: topLevelNodes.push(node); break; - case 206 /* ModuleDeclaration */: + case 208 /* ModuleDeclaration */: var moduleDeclaration = node; topLevelNodes.push(node); addTopLevelNodes(getInnermostModule(moduleDeclaration).body.statements, topLevelNodes); break; - case 201 /* FunctionDeclaration */: + case 203 /* FunctionDeclaration */: var functionDeclaration = node; if (isTopLevelFunctionDeclaration(functionDeclaration)) { topLevelNodes.push(node); @@ -31091,12 +32882,12 @@ var ts; } } function isTopLevelFunctionDeclaration(functionDeclaration) { - if (functionDeclaration.kind === 201 /* FunctionDeclaration */) { + if (functionDeclaration.kind === 203 /* FunctionDeclaration */) { // A function declaration is 'top level' if it contains any function declarations // within it. - if (functionDeclaration.body && functionDeclaration.body.kind === 180 /* Block */) { + if (functionDeclaration.body && functionDeclaration.body.kind === 182 /* Block */) { // Proper function declarations can only have identifier names - if (ts.forEach(functionDeclaration.body.statements, function (s) { return s.kind === 201 /* FunctionDeclaration */ && !isEmpty(s.name.text); })) { + if (ts.forEach(functionDeclaration.body.statements, function (s) { return s.kind === 203 /* FunctionDeclaration */ && !isEmpty(s.name.text); })) { return true; } // Or if it is not parented by another function. i.e all functions @@ -31156,7 +32947,7 @@ var ts; } function createChildItem(node) { switch (node.kind) { - case 130 /* Parameter */: + case 131 /* Parameter */: if (ts.isBindingPattern(node.name)) { break; } @@ -31164,36 +32955,36 @@ var ts; return undefined; } return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.memberVariableElement); - case 135 /* MethodDeclaration */: - case 134 /* MethodSignature */: + case 136 /* MethodDeclaration */: + case 135 /* MethodSignature */: return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.memberFunctionElement); - case 137 /* GetAccessor */: + case 138 /* GetAccessor */: return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.memberGetAccessorElement); - case 138 /* SetAccessor */: + case 139 /* SetAccessor */: return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.memberSetAccessorElement); - case 141 /* IndexSignature */: + case 142 /* IndexSignature */: return createItem(node, "[]", ts.ScriptElementKind.indexSignatureElement); - case 227 /* EnumMember */: + case 229 /* EnumMember */: return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.memberVariableElement); - case 139 /* CallSignature */: + case 140 /* CallSignature */: return createItem(node, "()", ts.ScriptElementKind.callSignatureElement); - case 140 /* ConstructSignature */: + case 141 /* ConstructSignature */: return createItem(node, "new()", ts.ScriptElementKind.constructSignatureElement); - case 133 /* PropertyDeclaration */: - case 132 /* PropertySignature */: + case 134 /* PropertyDeclaration */: + case 133 /* PropertySignature */: return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.memberVariableElement); - case 201 /* FunctionDeclaration */: + case 203 /* FunctionDeclaration */: return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.functionElement); - case 199 /* VariableDeclaration */: - case 153 /* BindingElement */: + case 201 /* VariableDeclaration */: + case 155 /* BindingElement */: var variableDeclarationNode; - var name_24; - if (node.kind === 153 /* BindingElement */) { - name_24 = node.name; + var name_25; + if (node.kind === 155 /* BindingElement */) { + name_25 = node.name; variableDeclarationNode = node; // binding elements are added only for variable declarations // bubble up to the containing variable declaration - while (variableDeclarationNode && variableDeclarationNode.kind !== 199 /* VariableDeclaration */) { + while (variableDeclarationNode && variableDeclarationNode.kind !== 201 /* VariableDeclaration */) { variableDeclarationNode = variableDeclarationNode.parent; } ts.Debug.assert(variableDeclarationNode !== undefined); @@ -31201,24 +32992,24 @@ var ts; else { ts.Debug.assert(!ts.isBindingPattern(node.name)); variableDeclarationNode = node; - name_24 = node.name; + name_25 = node.name; } if (ts.isConst(variableDeclarationNode)) { - return createItem(node, getTextOfNode(name_24), ts.ScriptElementKind.constElement); + return createItem(node, getTextOfNode(name_25), ts.ScriptElementKind.constElement); } else if (ts.isLet(variableDeclarationNode)) { - return createItem(node, getTextOfNode(name_24), ts.ScriptElementKind.letElement); + return createItem(node, getTextOfNode(name_25), ts.ScriptElementKind.letElement); } else { - return createItem(node, getTextOfNode(name_24), ts.ScriptElementKind.variableElement); + return createItem(node, getTextOfNode(name_25), ts.ScriptElementKind.variableElement); } - case 136 /* Constructor */: + case 137 /* Constructor */: return createItem(node, "constructor", ts.ScriptElementKind.constructorImplementationElement); - case 218 /* ExportSpecifier */: - case 214 /* ImportSpecifier */: - case 209 /* ImportEqualsDeclaration */: - case 211 /* ImportClause */: - case 212 /* NamespaceImport */: + case 220 /* ExportSpecifier */: + case 216 /* ImportSpecifier */: + case 211 /* ImportEqualsDeclaration */: + case 213 /* ImportClause */: + case 214 /* NamespaceImport */: return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.alias); } return undefined; @@ -31248,17 +33039,17 @@ var ts; } function createTopLevelItem(node) { switch (node.kind) { - case 228 /* SourceFile */: + case 230 /* SourceFile */: return createSourceFileItem(node); - case 202 /* ClassDeclaration */: + case 204 /* ClassDeclaration */: return createClassItem(node); - case 205 /* EnumDeclaration */: + case 207 /* EnumDeclaration */: return createEnumItem(node); - case 203 /* InterfaceDeclaration */: + case 205 /* InterfaceDeclaration */: return createIterfaceItem(node); - case 206 /* ModuleDeclaration */: + case 208 /* ModuleDeclaration */: return createModuleItem(node); - case 201 /* FunctionDeclaration */: + case 203 /* FunctionDeclaration */: return createFunctionItem(node); } return undefined; @@ -31270,7 +33061,7 @@ var ts; // Otherwise, we need to aggregate each identifier to build up the qualified name. var result = []; result.push(moduleDeclaration.name.text); - while (moduleDeclaration.body && moduleDeclaration.body.kind === 206 /* ModuleDeclaration */) { + while (moduleDeclaration.body && moduleDeclaration.body.kind === 208 /* ModuleDeclaration */) { moduleDeclaration = moduleDeclaration.body; result.push(moduleDeclaration.name.text); } @@ -31282,7 +33073,7 @@ var ts; return getNavigationBarItem(moduleName, ts.ScriptElementKind.moduleElement, ts.getNodeModifiers(node), [getNodeSpan(node)], childItems, getIndent(node)); } function createFunctionItem(node) { - if (node.body && node.body.kind === 180 /* Block */) { + if (node.body && node.body.kind === 182 /* Block */) { var childItems = getItemsWorker(sortNodes(node.body.statements), createChildItem); return getNavigationBarItem(!node.name ? "default" : node.name.text, ts.ScriptElementKind.functionElement, ts.getNodeModifiers(node), [getNodeSpan(node)], childItems, getIndent(node)); } @@ -31303,7 +33094,7 @@ var ts; var childItems; if (node.members) { var constructor = ts.forEach(node.members, function (member) { - return member.kind === 136 /* Constructor */ && member; + return member.kind === 137 /* Constructor */ && member; }); // Add the constructor parameters in as children of the class (for property parameters). // Note that *all non-binding pattern named* parameters will be added to the nodes array, but parameters that @@ -31327,7 +33118,7 @@ var ts; } } function removeComputedProperties(node) { - return ts.filter(node.members, function (member) { return member.name === undefined || member.name.kind !== 128 /* ComputedPropertyName */; }); + return ts.filter(node.members, function (member) { return member.name === undefined || member.name.kind !== 129 /* ComputedPropertyName */; }); } /** * Like removeComputedProperties, but retains the properties with well known symbol names @@ -31336,13 +33127,13 @@ var ts; return ts.filter(node.members, function (member) { return !ts.hasDynamicName(member); }); } function getInnermostModule(node) { - while (node.body.kind === 206 /* ModuleDeclaration */) { + while (node.body.kind === 208 /* ModuleDeclaration */) { node = node.body; } return node; } function getNodeSpan(node) { - return node.kind === 228 /* SourceFile */ + return node.kind === 230 /* SourceFile */ ? ts.createTextSpanFromBounds(node.getFullStart(), node.getEnd()) : ts.createTextSpanFromBounds(node.getStart(), node.getEnd()); } @@ -31857,7 +33648,7 @@ var ts; var hasTransitionFromUpperToLower = transitionFromUpperToLower(identifier, word, i, wordStart); if (charIsPunctuation(identifier.charCodeAt(i - 1)) || charIsPunctuation(identifier.charCodeAt(i)) || - lastIsDigit != currentIsDigit || + lastIsDigit !== currentIsDigit || hasTransitionFromLowerToUpper || hasTransitionFromUpperToLower) { if (!isAllPunctuation(identifier, wordStart, i)) { @@ -31918,7 +33709,7 @@ var ts; // 3) HTMLDocument -> HTML, Document // // etc. - if (index != wordStart && + if (index !== wordStart && index + 1 < identifier.length) { var currentIsUpper = isUpperCaseLetter(identifier.charCodeAt(index)); var nextIsLower = isLowerCaseLetter(identifier.charCodeAt(index + 1)); @@ -32137,7 +33928,7 @@ var ts; } return createSignatureHelpItems(candidates, resolvedSignature, argumentInfo); function createJavaScriptSignatureHelpItems(argumentInfo) { - if (argumentInfo.invocation.kind !== 158 /* CallExpression */) { + if (argumentInfo.invocation.kind !== 160 /* CallExpression */) { return undefined; } // See if we can find some symbol with the call expression name that has call signatures. @@ -32145,7 +33936,7 @@ var ts; var expression = callExpression.expression; var name = expression.kind === 65 /* Identifier */ ? expression - : expression.kind === 156 /* PropertyAccessExpression */ + : expression.kind === 158 /* PropertyAccessExpression */ ? expression.name : undefined; if (!name || !name.text) { @@ -32178,7 +33969,7 @@ var ts; * in the argument of an invocation; returns undefined otherwise. */ function getImmediatelyContainingArgumentInfo(node) { - if (node.parent.kind === 158 /* CallExpression */ || node.parent.kind === 159 /* NewExpression */) { + if (node.parent.kind === 160 /* CallExpression */ || node.parent.kind === 161 /* NewExpression */) { var callExpression = node.parent; // There are 3 cases to handle: // 1. The token introduces a list, and should begin a sig help session @@ -32231,25 +34022,25 @@ var ts; }; } } - else if (node.kind === 10 /* NoSubstitutionTemplateLiteral */ && node.parent.kind === 160 /* TaggedTemplateExpression */) { + else if (node.kind === 10 /* NoSubstitutionTemplateLiteral */ && node.parent.kind === 162 /* TaggedTemplateExpression */) { // Check if we're actually inside the template; // otherwise we'll fall out and return undefined. if (ts.isInsideTemplateLiteral(node, position)) { return getArgumentListInfoForTemplate(node.parent, 0); } } - else if (node.kind === 11 /* TemplateHead */ && node.parent.parent.kind === 160 /* TaggedTemplateExpression */) { + else if (node.kind === 11 /* TemplateHead */ && node.parent.parent.kind === 162 /* TaggedTemplateExpression */) { var templateExpression = node.parent; var tagExpression = templateExpression.parent; - ts.Debug.assert(templateExpression.kind === 172 /* TemplateExpression */); + ts.Debug.assert(templateExpression.kind === 174 /* TemplateExpression */); var argumentIndex = ts.isInsideTemplateLiteral(node, position) ? 0 : 1; return getArgumentListInfoForTemplate(tagExpression, argumentIndex); } - else if (node.parent.kind === 178 /* TemplateSpan */ && node.parent.parent.parent.kind === 160 /* TaggedTemplateExpression */) { + else if (node.parent.kind === 180 /* TemplateSpan */ && node.parent.parent.parent.kind === 162 /* TaggedTemplateExpression */) { var templateSpan = node.parent; var templateExpression = templateSpan.parent; var tagExpression = templateExpression.parent; - ts.Debug.assert(templateExpression.kind === 172 /* TemplateExpression */); + ts.Debug.assert(templateExpression.kind === 174 /* TemplateExpression */); // If we're just after a template tail, don't show signature help. if (node.kind === 13 /* TemplateTail */ && !ts.isInsideTemplateLiteral(node, position)) { return undefined; @@ -32367,7 +34158,7 @@ var ts; // // This is because a Missing node has no width. However, what we actually want is to include trivia // leading up to the next token in case the user is about to type in a TemplateMiddle or TemplateTail. - if (template.kind === 172 /* TemplateExpression */) { + if (template.kind === 174 /* TemplateExpression */) { var lastSpan = ts.lastOrUndefined(template.templateSpans); if (lastSpan.literal.getFullWidth() === 0) { applicableSpanEnd = ts.skipTrivia(sourceFile.text, applicableSpanEnd, false); @@ -32376,7 +34167,7 @@ var ts; return ts.createTextSpan(applicableSpanStart, applicableSpanEnd - applicableSpanStart); } function getContainingArgumentInfo(node) { - for (var n = node; n.kind !== 228 /* SourceFile */; n = n.parent) { + for (var n = node; n.kind !== 230 /* SourceFile */; n = n.parent) { if (ts.isFunctionBlock(n)) { return undefined; } @@ -32577,40 +34368,40 @@ var ts; return false; } switch (n.kind) { - case 202 /* ClassDeclaration */: - case 203 /* InterfaceDeclaration */: - case 205 /* EnumDeclaration */: - case 155 /* ObjectLiteralExpression */: - case 151 /* ObjectBindingPattern */: - case 146 /* TypeLiteral */: - case 180 /* Block */: - case 207 /* ModuleBlock */: - case 208 /* CaseBlock */: + case 204 /* ClassDeclaration */: + case 205 /* InterfaceDeclaration */: + case 207 /* EnumDeclaration */: + case 157 /* ObjectLiteralExpression */: + case 153 /* ObjectBindingPattern */: + case 148 /* TypeLiteral */: + case 182 /* Block */: + case 209 /* ModuleBlock */: + case 210 /* CaseBlock */: return nodeEndsWith(n, 15 /* CloseBraceToken */, sourceFile); - case 224 /* CatchClause */: + case 226 /* CatchClause */: return isCompletedNode(n.block, sourceFile); - case 159 /* NewExpression */: + case 161 /* NewExpression */: if (!n.arguments) { return true; } // fall through - case 158 /* CallExpression */: - case 162 /* ParenthesizedExpression */: - case 150 /* ParenthesizedType */: + case 160 /* CallExpression */: + case 164 /* ParenthesizedExpression */: + case 152 /* ParenthesizedType */: return nodeEndsWith(n, 17 /* CloseParenToken */, sourceFile); - case 143 /* FunctionType */: - case 144 /* ConstructorType */: + case 145 /* FunctionType */: + case 146 /* ConstructorType */: return isCompletedNode(n.type, sourceFile); - case 136 /* Constructor */: - case 137 /* GetAccessor */: - case 138 /* SetAccessor */: - case 201 /* FunctionDeclaration */: - case 163 /* FunctionExpression */: - case 135 /* MethodDeclaration */: - case 134 /* MethodSignature */: - case 140 /* ConstructSignature */: - case 139 /* CallSignature */: - case 164 /* ArrowFunction */: + case 137 /* Constructor */: + case 138 /* GetAccessor */: + case 139 /* SetAccessor */: + case 203 /* FunctionDeclaration */: + case 165 /* FunctionExpression */: + case 136 /* MethodDeclaration */: + case 135 /* MethodSignature */: + case 141 /* ConstructSignature */: + case 140 /* CallSignature */: + case 166 /* ArrowFunction */: if (n.body) { return isCompletedNode(n.body, sourceFile); } @@ -32620,63 +34411,63 @@ var ts; // Even though type parameters can be unclosed, we can get away with // having at least a closing paren. return hasChildOfKind(n, 17 /* CloseParenToken */, sourceFile); - case 206 /* ModuleDeclaration */: + case 208 /* ModuleDeclaration */: return n.body && isCompletedNode(n.body, sourceFile); - case 184 /* IfStatement */: + case 186 /* IfStatement */: if (n.elseStatement) { return isCompletedNode(n.elseStatement, sourceFile); } return isCompletedNode(n.thenStatement, sourceFile); - case 183 /* ExpressionStatement */: + case 185 /* ExpressionStatement */: return isCompletedNode(n.expression, sourceFile); - case 154 /* ArrayLiteralExpression */: - case 152 /* ArrayBindingPattern */: - case 157 /* ElementAccessExpression */: - case 128 /* ComputedPropertyName */: - case 148 /* TupleType */: + case 156 /* ArrayLiteralExpression */: + case 154 /* ArrayBindingPattern */: + case 159 /* ElementAccessExpression */: + case 129 /* ComputedPropertyName */: + case 150 /* TupleType */: return nodeEndsWith(n, 19 /* CloseBracketToken */, sourceFile); - case 141 /* IndexSignature */: + case 142 /* IndexSignature */: if (n.type) { return isCompletedNode(n.type, sourceFile); } return hasChildOfKind(n, 19 /* CloseBracketToken */, sourceFile); - case 221 /* CaseClause */: - case 222 /* DefaultClause */: + case 223 /* CaseClause */: + case 224 /* DefaultClause */: // there is no such thing as terminator token for CaseClause/DefaultClause so for simplicitly always consider them non-completed return false; - case 187 /* ForStatement */: - case 188 /* ForInStatement */: - case 189 /* ForOfStatement */: - case 186 /* WhileStatement */: + case 189 /* ForStatement */: + case 190 /* ForInStatement */: + case 191 /* ForOfStatement */: + case 188 /* WhileStatement */: return isCompletedNode(n.statement, sourceFile); - case 185 /* DoStatement */: + case 187 /* DoStatement */: // rough approximation: if DoStatement has While keyword - then if node is completed is checking the presence of ')'; var hasWhileKeyword = findChildOfKind(n, 100 /* WhileKeyword */, sourceFile); if (hasWhileKeyword) { return nodeEndsWith(n, 17 /* CloseParenToken */, sourceFile); } return isCompletedNode(n.statement, sourceFile); - case 145 /* TypeQuery */: + case 147 /* TypeQuery */: return isCompletedNode(n.exprName, sourceFile); - case 166 /* TypeOfExpression */: - case 165 /* DeleteExpression */: - case 167 /* VoidExpression */: - case 173 /* YieldExpression */: - case 174 /* SpreadElementExpression */: + case 168 /* TypeOfExpression */: + case 167 /* DeleteExpression */: + case 169 /* VoidExpression */: + case 175 /* YieldExpression */: + case 176 /* SpreadElementExpression */: var unaryWordExpression = n; return isCompletedNode(unaryWordExpression.expression, sourceFile); - case 160 /* TaggedTemplateExpression */: + case 162 /* TaggedTemplateExpression */: return isCompletedNode(n.template, sourceFile); - case 172 /* TemplateExpression */: + case 174 /* TemplateExpression */: var lastSpan = ts.lastOrUndefined(n.templateSpans); return isCompletedNode(lastSpan, sourceFile); - case 178 /* TemplateSpan */: + case 180 /* TemplateSpan */: return ts.nodeIsPresent(n.literal); - case 168 /* PrefixUnaryExpression */: + case 170 /* PrefixUnaryExpression */: return isCompletedNode(n.operand, sourceFile); - case 170 /* BinaryExpression */: + case 172 /* BinaryExpression */: return isCompletedNode(n.right, sourceFile); - case 171 /* ConditionalExpression */: + case 173 /* ConditionalExpression */: return isCompletedNode(n.whenFalse, sourceFile); default: return true; @@ -32732,7 +34523,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 === 229 /* SyntaxList */ && c.pos <= node.pos && c.end >= node.end) { + if (c.kind === 253 /* SyntaxList */ && c.pos <= node.pos && c.end >= node.end) { return c; } }); @@ -32866,7 +34657,7 @@ var ts; } } } - ts.Debug.assert(startNode !== undefined || n.kind === 228 /* SourceFile */); + ts.Debug.assert(startNode !== undefined || n.kind === 230 /* SourceFile */); // 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. @@ -32910,17 +34701,17 @@ var ts; } ts.getNodeModifiers = getNodeModifiers; function getTypeArgumentOrTypeParameterList(node) { - if (node.kind === 142 /* TypeReference */ || node.kind === 158 /* CallExpression */) { + if (node.kind === 144 /* TypeReference */ || node.kind === 160 /* CallExpression */) { return node.typeArguments; } - if (ts.isFunctionLike(node) || node.kind === 202 /* ClassDeclaration */ || node.kind === 203 /* InterfaceDeclaration */) { + if (ts.isFunctionLike(node) || node.kind === 204 /* ClassDeclaration */ || node.kind === 205 /* InterfaceDeclaration */) { return node.typeParameters; } return undefined; } ts.getTypeArgumentOrTypeParameterList = getTypeArgumentOrTypeParameterList; function isToken(n) { - return n.kind >= 0 /* FirstToken */ && n.kind <= 126 /* LastToken */; + return n.kind >= 0 /* FirstToken */ && n.kind <= 127 /* LastToken */; } ts.isToken = isToken; function isWord(kind) { @@ -32975,7 +34766,7 @@ var ts; var ts; (function (ts) { function isFirstDeclarationOfSymbolParameter(symbol) { - return symbol.declarations && symbol.declarations.length > 0 && symbol.declarations[0].kind === 130 /* Parameter */; + return symbol.declarations && symbol.declarations.length > 0 && symbol.declarations[0].kind === 131 /* Parameter */; } ts.isFirstDeclarationOfSymbolParameter = isFirstDeclarationOfSymbolParameter; var displayPartWriter = getDisplayPartWriter(); @@ -33139,10 +34930,6 @@ var ts; }); } ts.signatureToDisplayParts = signatureToDisplayParts; - function isJavaScript(fileName) { - return ts.fileExtensionIs(fileName, ".js"); - } - ts.isJavaScript = isJavaScript; })(ts || (ts = {})); /// /// @@ -33392,7 +35179,7 @@ var ts; if (this.tokensAreOnSameLine === undefined) { var startLine = this.sourceFile.getLineAndCharacterOfPosition(this.currentTokenSpan.pos).line; var endLine = this.sourceFile.getLineAndCharacterOfPosition(this.nextTokenSpan.pos).line; - this.tokensAreOnSameLine = (startLine == endLine); + this.tokensAreOnSameLine = (startLine === endLine); } return this.tokensAreOnSameLine; }; @@ -33411,7 +35198,7 @@ var ts; FormattingContext.prototype.NodeIsOnOneLine = function (node) { var startLine = this.sourceFile.getLineAndCharacterOfPosition(node.getStart(this.sourceFile)).line; var endLine = this.sourceFile.getLineAndCharacterOfPosition(node.getEnd()).line; - return startLine == endLine; + return startLine === endLine; }; FormattingContext.prototype.BlockIsOnOneLine = function (node) { var openBrace = ts.findChildOfKind(node, 14 /* OpenBraceToken */, this.sourceFile); @@ -33571,7 +35358,7 @@ var ts; this.customContextChecks = funcs; } RuleOperationContext.prototype.IsAny = function () { - return this == RuleOperationContext.Any; + return this === RuleOperationContext.Any; }; RuleOperationContext.prototype.InContext = function (context) { if (this.IsAny()) { @@ -33625,7 +35412,7 @@ var ts; this.NoSpaceBeforeOpenBracket = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 18 /* OpenBracketToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8 /* Delete */)); this.NoSpaceAfterOpenBracket = new formatting.Rule(formatting.RuleDescriptor.create3(18 /* OpenBracketToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8 /* Delete */)); this.NoSpaceBeforeCloseBracket = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 19 /* CloseBracketToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8 /* Delete */)); - this.NoSpaceAfterCloseBracket = new formatting.Rule(formatting.RuleDescriptor.create3(19 /* CloseBracketToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8 /* Delete */)); + this.NoSpaceAfterCloseBracket = new formatting.Rule(formatting.RuleDescriptor.create3(19 /* CloseBracketToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, 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, 14 /* OpenBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext, Rules.IsBeforeBlockContext, Rules.IsNotFormatOnEnter, Rules.IsSameLineTokenOrBeforeMultilineBlockContext), 2 /* Space */), 1 /* CanDeleteNewLines */); @@ -33677,7 +35464,7 @@ var ts; this.SpaceAfterTryFinally = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.FromTokens([96 /* TryKeyword */, 81 /* FinallyKeyword */]), 14 /* OpenBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 2 /* Space */)); // get x() {} // set x(val) {} - this.SpaceAfterGetSetInMember = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.FromTokens([116 /* GetKeyword */, 121 /* SetKeyword */]), 65 /* Identifier */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext), 2 /* Space */)); + this.SpaceAfterGetSetInMember = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.FromTokens([116 /* GetKeyword */, 122 /* SetKeyword */]), 65 /* Identifier */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext), 2 /* Space */)); // Special case for binary operators (that are keywords). For these we have to add a space and shouldn't follow any user options. this.SpaceBeforeBinaryKeywordOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.BinaryKeywordOperators), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsBinaryOpContext), 2 /* Space */)); this.SpaceAfterBinaryKeywordOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.BinaryKeywordOperators, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsBinaryOpContext), 2 /* Space */)); @@ -33685,9 +35472,9 @@ var ts; // Treat constructor as an identifier in a function declaration, and remove spaces between constructor and following left parentheses this.NoSpaceAfterConstructor = new formatting.Rule(formatting.RuleDescriptor.create1(114 /* ConstructorKeyword */, 16 /* OpenParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8 /* Delete */)); // Use of module as a function call. e.g.: import m2 = module("m2"); - this.NoSpaceAfterModuleImport = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.FromTokens([117 /* ModuleKeyword */, 119 /* RequireKeyword */]), 16 /* OpenParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8 /* Delete */)); + this.NoSpaceAfterModuleImport = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.FromTokens([118 /* ModuleKeyword */, 120 /* RequireKeyword */]), 16 /* OpenParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8 /* Delete */)); // Add a space around certain TypeScript keywords - this.SpaceAfterCertainTypeScriptKeywords = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([69 /* ClassKeyword */, 115 /* DeclareKeyword */, 77 /* EnumKeyword */, 78 /* ExportKeyword */, 79 /* ExtendsKeyword */, 116 /* GetKeyword */, 102 /* ImplementsKeyword */, 85 /* ImportKeyword */, 103 /* InterfaceKeyword */, 117 /* ModuleKeyword */, 118 /* NamespaceKeyword */, 106 /* PrivateKeyword */, 108 /* PublicKeyword */, 121 /* SetKeyword */, 109 /* StaticKeyword */]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 2 /* Space */)); + this.SpaceAfterCertainTypeScriptKeywords = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([69 /* ClassKeyword */, 115 /* DeclareKeyword */, 77 /* EnumKeyword */, 78 /* ExportKeyword */, 79 /* ExtendsKeyword */, 116 /* GetKeyword */, 102 /* ImplementsKeyword */, 85 /* ImportKeyword */, 103 /* InterfaceKeyword */, 118 /* ModuleKeyword */, 119 /* NamespaceKeyword */, 106 /* PrivateKeyword */, 108 /* PublicKeyword */, 122 /* SetKeyword */, 109 /* StaticKeyword */]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 2 /* Space */)); this.SpaceBeforeCertainTypeScriptKeywords = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.FromTokens([79 /* ExtendsKeyword */, 102 /* ImplementsKeyword */])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 2 /* Space */)); // Treat string literals in module names as identifiers, and add a space between the literal and the opening Brace braces, e.g.: module "m2" { this.SpaceAfterModuleName = new formatting.Rule(formatting.RuleDescriptor.create1(8 /* StringLiteral */, 14 /* OpenBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsModuleDeclContext), 2 /* Space */)); @@ -33707,7 +35494,11 @@ var ts; // decorators this.SpaceBeforeAt = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 52 /* AtToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 2 /* Space */)); this.NoSpaceAfterAt = new formatting.Rule(formatting.RuleDescriptor.create3(52 /* AtToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8 /* Delete */)); - this.SpaceAfterDecorator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.FromTokens([65 /* Identifier */, 78 /* ExportKeyword */, 73 /* DefaultKeyword */, 69 /* ClassKeyword */, 109 /* StaticKeyword */, 108 /* PublicKeyword */, 106 /* PrivateKeyword */, 107 /* ProtectedKeyword */, 116 /* GetKeyword */, 121 /* SetKeyword */, 18 /* OpenBracketToken */, 35 /* AsteriskToken */])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsEndOfDecoratorContextOnSameLine), 2 /* Space */)); + this.SpaceAfterDecorator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.FromTokens([65 /* Identifier */, 78 /* ExportKeyword */, 73 /* DefaultKeyword */, 69 /* ClassKeyword */, 109 /* StaticKeyword */, 108 /* PublicKeyword */, 106 /* PrivateKeyword */, 107 /* ProtectedKeyword */, 116 /* GetKeyword */, 122 /* SetKeyword */, 18 /* OpenBracketToken */, 35 /* AsteriskToken */])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsEndOfDecoratorContextOnSameLine), 2 /* Space */)); + this.NoSpaceBetweenFunctionKeywordAndStar = new formatting.Rule(formatting.RuleDescriptor.create1(83 /* FunctionKeyword */, 35 /* AsteriskToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclarationOrFunctionExpressionContext), 8 /* Delete */)); + this.SpaceAfterStarInGeneratorDeclaration = new formatting.Rule(formatting.RuleDescriptor.create3(35 /* AsteriskToken */, formatting.Shared.TokenRange.FromTokens([65 /* Identifier */, 16 /* OpenParenToken */])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclarationOrFunctionExpressionContext), 2 /* Space */)); + this.NoSpaceBetweenYieldKeywordAndStar = new formatting.Rule(formatting.RuleDescriptor.create1(110 /* YieldKeyword */, 35 /* AsteriskToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsYieldOrYieldStarWithOperand), 8 /* Delete */)); + this.SpaceBetweenYieldOrYieldStarAndOperand = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([110 /* YieldKeyword */, 35 /* AsteriskToken */]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsYieldOrYieldStarWithOperand), 2 /* Space */)); // These rules are higher in priority than user-configurable rules. this.HighPriorityCommonRules = [ @@ -33725,7 +35516,9 @@ var ts; this.NoSpaceAfterCloseBrace, this.SpaceAfterOpenBrace, this.SpaceBeforeCloseBrace, this.NewLineBeforeCloseBraceInBlockContext, this.SpaceAfterCloseBrace, this.SpaceBetweenCloseBraceAndElse, this.SpaceBetweenCloseBraceAndWhile, this.NoSpaceBetweenEmptyBraceBrackets, + this.NoSpaceBetweenFunctionKeywordAndStar, this.SpaceAfterStarInGeneratorDeclaration, this.SpaceAfterFunctionInFuncDecl, this.NewLineAfterOpenBraceInBlockContext, this.SpaceAfterGetSetInMember, + this.NoSpaceBetweenYieldKeywordAndStar, this.SpaceBetweenYieldOrYieldStarAndOperand, this.NoSpaceBetweenReturnAndSemicolon, this.SpaceAfterCertainKeywords, this.SpaceAfterLetConstInVariableDeclaration, @@ -33797,9 +35590,9 @@ var ts; } Rules.prototype.getRuleName = function (rule) { var o = this; - for (var name_25 in o) { - if (o[name_25] === rule) { - return name_25; + for (var name_26 in o) { + if (o[name_26] === rule) { + return name_26; } } throw new Error("Unknown rule"); @@ -33808,36 +35601,37 @@ var ts; /// Contexts /// Rules.IsForContext = function (context) { - return context.contextNode.kind === 187 /* ForStatement */; + return context.contextNode.kind === 189 /* ForStatement */; }; Rules.IsNotForContext = function (context) { return !Rules.IsForContext(context); }; Rules.IsBinaryOpContext = function (context) { switch (context.contextNode.kind) { - case 170 /* BinaryExpression */: - case 171 /* ConditionalExpression */: + case 172 /* BinaryExpression */: + case 173 /* ConditionalExpression */: + case 143 /* TypePredicate */: return true; // equals in binding elements: function foo([[x, y] = [1, 2]]) - case 153 /* BindingElement */: + case 155 /* BindingElement */: // equals in type X = ... - case 204 /* TypeAliasDeclaration */: + case 206 /* TypeAliasDeclaration */: // equal in import a = module('a'); - case 209 /* ImportEqualsDeclaration */: + case 211 /* ImportEqualsDeclaration */: // equal in let a = 0; - case 199 /* VariableDeclaration */: + case 201 /* VariableDeclaration */: // equal in p = 0; - case 130 /* Parameter */: - case 227 /* EnumMember */: - case 133 /* PropertyDeclaration */: - case 132 /* PropertySignature */: + case 131 /* Parameter */: + case 229 /* EnumMember */: + case 134 /* PropertyDeclaration */: + case 133 /* PropertySignature */: return context.currentTokenSpan.kind === 53 /* EqualsToken */ || context.nextTokenSpan.kind === 53 /* EqualsToken */; // "in" keyword in for (let x in []) { } - case 188 /* ForInStatement */: + case 190 /* ForInStatement */: return context.currentTokenSpan.kind === 86 /* InKeyword */ || context.nextTokenSpan.kind === 86 /* InKeyword */; // Technically, "of" is not a binary operator, but format it the same way as "in" - case 189 /* ForOfStatement */: - return context.currentTokenSpan.kind === 126 /* OfKeyword */ || context.nextTokenSpan.kind === 126 /* OfKeyword */; + case 191 /* ForOfStatement */: + return context.currentTokenSpan.kind === 127 /* OfKeyword */ || context.nextTokenSpan.kind === 127 /* OfKeyword */; } return false; }; @@ -33845,7 +35639,7 @@ var ts; return !Rules.IsBinaryOpContext(context); }; Rules.IsConditionalOperatorContext = function (context) { - return context.contextNode.kind === 171 /* ConditionalExpression */; + return context.contextNode.kind === 173 /* ConditionalExpression */; }; Rules.IsSameLineTokenOrBeforeMultilineBlockContext = function (context) { //// This check is mainly used inside SpaceBeforeOpenBraceInControl and SpaceBeforeOpenBraceInFunction. @@ -33889,89 +35683,92 @@ var ts; return true; } switch (node.kind) { - case 180 /* Block */: - case 208 /* CaseBlock */: - case 155 /* ObjectLiteralExpression */: - case 207 /* ModuleBlock */: + case 182 /* Block */: + case 210 /* CaseBlock */: + case 157 /* ObjectLiteralExpression */: + case 209 /* ModuleBlock */: return true; } return false; }; Rules.IsFunctionDeclContext = function (context) { switch (context.contextNode.kind) { - case 201 /* FunctionDeclaration */: - case 135 /* MethodDeclaration */: - case 134 /* MethodSignature */: + case 203 /* FunctionDeclaration */: + case 136 /* MethodDeclaration */: + case 135 /* MethodSignature */: //case SyntaxKind.MemberFunctionDeclaration: - case 137 /* GetAccessor */: - case 138 /* SetAccessor */: + case 138 /* GetAccessor */: + case 139 /* SetAccessor */: ///case SyntaxKind.MethodSignature: - case 139 /* CallSignature */: - case 163 /* FunctionExpression */: - case 136 /* Constructor */: - case 164 /* ArrowFunction */: + case 140 /* CallSignature */: + case 165 /* FunctionExpression */: + case 137 /* Constructor */: + case 166 /* ArrowFunction */: //case SyntaxKind.ConstructorDeclaration: //case SyntaxKind.SimpleArrowFunctionExpression: //case SyntaxKind.ParenthesizedArrowFunctionExpression: - case 203 /* InterfaceDeclaration */: + case 205 /* InterfaceDeclaration */: return true; } return false; }; + Rules.IsFunctionDeclarationOrFunctionExpressionContext = function (context) { + return context.contextNode.kind === 203 /* FunctionDeclaration */ || context.contextNode.kind === 165 /* FunctionExpression */; + }; Rules.IsTypeScriptDeclWithBlockContext = function (context) { return Rules.NodeIsTypeScriptDeclWithBlockContext(context.contextNode); }; Rules.NodeIsTypeScriptDeclWithBlockContext = function (node) { switch (node.kind) { - case 202 /* ClassDeclaration */: - case 203 /* InterfaceDeclaration */: - case 205 /* EnumDeclaration */: - case 146 /* TypeLiteral */: - case 206 /* ModuleDeclaration */: + case 204 /* ClassDeclaration */: + case 205 /* InterfaceDeclaration */: + case 207 /* EnumDeclaration */: + case 148 /* TypeLiteral */: + case 208 /* ModuleDeclaration */: return true; } return false; }; Rules.IsAfterCodeBlockContext = function (context) { switch (context.currentTokenParent.kind) { - case 202 /* ClassDeclaration */: - case 206 /* ModuleDeclaration */: - case 205 /* EnumDeclaration */: - case 180 /* Block */: - case 224 /* CatchClause */: - case 207 /* ModuleBlock */: - case 194 /* SwitchStatement */: + case 204 /* ClassDeclaration */: + case 208 /* ModuleDeclaration */: + case 207 /* EnumDeclaration */: + case 182 /* Block */: + case 226 /* CatchClause */: + case 209 /* ModuleBlock */: + case 196 /* SwitchStatement */: return true; } return false; }; Rules.IsControlDeclContext = function (context) { switch (context.contextNode.kind) { - case 184 /* IfStatement */: - case 194 /* SwitchStatement */: - case 187 /* ForStatement */: - case 188 /* ForInStatement */: - case 189 /* ForOfStatement */: - case 186 /* WhileStatement */: - case 197 /* TryStatement */: - case 185 /* DoStatement */: - case 193 /* WithStatement */: + case 186 /* IfStatement */: + case 196 /* SwitchStatement */: + case 189 /* ForStatement */: + case 190 /* ForInStatement */: + case 191 /* ForOfStatement */: + case 188 /* WhileStatement */: + case 199 /* TryStatement */: + case 187 /* DoStatement */: + case 195 /* WithStatement */: // TODO // case SyntaxKind.ElseClause: - case 224 /* CatchClause */: + case 226 /* CatchClause */: return true; default: return false; } }; Rules.IsObjectContext = function (context) { - return context.contextNode.kind === 155 /* ObjectLiteralExpression */; + return context.contextNode.kind === 157 /* ObjectLiteralExpression */; }; Rules.IsFunctionCallContext = function (context) { - return context.contextNode.kind === 158 /* CallExpression */; + return context.contextNode.kind === 160 /* CallExpression */; }; Rules.IsNewContext = function (context) { - return context.contextNode.kind === 159 /* NewExpression */; + return context.contextNode.kind === 161 /* NewExpression */; }; Rules.IsFunctionCallOrNewContext = function (context) { return Rules.IsFunctionCallContext(context) || Rules.IsNewContext(context); @@ -33982,6 +35779,9 @@ var ts; Rules.IsSameLineTokenContext = function (context) { return context.TokensAreOnSameLine(); }; + Rules.IsNotBeforeBlockInFunctionDeclarationContext = function (context) { + return !Rules.IsFunctionDeclContext(context) && !Rules.IsBeforeBlockContext(context); + }; Rules.IsEndOfDecoratorContextOnSameLine = function (context) { return context.TokensAreOnSameLine() && context.contextNode.decorators && @@ -33992,38 +35792,38 @@ var ts; while (ts.isExpression(node)) { node = node.parent; } - return node.kind === 131 /* Decorator */; + return node.kind === 132 /* Decorator */; }; Rules.IsStartOfVariableDeclarationList = function (context) { - return context.currentTokenParent.kind === 200 /* VariableDeclarationList */ && + return context.currentTokenParent.kind === 202 /* VariableDeclarationList */ && context.currentTokenParent.getStart(context.sourceFile) === context.currentTokenSpan.pos; }; Rules.IsNotFormatOnEnter = function (context) { - return context.formattingRequestKind != 2 /* FormatOnEnter */; + return context.formattingRequestKind !== 2 /* FormatOnEnter */; }; Rules.IsModuleDeclContext = function (context) { - return context.contextNode.kind === 206 /* ModuleDeclaration */; + return context.contextNode.kind === 208 /* ModuleDeclaration */; }; Rules.IsObjectTypeContext = function (context) { - return context.contextNode.kind === 146 /* TypeLiteral */; // && context.contextNode.parent.kind !== SyntaxKind.InterfaceDeclaration; + return context.contextNode.kind === 148 /* TypeLiteral */; // && context.contextNode.parent.kind !== SyntaxKind.InterfaceDeclaration; }; Rules.IsTypeArgumentOrParameter = function (token, parent) { if (token.kind !== 24 /* LessThanToken */ && token.kind !== 25 /* GreaterThanToken */) { return false; } switch (parent.kind) { - case 142 /* TypeReference */: - case 202 /* ClassDeclaration */: - case 203 /* InterfaceDeclaration */: - case 201 /* FunctionDeclaration */: - case 163 /* FunctionExpression */: - case 164 /* ArrowFunction */: - case 135 /* MethodDeclaration */: - case 134 /* MethodSignature */: - case 139 /* CallSignature */: - case 140 /* ConstructSignature */: - case 158 /* CallExpression */: - case 159 /* NewExpression */: + case 144 /* TypeReference */: + case 204 /* ClassDeclaration */: + case 205 /* InterfaceDeclaration */: + case 203 /* FunctionDeclaration */: + case 165 /* FunctionExpression */: + case 166 /* ArrowFunction */: + case 136 /* MethodDeclaration */: + case 135 /* MethodSignature */: + case 140 /* CallSignature */: + case 141 /* ConstructSignature */: + case 160 /* CallExpression */: + case 161 /* NewExpression */: return true; default: return false; @@ -34034,7 +35834,10 @@ var ts; Rules.IsTypeArgumentOrParameter(context.nextTokenSpan, context.nextTokenParent); }; Rules.IsVoidOpContext = function (context) { - return context.currentTokenSpan.kind === 99 /* VoidKeyword */ && context.currentTokenParent.kind === 167 /* VoidExpression */; + return context.currentTokenSpan.kind === 99 /* VoidKeyword */ && context.currentTokenParent.kind === 169 /* VoidExpression */; + }; + Rules.IsYieldOrYieldStarWithOperand = function (context) { + return context.contextNode.kind === 175 /* YieldExpression */ && context.contextNode.expression !== undefined; }; return Rules; })(); @@ -34058,7 +35861,7 @@ var ts; return result; }; RulesMap.prototype.Initialize = function (rules) { - this.mapRowLength = 126 /* LastToken */ + 1; + this.mapRowLength = 127 /* LastToken */ + 1; this.map = new Array(this.mapRowLength * this.mapRowLength); //new Array(this.mapRowLength * this.mapRowLength); // This array is used only during construction of the rulesbucket in the map var rulesBucketConstructionStateList = new Array(this.map.length); //new Array(this.map.length); @@ -34078,13 +35881,13 @@ var ts; }; RulesMap.prototype.FillRule = function (rule, rulesBucketConstructionStateList) { var _this = this; - var specificRule = rule.Descriptor.LeftTokenRange != formatting.Shared.TokenRange.Any && - rule.Descriptor.RightTokenRange != formatting.Shared.TokenRange.Any; + var specificRule = rule.Descriptor.LeftTokenRange !== formatting.Shared.TokenRange.Any && + rule.Descriptor.RightTokenRange !== formatting.Shared.TokenRange.Any; rule.Descriptor.LeftTokenRange.GetTokens().forEach(function (left) { rule.Descriptor.RightTokenRange.GetTokens().forEach(function (right) { var rulesBucketIndex = _this.GetRuleBucketIndex(left, right); var rulesBucket = _this.map[rulesBucketIndex]; - if (rulesBucket == undefined) { + if (rulesBucket === undefined) { rulesBucket = _this.map[rulesBucketIndex] = new RulesBucket(); } rulesBucket.AddRule(rule, specificRule, rulesBucketConstructionStateList, rulesBucketIndex); @@ -34151,7 +35954,7 @@ var ts; RulesBucketConstructionState.prototype.IncreaseInsertionIndex = function (maskPosition) { var value = (this.rulesInsertionIndexBitmap >> maskPosition) & Mask; value++; - ts.Debug.assert((value & Mask) == value, "Adding more rules into the sub-bucket than allowed. Maximum allowed is 32 rules."); + ts.Debug.assert((value & Mask) === value, "Adding more rules into the sub-bucket than allowed. Maximum allowed is 32 rules."); var temp = this.rulesInsertionIndexBitmap & ~(Mask << maskPosition); temp |= value << maskPosition; this.rulesInsertionIndexBitmap = temp; @@ -34168,7 +35971,7 @@ var ts; }; RulesBucket.prototype.AddRule = function (rule, specificTokens, constructionState, rulesBucketIndex) { var position; - if (rule.Operation.Action == 1 /* Ignore */) { + if (rule.Operation.Action === 1 /* Ignore */) { position = specificTokens ? RulesPosition.IgnoreRulesSpecific : RulesPosition.IgnoreRulesAny; @@ -34243,7 +36046,7 @@ var ts; return [this.token]; }; TokenSingleValueAccess.prototype.Contains = function (tokenValue) { - return tokenValue == this.token; + return tokenValue === this.token; }; return TokenSingleValueAccess; })(); @@ -34253,7 +36056,7 @@ var ts; } TokenAllAccess.prototype.GetTokens = function () { var result = []; - for (var token = 0 /* FirstToken */; token <= 126 /* LastToken */; token++) { + for (var token = 0 /* FirstToken */; token <= 127 /* LastToken */; token++) { result.push(token); } return result; @@ -34295,9 +36098,9 @@ var ts; }; TokenRange.Any = TokenRange.AllTokens(); TokenRange.AnyIncludingMultilineComments = TokenRange.FromTokens(TokenRange.Any.GetTokens().concat([3 /* MultiLineCommentTrivia */])); - TokenRange.Keywords = TokenRange.FromRange(66 /* FirstKeyword */, 126 /* LastKeyword */); + TokenRange.Keywords = TokenRange.FromRange(66 /* FirstKeyword */, 127 /* LastKeyword */); TokenRange.BinaryOperators = TokenRange.FromRange(24 /* FirstBinaryOperator */, 64 /* LastBinaryOperator */); - TokenRange.BinaryKeywordOperators = TokenRange.FromTokens([86 /* InKeyword */, 87 /* InstanceOfKeyword */, 126 /* OfKeyword */]); + TokenRange.BinaryKeywordOperators = TokenRange.FromTokens([86 /* InKeyword */, 87 /* InstanceOfKeyword */, 127 /* OfKeyword */, 117 /* IsKeyword */]); TokenRange.UnaryPrefixOperators = TokenRange.FromTokens([38 /* PlusPlusToken */, 39 /* MinusMinusToken */, 47 /* TildeToken */, 46 /* ExclamationToken */]); TokenRange.UnaryPrefixExpressions = TokenRange.FromTokens([7 /* NumericLiteral */, 65 /* Identifier */, 16 /* OpenParenToken */, 18 /* OpenBracketToken */, 14 /* OpenBraceToken */, 93 /* ThisKeyword */, 88 /* NewKeyword */]); TokenRange.UnaryPreincrementExpressions = TokenRange.FromTokens([65 /* Identifier */, 16 /* OpenParenToken */, 93 /* ThisKeyword */, 88 /* NewKeyword */]); @@ -34305,7 +36108,7 @@ var ts; TokenRange.UnaryPredecrementExpressions = TokenRange.FromTokens([65 /* Identifier */, 16 /* OpenParenToken */, 93 /* ThisKeyword */, 88 /* NewKeyword */]); TokenRange.UnaryPostdecrementExpressions = TokenRange.FromTokens([65 /* Identifier */, 17 /* CloseParenToken */, 19 /* CloseBracketToken */, 88 /* NewKeyword */]); TokenRange.Comments = TokenRange.FromTokens([2 /* SingleLineCommentTrivia */, 3 /* MultiLineCommentTrivia */]); - TokenRange.TypeNames = TokenRange.FromTokens([65 /* Identifier */, 120 /* NumberKeyword */, 122 /* StringKeyword */, 113 /* BooleanKeyword */, 123 /* SymbolKeyword */, 99 /* VoidKeyword */, 112 /* AnyKeyword */]); + TokenRange.TypeNames = TokenRange.FromTokens([65 /* Identifier */, 121 /* NumberKeyword */, 123 /* StringKeyword */, 113 /* BooleanKeyword */, 124 /* SymbolKeyword */, 99 /* VoidKeyword */, 112 /* AnyKeyword */]); return TokenRange; })(); Shared.TokenRange = TokenRange; @@ -34344,6 +36147,7 @@ var ts; return this.rulesMap; }; RulesProvider.prototype.ensureUpToDate = function (options) { + // TODO: Should this be '==='? if (this.options == null || !ts.compareDataObjects(this.options, options)) { var activeRules = this.createActiveRules(options); var rulesMap = formatting.RulesMap.create(activeRules); @@ -34508,17 +36312,17 @@ var ts; // i.e. parent is class declaration with the list of members and node is one of members. function isListElement(parent, node) { switch (parent.kind) { - case 202 /* ClassDeclaration */: - case 203 /* InterfaceDeclaration */: + case 204 /* ClassDeclaration */: + case 205 /* InterfaceDeclaration */: return ts.rangeContainsRange(parent.members, node); - case 206 /* ModuleDeclaration */: + case 208 /* ModuleDeclaration */: var body = parent.body; - return body && body.kind === 180 /* Block */ && ts.rangeContainsRange(body.statements, node); - case 228 /* SourceFile */: - case 180 /* Block */: - case 207 /* ModuleBlock */: + return body && body.kind === 182 /* Block */ && ts.rangeContainsRange(body.statements, node); + case 230 /* SourceFile */: + case 182 /* Block */: + case 209 /* ModuleBlock */: return ts.rangeContainsRange(parent.statements, node); - case 224 /* CatchClause */: + case 226 /* CatchClause */: return ts.rangeContainsRange(parent.block.statements, node); } return false; @@ -34691,9 +36495,9 @@ var ts; // - source file // - switch\default clauses if (isSomeBlock(parent.kind) || - parent.kind === 228 /* SourceFile */ || - parent.kind === 221 /* CaseClause */ || - parent.kind === 222 /* DefaultClause */) { + parent.kind === 230 /* SourceFile */ || + parent.kind === 223 /* CaseClause */ || + parent.kind === 224 /* DefaultClause */) { indentation = parentDynamicIndentation.getIndentation() + parentDynamicIndentation.getDelta(); } else { @@ -34729,19 +36533,19 @@ var ts; return node.modifiers[0].kind; } switch (node.kind) { - case 202 /* ClassDeclaration */: return 69 /* ClassKeyword */; - case 203 /* InterfaceDeclaration */: return 103 /* InterfaceKeyword */; - case 201 /* FunctionDeclaration */: return 83 /* FunctionKeyword */; - case 205 /* EnumDeclaration */: return 205 /* EnumDeclaration */; - case 137 /* GetAccessor */: return 116 /* GetKeyword */; - case 138 /* SetAccessor */: return 121 /* SetKeyword */; - case 135 /* MethodDeclaration */: + case 204 /* ClassDeclaration */: return 69 /* ClassKeyword */; + case 205 /* InterfaceDeclaration */: return 103 /* InterfaceKeyword */; + case 203 /* FunctionDeclaration */: return 83 /* FunctionKeyword */; + case 207 /* EnumDeclaration */: return 207 /* EnumDeclaration */; + case 138 /* GetAccessor */: return 116 /* GetKeyword */; + case 139 /* SetAccessor */: return 122 /* SetKeyword */; + case 136 /* MethodDeclaration */: if (node.asteriskToken) { return 35 /* AsteriskToken */; } // fall-through - case 133 /* PropertyDeclaration */: - case 130 /* Parameter */: + case 134 /* PropertyDeclaration */: + case 131 /* Parameter */: return node.name.kind; } } @@ -34874,7 +36678,7 @@ var ts; consumeTokenAndAdvanceScanner(tokenInfo, node, parentDynamicIndentation); return inheritedIndentation; } - var effectiveParentStartLine = child.kind === 131 /* Decorator */ ? childStartLine : undecoratedParentStartLine; + var effectiveParentStartLine = child.kind === 132 /* Decorator */ ? childStartLine : undecoratedParentStartLine; var childIndentation = computeIndentation(child, childStartLine, childIndentationAmount, node, parentDynamicIndentation, effectiveParentStartLine); processNode(child, childContextNode, childStartLine, undecoratedChildStartLine, childIndentation.indentation, childIndentation.delta); childContextNode = node; @@ -35197,20 +37001,20 @@ var ts; } function isSomeBlock(kind) { switch (kind) { - case 180 /* Block */: - case 207 /* ModuleBlock */: + case 182 /* Block */: + case 209 /* ModuleBlock */: return true; } return false; } function getOpenTokenForList(node, list) { switch (node.kind) { - case 136 /* Constructor */: - case 201 /* FunctionDeclaration */: - case 163 /* FunctionExpression */: - case 135 /* MethodDeclaration */: - case 134 /* MethodSignature */: - case 164 /* ArrowFunction */: + case 137 /* Constructor */: + case 203 /* FunctionDeclaration */: + case 165 /* FunctionExpression */: + case 136 /* MethodDeclaration */: + case 135 /* MethodSignature */: + case 166 /* ArrowFunction */: if (node.typeParameters === list) { return 24 /* LessThanToken */; } @@ -35218,8 +37022,8 @@ var ts; return 16 /* OpenParenToken */; } break; - case 158 /* CallExpression */: - case 159 /* NewExpression */: + case 160 /* CallExpression */: + case 161 /* NewExpression */: if (node.typeArguments === list) { return 24 /* LessThanToken */; } @@ -35227,7 +37031,7 @@ var ts; return 16 /* OpenParenToken */; } break; - case 142 /* TypeReference */: + case 144 /* TypeReference */: if (node.typeArguments === list) { return 24 /* LessThanToken */; } @@ -35326,7 +37130,7 @@ var ts; return 0; } var lineAtPosition = sourceFile.getLineAndCharacterOfPosition(position).line; - if (precedingToken.kind === 23 /* CommaToken */ && precedingToken.parent.kind !== 170 /* BinaryExpression */) { + if (precedingToken.kind === 23 /* CommaToken */ && precedingToken.parent.kind !== 172 /* BinaryExpression */) { // previous token is comma that separates items in list - find the previous item and try to derive indentation from it var actualIndentation = getActualIndentationForListItemBeforeComma(precedingToken, sourceFile, options); if (actualIndentation !== -1 /* Unknown */) { @@ -35437,7 +37241,7 @@ var ts; // - parent is SourceFile - by default immediate children of SourceFile are not indented except when user indents them manually // - parent and child are not on the same line var useActualIndentation = (ts.isDeclaration(current) || ts.isStatement(current)) && - (parent.kind === 228 /* SourceFile */ || !parentAndChildShareLine); + (parent.kind === 230 /* SourceFile */ || !parentAndChildShareLine); if (!useActualIndentation) { return -1 /* Unknown */; } @@ -35470,7 +37274,7 @@ var ts; return sourceFile.getLineAndCharacterOfPosition(n.getStart(sourceFile)); } function childStartsOnTheSameLineWithElseInIfStatement(parent, child, childStartLine, sourceFile) { - if (parent.kind === 184 /* IfStatement */ && parent.elseStatement === child) { + if (parent.kind === 186 /* IfStatement */ && parent.elseStatement === child) { var elseKeyword = ts.findChildOfKind(parent, 76 /* ElseKeyword */, sourceFile); ts.Debug.assert(elseKeyword !== undefined); var elseKeywordStartLine = getStartLineAndCharacterForNode(elseKeyword, sourceFile).line; @@ -35482,23 +37286,23 @@ var ts; function getContainingList(node, sourceFile) { if (node.parent) { switch (node.parent.kind) { - case 142 /* TypeReference */: + case 144 /* TypeReference */: if (node.parent.typeArguments && ts.rangeContainsStartEnd(node.parent.typeArguments, node.getStart(sourceFile), node.getEnd())) { return node.parent.typeArguments; } break; - case 155 /* ObjectLiteralExpression */: + case 157 /* ObjectLiteralExpression */: return node.parent.properties; - case 154 /* ArrayLiteralExpression */: + case 156 /* ArrayLiteralExpression */: return node.parent.elements; - case 201 /* FunctionDeclaration */: - case 163 /* FunctionExpression */: - case 164 /* ArrowFunction */: - case 135 /* MethodDeclaration */: - case 134 /* MethodSignature */: - case 139 /* CallSignature */: - case 140 /* ConstructSignature */: { + case 203 /* FunctionDeclaration */: + case 165 /* FunctionExpression */: + case 166 /* ArrowFunction */: + case 136 /* MethodDeclaration */: + case 135 /* MethodSignature */: + case 140 /* CallSignature */: + case 141 /* ConstructSignature */: { var start = node.getStart(sourceFile); if (node.parent.typeParameters && ts.rangeContainsStartEnd(node.parent.typeParameters, start, node.getEnd())) { @@ -35509,8 +37313,8 @@ var ts; } break; } - case 159 /* NewExpression */: - case 158 /* CallExpression */: { + case 161 /* NewExpression */: + case 160 /* CallExpression */: { var start = node.getStart(sourceFile); if (node.parent.typeArguments && ts.rangeContainsStartEnd(node.parent.typeArguments, start, node.getEnd())) { @@ -35589,28 +37393,28 @@ var ts; SmartIndenter.findFirstNonWhitespaceColumn = findFirstNonWhitespaceColumn; function nodeContentIsAlwaysIndented(kind) { switch (kind) { - case 202 /* ClassDeclaration */: - case 203 /* InterfaceDeclaration */: - case 205 /* EnumDeclaration */: - case 154 /* ArrayLiteralExpression */: - case 180 /* Block */: - case 207 /* ModuleBlock */: - case 155 /* ObjectLiteralExpression */: - case 146 /* TypeLiteral */: - case 148 /* TupleType */: - case 208 /* CaseBlock */: - case 222 /* DefaultClause */: - case 221 /* CaseClause */: - case 162 /* ParenthesizedExpression */: - case 158 /* CallExpression */: - case 159 /* NewExpression */: - case 181 /* VariableStatement */: - case 199 /* VariableDeclaration */: - case 215 /* ExportAssignment */: - case 192 /* ReturnStatement */: - case 171 /* ConditionalExpression */: - case 152 /* ArrayBindingPattern */: - case 151 /* ObjectBindingPattern */: + case 204 /* ClassDeclaration */: + case 205 /* InterfaceDeclaration */: + case 207 /* EnumDeclaration */: + case 156 /* ArrayLiteralExpression */: + case 182 /* Block */: + case 209 /* ModuleBlock */: + case 157 /* ObjectLiteralExpression */: + case 148 /* TypeLiteral */: + case 150 /* TupleType */: + case 210 /* CaseBlock */: + case 224 /* DefaultClause */: + case 223 /* CaseClause */: + case 164 /* ParenthesizedExpression */: + case 160 /* CallExpression */: + case 161 /* NewExpression */: + case 183 /* VariableStatement */: + case 201 /* VariableDeclaration */: + case 217 /* ExportAssignment */: + case 194 /* ReturnStatement */: + case 173 /* ConditionalExpression */: + case 154 /* ArrayBindingPattern */: + case 153 /* ObjectBindingPattern */: return true; } return false; @@ -35620,22 +37424,22 @@ var ts; return true; } switch (parent) { - case 185 /* DoStatement */: - case 186 /* WhileStatement */: - case 188 /* ForInStatement */: - case 189 /* ForOfStatement */: - case 187 /* ForStatement */: - case 184 /* IfStatement */: - case 201 /* FunctionDeclaration */: - case 163 /* FunctionExpression */: - case 135 /* MethodDeclaration */: - case 134 /* MethodSignature */: - case 139 /* CallSignature */: - case 164 /* ArrowFunction */: - case 136 /* Constructor */: - case 137 /* GetAccessor */: - case 138 /* SetAccessor */: - return child !== 180 /* Block */; + case 187 /* DoStatement */: + case 188 /* WhileStatement */: + case 190 /* ForInStatement */: + case 191 /* ForOfStatement */: + case 189 /* ForStatement */: + case 186 /* IfStatement */: + case 203 /* FunctionDeclaration */: + case 165 /* FunctionExpression */: + case 136 /* MethodDeclaration */: + case 135 /* MethodSignature */: + case 140 /* CallSignature */: + case 166 /* ArrowFunction */: + case 137 /* Constructor */: + case 138 /* GetAccessor */: + case 139 /* SetAccessor */: + return child !== 182 /* Block */; default: return false; } @@ -35648,8 +37452,7 @@ var ts; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; /// /// @@ -35718,7 +37521,7 @@ var ts; return this.getEnd() - this.getStart(sourceFile); }; NodeObject.prototype.getFullWidth = function () { - return this.end - this.getFullStart(); + return this.end - this.pos; }; NodeObject.prototype.getLeadingTriviaWidth = function (sourceFile) { return this.getStart(sourceFile) - this.pos; @@ -35740,7 +37543,7 @@ var ts; return pos; }; NodeObject.prototype.createSyntaxList = function (nodes) { - var list = createNode(229 /* SyntaxList */, nodes.pos, nodes.end, 1024 /* Synthetic */, this); + var list = createNode(253 /* SyntaxList */, nodes.pos, nodes.end, 1024 /* Synthetic */, this); list._children = []; var pos = nodes.pos; for (var _i = 0; _i < nodes.length; _i++) { @@ -35759,7 +37562,7 @@ var ts; NodeObject.prototype.createChildren = function (sourceFile) { var _this = this; var children; - if (this.kind >= 127 /* FirstNode */) { + if (this.kind >= 128 /* FirstNode */) { scanner.setText((sourceFile || this.getSourceFile()).text); children = []; var pos = this.pos; @@ -35804,7 +37607,7 @@ var ts; var children = this.getChildren(); for (var _i = 0; _i < children.length; _i++) { var child = children[_i]; - if (child.kind < 127 /* FirstNode */) { + if (child.kind < 128 /* FirstNode */) { return child; } return child.getFirstToken(sourceFile); @@ -35814,7 +37617,7 @@ var ts; var children = this.getChildren(sourceFile); for (var i = children.length - 1; i >= 0; i--) { var child = children[i]; - if (child.kind < 127 /* FirstNode */) { + if (child.kind < 128 /* FirstNode */) { return child; } return child.getLastToken(sourceFile); @@ -35867,7 +37670,7 @@ var ts; if (ts.indexOf(declarations, declaration) === indexOfDeclaration) { var sourceFileOfDeclaration = ts.getSourceFileOfNode(declaration); // If it is parameter - try and get the jsDoc comment with @param tag from function declaration's jsDoc comments - if (canUseParsedParamTagComments && declaration.kind === 130 /* Parameter */) { + if (canUseParsedParamTagComments && declaration.kind === 131 /* Parameter */) { ts.forEach(getJsDocCommentTextRange(declaration.parent, sourceFileOfDeclaration), function (jsDocCommentTextRange) { var cleanedParamJsDocComment = getCleanedParamJsDocComment(jsDocCommentTextRange.pos, jsDocCommentTextRange.end, sourceFileOfDeclaration); if (cleanedParamJsDocComment) { @@ -35876,15 +37679,15 @@ var ts; }); } // If this is left side of dotted module declaration, there is no doc comments associated with this node - if (declaration.kind === 206 /* ModuleDeclaration */ && declaration.body.kind === 206 /* ModuleDeclaration */) { + if (declaration.kind === 208 /* ModuleDeclaration */ && declaration.body.kind === 208 /* ModuleDeclaration */) { return; } // If this is dotted module name, get the doc comments from the parent - while (declaration.kind === 206 /* ModuleDeclaration */ && declaration.parent.kind === 206 /* ModuleDeclaration */) { + while (declaration.kind === 208 /* ModuleDeclaration */ && declaration.parent.kind === 208 /* ModuleDeclaration */) { declaration = declaration.parent; } // Get the cleaned js doc comment text from the declaration - ts.forEach(getJsDocCommentTextRange(declaration.kind === 199 /* VariableDeclaration */ ? declaration.parent.parent : declaration, sourceFileOfDeclaration), function (jsDocCommentTextRange) { + ts.forEach(getJsDocCommentTextRange(declaration.kind === 201 /* VariableDeclaration */ ? declaration.parent.parent : declaration, sourceFileOfDeclaration), function (jsDocCommentTextRange) { var cleanedJsDocComment = getCleanedJsDocComment(jsDocCommentTextRange.pos, jsDocCommentTextRange.end, sourceFileOfDeclaration); if (cleanedJsDocComment) { jsDocCommentParts.push.apply(jsDocCommentParts, cleanedJsDocComment); @@ -36223,9 +38026,9 @@ var ts; if (result_2 !== undefined) { return result_2; } - if (declaration.name.kind === 128 /* ComputedPropertyName */) { + if (declaration.name.kind === 129 /* ComputedPropertyName */) { var expr = declaration.name.expression; - if (expr.kind === 156 /* PropertyAccessExpression */) { + if (expr.kind === 158 /* PropertyAccessExpression */) { return expr.name.text; } return getTextOfIdentifierOrLiteral(expr); @@ -36245,9 +38048,9 @@ var ts; } function visit(node) { switch (node.kind) { - case 201 /* FunctionDeclaration */: - case 135 /* MethodDeclaration */: - case 134 /* MethodSignature */: + case 203 /* FunctionDeclaration */: + case 136 /* MethodDeclaration */: + case 135 /* MethodSignature */: var functionDeclaration = node; var declarationName = getDeclarationName(functionDeclaration); if (declarationName) { @@ -36267,60 +38070,60 @@ var ts; ts.forEachChild(node, visit); } break; - case 202 /* ClassDeclaration */: - case 203 /* InterfaceDeclaration */: - case 204 /* TypeAliasDeclaration */: - case 205 /* EnumDeclaration */: - case 206 /* ModuleDeclaration */: - case 209 /* ImportEqualsDeclaration */: - case 218 /* ExportSpecifier */: - case 214 /* ImportSpecifier */: - case 209 /* ImportEqualsDeclaration */: - case 211 /* ImportClause */: - case 212 /* NamespaceImport */: - case 137 /* GetAccessor */: - case 138 /* SetAccessor */: - case 146 /* TypeLiteral */: + case 204 /* ClassDeclaration */: + case 205 /* InterfaceDeclaration */: + case 206 /* TypeAliasDeclaration */: + case 207 /* EnumDeclaration */: + case 208 /* ModuleDeclaration */: + case 211 /* ImportEqualsDeclaration */: + case 220 /* ExportSpecifier */: + case 216 /* ImportSpecifier */: + case 211 /* ImportEqualsDeclaration */: + case 213 /* ImportClause */: + case 214 /* NamespaceImport */: + case 138 /* GetAccessor */: + case 139 /* SetAccessor */: + case 148 /* TypeLiteral */: addDeclaration(node); // fall through - case 136 /* Constructor */: - case 181 /* VariableStatement */: - case 200 /* VariableDeclarationList */: - case 151 /* ObjectBindingPattern */: - case 152 /* ArrayBindingPattern */: - case 207 /* ModuleBlock */: + case 137 /* Constructor */: + case 183 /* VariableStatement */: + case 202 /* VariableDeclarationList */: + case 153 /* ObjectBindingPattern */: + case 154 /* ArrayBindingPattern */: + case 209 /* ModuleBlock */: ts.forEachChild(node, visit); break; - case 180 /* Block */: + case 182 /* Block */: if (ts.isFunctionBlock(node)) { ts.forEachChild(node, visit); } break; - case 130 /* Parameter */: + case 131 /* Parameter */: // Only consider properties defined as constructor parameters if (!(node.flags & 112 /* AccessibilityModifier */)) { break; } // fall through - case 199 /* VariableDeclaration */: - case 153 /* BindingElement */: + case 201 /* VariableDeclaration */: + case 155 /* BindingElement */: if (ts.isBindingPattern(node.name)) { ts.forEachChild(node.name, visit); break; } - case 227 /* EnumMember */: - case 133 /* PropertyDeclaration */: - case 132 /* PropertySignature */: + case 229 /* EnumMember */: + case 134 /* PropertyDeclaration */: + case 133 /* PropertySignature */: addDeclaration(node); break; - case 216 /* ExportDeclaration */: + case 218 /* ExportDeclaration */: // Handle named exports case e.g.: // export {a, b as B} from "mod"; if (node.exportClause) { ts.forEach(node.exportClause.elements, visit); } break; - case 210 /* ImportDeclaration */: + case 212 /* ImportDeclaration */: var importClause = node.importClause; if (importClause) { // Handle default import case e.g.: @@ -36332,7 +38135,7 @@ var ts; // import * as NS from "mod"; // import {a, b as B} from "mod"; if (importClause.namedBindings) { - if (importClause.namedBindings.kind === 212 /* NamespaceImport */) { + if (importClause.namedBindings.kind === 214 /* NamespaceImport */) { addDeclaration(importClause.namedBindings); } else { @@ -36495,6 +38298,7 @@ var ts; ClassificationTypeNames.typeParameterName = "type parameter name"; ClassificationTypeNames.typeAliasName = "type alias name"; ClassificationTypeNames.parameterName = "parameter name"; + ClassificationTypeNames.docCommentTagName = "doc comment tag name"; return ClassificationTypeNames; })(); ts.ClassificationTypeNames = ClassificationTypeNames; @@ -36516,6 +38320,7 @@ var ts; ClassificationType[ClassificationType["typeParameterName"] = 15] = "typeParameterName"; ClassificationType[ClassificationType["typeAliasName"] = 16] = "typeAliasName"; ClassificationType[ClassificationType["parameterName"] = 17] = "parameterName"; + ClassificationType[ClassificationType["docCommentTagName"] = 18] = "docCommentTagName"; })(ts.ClassificationType || (ts.ClassificationType = {})); var ClassificationType = ts.ClassificationType; function displayPartsToString(displayParts) { @@ -36531,16 +38336,16 @@ var ts; } return ts.forEach(symbol.declarations, function (declaration) { // Function expressions are local - if (declaration.kind === 163 /* FunctionExpression */) { + if (declaration.kind === 165 /* FunctionExpression */) { return true; } - if (declaration.kind !== 199 /* VariableDeclaration */ && declaration.kind !== 201 /* FunctionDeclaration */) { + if (declaration.kind !== 201 /* VariableDeclaration */ && declaration.kind !== 203 /* FunctionDeclaration */) { return false; } // If the parent is not sourceFile or module block it is local variable - for (var parent_7 = declaration.parent; !ts.isFunctionBlock(parent_7); parent_7 = parent_7.parent) { + for (var parent_9 = declaration.parent; !ts.isFunctionBlock(parent_9); parent_9 = parent_9.parent) { // Reached source file or module block - if (parent_7.kind === 228 /* SourceFile */ || parent_7.kind === 207 /* ModuleBlock */) { + if (parent_9.kind === 230 /* SourceFile */ || parent_9.kind === 209 /* ModuleBlock */) { return false; } } @@ -36584,9 +38389,8 @@ var ts; var HostCache = (function () { function HostCache(host, getCanonicalFileName) { this.host = host; - this.getCanonicalFileName = getCanonicalFileName; // script id => script index - this.fileNameToEntry = {}; + this.fileNameToEntry = ts.createFileMap(getCanonicalFileName); // Initialize the list with the root file names var rootFileNames = host.getScriptFileNames(); for (var _i = 0; _i < rootFileNames.length; _i++) { @@ -36599,9 +38403,6 @@ var ts; HostCache.prototype.compilationSettings = function () { return this._compilationSettings; }; - HostCache.prototype.normalizeFileName = function (fileName) { - return this.getCanonicalFileName(ts.normalizeSlashes(fileName)); - }; HostCache.prototype.createEntry = function (fileName) { var entry; var scriptSnapshot = this.host.getScriptSnapshot(fileName); @@ -36612,13 +38413,14 @@ var ts; scriptSnapshot: scriptSnapshot }; } - return this.fileNameToEntry[this.normalizeFileName(fileName)] = entry; + this.fileNameToEntry.set(fileName, entry); + return entry; }; HostCache.prototype.getEntry = function (fileName) { - return ts.lookUp(this.fileNameToEntry, this.normalizeFileName(fileName)); + return this.fileNameToEntry.get(fileName); }; HostCache.prototype.contains = function (fileName) { - return ts.hasProperty(this.fileNameToEntry, this.normalizeFileName(fileName)); + return this.fileNameToEntry.contains(fileName); }; HostCache.prototype.getOrCreateEntry = function (fileName) { if (this.contains(fileName)) { @@ -36627,12 +38429,10 @@ var ts; return this.createEntry(fileName); }; HostCache.prototype.getRootFileNames = function () { - var _this = this; var fileNames = []; - ts.forEachKey(this.fileNameToEntry, function (key) { - var entry = _this.getEntry(key); - if (entry) { - fileNames.push(entry.hostFileName); + this.fileNameToEntry.forEachValue(function (value) { + if (value) { + fileNames.push(value.hostFileName); } }); return fileNames; @@ -36687,21 +38487,29 @@ var ts; * This function will compile source text from 'input' argument using specified compiler options. * If not options are provided - it will use a set of default compiler options. * Extra compiler options that will unconditionally be used bu this function are: - * - separateCompilation = true + * - isolatedModules = true * - allowNonTsExtensions = true + * - noLib = true + * - noResolve = true */ - function transpile(input, compilerOptions, fileName, diagnostics) { + function transpile(input, compilerOptions, fileName, diagnostics, moduleName) { var options = compilerOptions ? ts.clone(compilerOptions) : getDefaultCompilerOptions(); - options.separateCompilation = true; + options.isolatedModules = true; // Filename can be non-ts file. options.allowNonTsExtensions = true; + // We are not returning a sourceFile for lib file when asked by the program, + // so pass --noLib to avoid reporting a file not found error. + options.noLib = true; + // We are not doing a full typecheck, we are not resolving the whole context, + // so pass --noResolve to avoid reporting missing file errors. + options.noResolve = true; // Parse var inputFileName = fileName || "module.ts"; var sourceFile = ts.createSourceFile(inputFileName, input, options.target); - // Store syntactic diagnostics - if (diagnostics && sourceFile.parseDiagnostics) { - diagnostics.push.apply(diagnostics, sourceFile.parseDiagnostics); + if (moduleName) { + sourceFile.moduleName = moduleName; } + var newLine = ts.getNewLineCharacter(options); // Output var outputText; // Create a compilerHost object to allow the compiler to read and write files @@ -36715,12 +38523,11 @@ var ts; useCaseSensitiveFileNames: function () { return false; }, getCanonicalFileName: function (fileName) { return fileName; }, getCurrentDirectory: function () { return ""; }, - getNewLine: function () { return (ts.sys && ts.sys.newLine) || "\r\n"; } + getNewLine: function () { return newLine; } }; var program = ts.createProgram([inputFileName], options, compilerHost); - if (diagnostics) { - diagnostics.push.apply(diagnostics, program.getGlobalDiagnostics()); - } + ts.addRange(diagnostics, program.getSyntacticDiagnostics(sourceFile)); + ts.addRange(diagnostics, program.getOptionsDiagnostics()); // Emit program.emit(); ts.Debug.assert(outputText !== undefined, "Output generation failed"); @@ -36728,7 +38535,8 @@ var ts; } ts.transpile = transpile; function createLanguageServiceSourceFile(fileName, scriptSnapshot, scriptTarget, version, setNodeParents) { - var sourceFile = ts.createSourceFile(fileName, scriptSnapshot.getText(0, scriptSnapshot.getLength()), scriptTarget, setNodeParents); + var text = scriptSnapshot.getText(0, scriptSnapshot.getLength()); + var sourceFile = ts.createSourceFile(fileName, text, scriptTarget, setNodeParents); setSourceFileFields(sourceFile, scriptSnapshot, version); // after full parsing we can use table with interned strings as name table sourceFile.nameTable = sourceFile.identifiers; @@ -36743,7 +38551,30 @@ var ts; if (version !== sourceFile.version) { // Once incremental parsing is ready, then just call into this function. if (!ts.disableIncrementalParsing) { - var newSourceFile = ts.updateSourceFile(sourceFile, scriptSnapshot.getText(0, scriptSnapshot.getLength()), textChangeRange, aggressiveChecks); + var newText; + // grab the fragment from the beginning of the original text to the beginning of the span + var prefix = textChangeRange.span.start !== 0 + ? sourceFile.text.substr(0, textChangeRange.span.start) + : ""; + // grab the fragment from the end of the span till the end of the original text + var suffix = ts.textSpanEnd(textChangeRange.span) !== sourceFile.text.length + ? sourceFile.text.substr(ts.textSpanEnd(textChangeRange.span)) + : ""; + if (textChangeRange.newLength === 0) { + // edit was a deletion - just combine prefix and suffix + newText = prefix && suffix ? prefix + suffix : prefix || suffix; + } + else { + // it was actual edit, fetch the fragment of new text that correspond to new span + var changedText = scriptSnapshot.getText(textChangeRange.span.start, textChangeRange.span.start + textChangeRange.newLength); + // combine prefix, changed text and suffix + newText = prefix && suffix + ? prefix + changedText + suffix + : prefix + ? (prefix + changedText) + : (changedText + suffix); + } + var newSourceFile = ts.updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks); setSourceFileFields(newSourceFile, scriptSnapshot, version); // after incremental parsing nameTable might not be up-to-date // drop it so it can be lazily recreated later @@ -36756,10 +38587,16 @@ var ts; return createLanguageServiceSourceFile(sourceFile.fileName, scriptSnapshot, sourceFile.languageVersion, version, true); } ts.updateLanguageServiceSourceFile = updateLanguageServiceSourceFile; - function createDocumentRegistry() { + function createGetCanonicalFileName(useCaseSensitivefileNames) { + return useCaseSensitivefileNames + ? (function (fileName) { return fileName; }) + : (function (fileName) { return fileName.toLowerCase(); }); + } + function createDocumentRegistry(useCaseSensitiveFileNames) { // Maps from compiler setting target (ES3, ES5, etc.) to all the cached documents we have // for those settings. var buckets = {}; + var getCanonicalFileName = createGetCanonicalFileName(!!useCaseSensitiveFileNames); function getKeyFromCompilationSettings(settings) { return "_" + settings.target; // + "|" + settings.propagateEnumConstantoString() } @@ -36767,7 +38604,7 @@ var ts; var key = getKeyFromCompilationSettings(settings); var bucket = ts.lookUp(buckets, key); if (!bucket && createIfMissing) { - buckets[key] = bucket = {}; + buckets[key] = bucket = ts.createFileMap(getCanonicalFileName); } return bucket; } @@ -36776,7 +38613,7 @@ var ts; var entries = ts.lookUp(buckets, name); var sourceFiles = []; for (var i in entries) { - var entry = entries[i]; + var entry = entries.get(i); sourceFiles.push({ name: i, refCount: entry.languageServiceRefCount, @@ -36799,16 +38636,17 @@ var ts; } function acquireOrUpdateDocument(fileName, compilationSettings, scriptSnapshot, version, acquiring) { var bucket = getBucketForCompilationSettings(compilationSettings, true); - var entry = ts.lookUp(bucket, fileName); + var entry = bucket.get(fileName); if (!entry) { ts.Debug.assert(acquiring, "How could we be trying to update a document that the registry doesn't have?"); // Have never seen this file with these settings. Create a new source file for it. var sourceFile = createLanguageServiceSourceFile(fileName, scriptSnapshot, compilationSettings.target, version, false); - bucket[fileName] = entry = { + entry = { sourceFile: sourceFile, languageServiceRefCount: 0, owners: [] }; + bucket.set(fileName, entry); } else { // We have an entry for this file. However, it may be for a different version of @@ -36831,11 +38669,11 @@ var ts; function releaseDocument(fileName, compilationSettings) { var bucket = getBucketForCompilationSettings(compilationSettings, false); ts.Debug.assert(bucket !== undefined); - var entry = ts.lookUp(bucket, fileName); + var entry = bucket.get(fileName); entry.languageServiceRefCount--; ts.Debug.assert(entry.languageServiceRefCount >= 0); if (entry.languageServiceRefCount === 0) { - delete bucket[fileName]; + bucket.remove(fileName); } } return { @@ -36898,7 +38736,7 @@ var ts; else { if (token === 65 /* Identifier */) { token = scanner.scan(); - if (token === 125 /* FromKeyword */) { + if (token === 126 /* FromKeyword */) { token = scanner.scan(); if (token === 8 /* StringLiteral */) { // import d from "mod"; @@ -36908,7 +38746,7 @@ var ts; } else if (token === 53 /* EqualsToken */) { token = scanner.scan(); - if (token === 119 /* RequireKeyword */) { + if (token === 120 /* RequireKeyword */) { token = scanner.scan(); if (token === 16 /* OpenParenToken */) { token = scanner.scan(); @@ -36937,7 +38775,7 @@ var ts; } if (token === 15 /* CloseBraceToken */) { token = scanner.scan(); - if (token === 125 /* FromKeyword */) { + if (token === 126 /* FromKeyword */) { token = scanner.scan(); if (token === 8 /* StringLiteral */) { // import {a as A} from "mod"; @@ -36953,7 +38791,7 @@ var ts; token = scanner.scan(); if (token === 65 /* Identifier */) { token = scanner.scan(); - if (token === 125 /* FromKeyword */) { + if (token === 126 /* FromKeyword */) { token = scanner.scan(); if (token === 8 /* StringLiteral */) { // import * as NS from "mod" @@ -36976,7 +38814,7 @@ var ts; } if (token === 15 /* CloseBraceToken */) { token = scanner.scan(); - if (token === 125 /* FromKeyword */) { + if (token === 126 /* FromKeyword */) { token = scanner.scan(); if (token === 8 /* StringLiteral */) { // export {a as A} from "mod"; @@ -36988,7 +38826,7 @@ var ts; } else if (token === 35 /* AsteriskToken */) { token = scanner.scan(); - if (token === 125 /* FromKeyword */) { + if (token === 126 /* FromKeyword */) { token = scanner.scan(); if (token === 8 /* StringLiteral */) { // export * from "mod" @@ -37011,7 +38849,7 @@ var ts; /// Helpers function getTargetLabel(referenceNode, labelName) { while (referenceNode) { - if (referenceNode.kind === 195 /* LabeledStatement */ && referenceNode.label.text === labelName) { + if (referenceNode.kind === 197 /* LabeledStatement */ && referenceNode.label.text === labelName) { return referenceNode.label; } referenceNode = referenceNode.parent; @@ -37020,12 +38858,12 @@ var ts; } function isJumpStatementTarget(node) { return node.kind === 65 /* Identifier */ && - (node.parent.kind === 191 /* BreakStatement */ || node.parent.kind === 190 /* ContinueStatement */) && + (node.parent.kind === 193 /* BreakStatement */ || node.parent.kind === 192 /* ContinueStatement */) && node.parent.label === node; } function isLabelOfLabeledStatement(node) { return node.kind === 65 /* Identifier */ && - node.parent.kind === 195 /* LabeledStatement */ && + node.parent.kind === 197 /* LabeledStatement */ && node.parent.label === node; } /** @@ -37033,7 +38871,7 @@ var ts; * Note: 'node' cannot be a SourceFile. */ function isLabeledBy(node, labelName) { - for (var owner = node.parent; owner.kind === 195 /* LabeledStatement */; owner = owner.parent) { + for (var owner = node.parent; owner.kind === 197 /* LabeledStatement */; owner = owner.parent) { if (owner.label.text === labelName) { return true; } @@ -37044,25 +38882,25 @@ var ts; return isLabelOfLabeledStatement(node) || isJumpStatementTarget(node); } function isRightSideOfQualifiedName(node) { - return node.parent.kind === 127 /* QualifiedName */ && node.parent.right === node; + return node.parent.kind === 128 /* QualifiedName */ && node.parent.right === node; } function isRightSideOfPropertyAccess(node) { - return node && node.parent && node.parent.kind === 156 /* PropertyAccessExpression */ && node.parent.name === node; + return node && node.parent && node.parent.kind === 158 /* PropertyAccessExpression */ && node.parent.name === node; } function isCallExpressionTarget(node) { if (isRightSideOfPropertyAccess(node)) { node = node.parent; } - return node && node.parent && node.parent.kind === 158 /* CallExpression */ && node.parent.expression === node; + return node && node.parent && node.parent.kind === 160 /* CallExpression */ && node.parent.expression === node; } function isNewExpressionTarget(node) { if (isRightSideOfPropertyAccess(node)) { node = node.parent; } - return node && node.parent && node.parent.kind === 159 /* NewExpression */ && node.parent.expression === node; + return node && node.parent && node.parent.kind === 161 /* NewExpression */ && node.parent.expression === node; } function isNameOfModuleDeclaration(node) { - return node.parent.kind === 206 /* ModuleDeclaration */ && node.parent.name === node; + return node.parent.kind === 208 /* ModuleDeclaration */ && node.parent.name === node; } function isNameOfFunctionDeclaration(node) { return node.kind === 65 /* Identifier */ && @@ -37071,22 +38909,22 @@ var ts; /** Returns true if node is a name of an object literal property, e.g. "a" in x = { "a": 1 } */ function isNameOfPropertyAssignment(node) { return (node.kind === 65 /* Identifier */ || node.kind === 8 /* StringLiteral */ || node.kind === 7 /* NumericLiteral */) && - (node.parent.kind === 225 /* PropertyAssignment */ || node.parent.kind === 226 /* ShorthandPropertyAssignment */) && node.parent.name === node; + (node.parent.kind === 227 /* PropertyAssignment */ || node.parent.kind === 228 /* ShorthandPropertyAssignment */) && node.parent.name === node; } function isLiteralNameOfPropertyDeclarationOrIndexAccess(node) { if (node.kind === 8 /* StringLiteral */ || node.kind === 7 /* NumericLiteral */) { switch (node.parent.kind) { - case 133 /* PropertyDeclaration */: - case 132 /* PropertySignature */: - case 225 /* PropertyAssignment */: - case 227 /* EnumMember */: - case 135 /* MethodDeclaration */: - case 134 /* MethodSignature */: - case 137 /* GetAccessor */: - case 138 /* SetAccessor */: - case 206 /* ModuleDeclaration */: + case 134 /* PropertyDeclaration */: + case 133 /* PropertySignature */: + case 227 /* PropertyAssignment */: + case 229 /* EnumMember */: + case 136 /* MethodDeclaration */: + case 135 /* MethodSignature */: + case 138 /* GetAccessor */: + case 139 /* SetAccessor */: + case 208 /* ModuleDeclaration */: return node.parent.name === node; - case 157 /* ElementAccessExpression */: + case 159 /* ElementAccessExpression */: return node.parent.argumentExpression === node; } } @@ -37145,7 +38983,7 @@ var ts; })(BreakContinueSearchType || (BreakContinueSearchType = {})); // A cache of completion entries for keywords, these do not change between sessions var keywordCompletions = []; - for (var i = 66 /* FirstKeyword */; i <= 126 /* LastKeyword */; i++) { + for (var i = 66 /* FirstKeyword */; i <= 127 /* LastKeyword */; i++) { keywordCompletions.push({ name: ts.tokenToString(i), kind: ScriptElementKind.keyword, @@ -37160,17 +38998,17 @@ var ts; return undefined; } switch (node.kind) { - case 228 /* SourceFile */: - case 135 /* MethodDeclaration */: - case 134 /* MethodSignature */: - case 201 /* FunctionDeclaration */: - case 163 /* FunctionExpression */: - case 137 /* GetAccessor */: - case 138 /* SetAccessor */: - case 202 /* ClassDeclaration */: - case 203 /* InterfaceDeclaration */: - case 205 /* EnumDeclaration */: - case 206 /* ModuleDeclaration */: + case 230 /* SourceFile */: + case 136 /* MethodDeclaration */: + case 135 /* MethodSignature */: + case 203 /* FunctionDeclaration */: + case 165 /* FunctionExpression */: + case 138 /* GetAccessor */: + case 139 /* SetAccessor */: + case 204 /* ClassDeclaration */: + case 205 /* InterfaceDeclaration */: + case 207 /* EnumDeclaration */: + case 208 /* ModuleDeclaration */: return node; } } @@ -37178,38 +39016,38 @@ var ts; ts.getContainerNode = getContainerNode; /* @internal */ function getNodeKind(node) { switch (node.kind) { - case 206 /* ModuleDeclaration */: return ScriptElementKind.moduleElement; - case 202 /* ClassDeclaration */: return ScriptElementKind.classElement; - case 203 /* InterfaceDeclaration */: return ScriptElementKind.interfaceElement; - case 204 /* TypeAliasDeclaration */: return ScriptElementKind.typeElement; - case 205 /* EnumDeclaration */: return ScriptElementKind.enumElement; - case 199 /* VariableDeclaration */: + case 208 /* ModuleDeclaration */: return ScriptElementKind.moduleElement; + case 204 /* ClassDeclaration */: return ScriptElementKind.classElement; + case 205 /* InterfaceDeclaration */: return ScriptElementKind.interfaceElement; + case 206 /* TypeAliasDeclaration */: return ScriptElementKind.typeElement; + case 207 /* EnumDeclaration */: return ScriptElementKind.enumElement; + case 201 /* VariableDeclaration */: return ts.isConst(node) ? ScriptElementKind.constElement : ts.isLet(node) ? ScriptElementKind.letElement : ScriptElementKind.variableElement; - case 201 /* FunctionDeclaration */: return ScriptElementKind.functionElement; - case 137 /* GetAccessor */: return ScriptElementKind.memberGetAccessorElement; - case 138 /* SetAccessor */: return ScriptElementKind.memberSetAccessorElement; - case 135 /* MethodDeclaration */: - case 134 /* MethodSignature */: + case 203 /* FunctionDeclaration */: return ScriptElementKind.functionElement; + case 138 /* GetAccessor */: return ScriptElementKind.memberGetAccessorElement; + case 139 /* SetAccessor */: return ScriptElementKind.memberSetAccessorElement; + case 136 /* MethodDeclaration */: + case 135 /* MethodSignature */: return ScriptElementKind.memberFunctionElement; - case 133 /* PropertyDeclaration */: - case 132 /* PropertySignature */: + case 134 /* PropertyDeclaration */: + case 133 /* PropertySignature */: return ScriptElementKind.memberVariableElement; - case 141 /* IndexSignature */: return ScriptElementKind.indexSignatureElement; - case 140 /* ConstructSignature */: return ScriptElementKind.constructSignatureElement; - case 139 /* CallSignature */: return ScriptElementKind.callSignatureElement; - case 136 /* Constructor */: return ScriptElementKind.constructorImplementationElement; - case 129 /* TypeParameter */: return ScriptElementKind.typeParameterElement; - case 227 /* EnumMember */: return ScriptElementKind.variableElement; - case 130 /* Parameter */: return (node.flags & 112 /* AccessibilityModifier */) ? ScriptElementKind.memberVariableElement : ScriptElementKind.parameterElement; - case 209 /* ImportEqualsDeclaration */: - case 214 /* ImportSpecifier */: - case 211 /* ImportClause */: - case 218 /* ExportSpecifier */: - case 212 /* NamespaceImport */: + case 142 /* IndexSignature */: return ScriptElementKind.indexSignatureElement; + case 141 /* ConstructSignature */: return ScriptElementKind.constructSignatureElement; + case 140 /* CallSignature */: return ScriptElementKind.callSignatureElement; + case 137 /* Constructor */: return ScriptElementKind.constructorImplementationElement; + case 130 /* TypeParameter */: return ScriptElementKind.typeParameterElement; + case 229 /* EnumMember */: return ScriptElementKind.variableElement; + case 131 /* Parameter */: return (node.flags & 112 /* AccessibilityModifier */) ? ScriptElementKind.memberVariableElement : ScriptElementKind.parameterElement; + case 211 /* ImportEqualsDeclaration */: + case 216 /* ImportSpecifier */: + case 213 /* ImportClause */: + case 220 /* ExportSpecifier */: + case 214 /* NamespaceImport */: return ScriptElementKind.alias; } return ScriptElementKind.unknown; @@ -37232,9 +39070,7 @@ var ts; host.log(message); } } - function getCanonicalFileName(fileName) { - return useCaseSensitivefileNames ? fileName : fileName.toLowerCase(); - } + var getCanonicalFileName = createGetCanonicalFileName(useCaseSensitivefileNames); function getValidSourceFile(fileName) { fileName = ts.normalizeSlashes(fileName); var sourceFile = program.getSourceFile(getCanonicalFileName(fileName)); @@ -37299,12 +39135,16 @@ var ts; } } } + // hostCache is captured in the closure for 'getOrCreateSourceFile' but it should not be used past this point. + // It needs to be cleared to allow all collected snapshots to be released + hostCache = undefined; program = newProgram; // Make sure all the nodes in the program are both bound, and have their parent // pointers set property. program.getTypeChecker(); return; function getOrCreateSourceFile(fileName) { + ts.Debug.assert(hostCache !== undefined); // The program is asking for this file, check first if the host can locate it. // If the host can not locate the file, then it does not exist. return undefined // to the program to allow reporting of errors for missing files. @@ -37421,44 +39261,44 @@ var ts; return false; } switch (node.kind) { - case 209 /* ImportEqualsDeclaration */: + case 211 /* ImportEqualsDeclaration */: diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.import_can_only_be_used_in_a_ts_file)); return true; - case 215 /* ExportAssignment */: + case 217 /* ExportAssignment */: diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.export_can_only_be_used_in_a_ts_file)); return true; - case 202 /* ClassDeclaration */: + case 204 /* ClassDeclaration */: var classDeclaration = node; if (checkModifiers(classDeclaration.modifiers) || checkTypeParameters(classDeclaration.typeParameters)) { return true; } break; - case 223 /* HeritageClause */: + case 225 /* HeritageClause */: var heritageClause = node; if (heritageClause.token === 102 /* ImplementsKeyword */) { diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.implements_clauses_can_only_be_used_in_a_ts_file)); return true; } break; - case 203 /* InterfaceDeclaration */: + case 205 /* InterfaceDeclaration */: diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.interface_declarations_can_only_be_used_in_a_ts_file)); return true; - case 206 /* ModuleDeclaration */: + case 208 /* ModuleDeclaration */: diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.module_declarations_can_only_be_used_in_a_ts_file)); return true; - case 204 /* TypeAliasDeclaration */: + case 206 /* TypeAliasDeclaration */: diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.type_aliases_can_only_be_used_in_a_ts_file)); return true; - case 135 /* MethodDeclaration */: - case 134 /* MethodSignature */: - case 136 /* Constructor */: - case 137 /* GetAccessor */: - case 138 /* SetAccessor */: - case 163 /* FunctionExpression */: - case 201 /* FunctionDeclaration */: - case 164 /* ArrowFunction */: - case 201 /* FunctionDeclaration */: + case 136 /* MethodDeclaration */: + case 135 /* MethodSignature */: + case 137 /* Constructor */: + case 138 /* GetAccessor */: + case 139 /* SetAccessor */: + case 165 /* FunctionExpression */: + case 203 /* FunctionDeclaration */: + case 166 /* ArrowFunction */: + case 203 /* FunctionDeclaration */: var functionDeclaration = node; if (checkModifiers(functionDeclaration.modifiers) || checkTypeParameters(functionDeclaration.typeParameters) || @@ -37466,20 +39306,20 @@ var ts; return true; } break; - case 181 /* VariableStatement */: + case 183 /* VariableStatement */: var variableStatement = node; if (checkModifiers(variableStatement.modifiers)) { return true; } break; - case 199 /* VariableDeclaration */: + case 201 /* VariableDeclaration */: var variableDeclaration = node; if (checkTypeAnnotation(variableDeclaration.type)) { return true; } break; - case 158 /* CallExpression */: - case 159 /* NewExpression */: + case 160 /* CallExpression */: + case 161 /* NewExpression */: var expression = node; if (expression.typeArguments && expression.typeArguments.length > 0) { var start = expression.typeArguments.pos; @@ -37487,7 +39327,7 @@ var ts; return true; } break; - case 130 /* Parameter */: + case 131 /* Parameter */: var parameter = node; if (parameter.modifiers) { var start = parameter.modifiers.pos; @@ -37495,7 +39335,7 @@ var ts; return true; } if (parameter.questionToken) { - diagnostics.push(ts.createDiagnosticForNode(parameter.questionToken, ts.Diagnostics.can_only_be_used_in_a_ts_file)); + diagnostics.push(ts.createDiagnosticForNode(parameter.questionToken, ts.Diagnostics._0_can_only_be_used_in_a_ts_file, '?')); return true; } if (parameter.type) { @@ -37503,17 +39343,17 @@ var ts; return true; } break; - case 133 /* PropertyDeclaration */: + case 134 /* PropertyDeclaration */: diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.property_declarations_can_only_be_used_in_a_ts_file)); return true; - case 205 /* EnumDeclaration */: + case 207 /* EnumDeclaration */: diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.enum_declarations_can_only_be_used_in_a_ts_file)); return true; - case 161 /* TypeAssertionExpression */: + case 163 /* TypeAssertionExpression */: var typeAssertionExpression = node; diagnostics.push(ts.createDiagnosticForNode(typeAssertionExpression.type, ts.Diagnostics.type_assertion_expressions_can_only_be_used_in_a_ts_file)); return true; - case 131 /* Decorator */: + case 132 /* Decorator */: diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.decorators_can_only_be_used_in_a_ts_file)); return true; } @@ -37558,7 +39398,7 @@ var ts; } function getCompilerOptionsDiagnostics() { synchronizeHostData(); - return program.getGlobalDiagnostics(); + return program.getOptionsDiagnostics().concat(program.getGlobalDiagnostics()); } /// Completion function getCompletionEntryDisplayNameForSymbol(symbol, target, performCharacterChecks) { @@ -37612,6 +39452,7 @@ var ts; var typeChecker = program.getTypeChecker(); var syntacticStart = new Date().getTime(); var sourceFile = getValidSourceFile(fileName); + var isJavaScriptFile = ts.isJavaScript(fileName); var start = new Date().getTime(); var currentToken = ts.getTokenAtPosition(sourceFile, position); log("getCompletionData: Get current token: " + (new Date().getTime() - start)); @@ -37646,11 +39487,11 @@ var ts; // visible symbols in the scope, and the node is the current location. var node = currentToken; var isRightOfDot = false; - if (contextToken && contextToken.kind === 20 /* DotToken */ && contextToken.parent.kind === 156 /* PropertyAccessExpression */) { + if (contextToken && contextToken.kind === 20 /* DotToken */ && contextToken.parent.kind === 158 /* PropertyAccessExpression */) { node = contextToken.parent.expression; isRightOfDot = true; } - else if (contextToken && contextToken.kind === 20 /* DotToken */ && contextToken.parent.kind === 127 /* QualifiedName */) { + else if (contextToken && contextToken.kind === 20 /* DotToken */ && contextToken.parent.kind === 128 /* QualifiedName */) { node = contextToken.parent.left; isRightOfDot = true; } @@ -37677,7 +39518,7 @@ var ts; // Right of dot member completion list isMemberCompletion = true; isNewIdentifierLocation = false; - if (node.kind === 65 /* Identifier */ || node.kind === 127 /* QualifiedName */ || node.kind === 156 /* PropertyAccessExpression */) { + if (node.kind === 65 /* Identifier */ || node.kind === 128 /* QualifiedName */ || node.kind === 158 /* PropertyAccessExpression */) { var symbol = typeChecker.getSymbolAtLocation(node); // This is an alias, follow what it aliases if (symbol && symbol.flags & 8388608 /* Alias */) { @@ -37694,13 +39535,29 @@ var ts; } } var type = typeChecker.getTypeAtLocation(node); + addTypeProperties(type); + } + function addTypeProperties(type) { if (type) { // Filter private properties - ts.forEach(type.getApparentProperties(), function (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 & 16384 /* 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); + } + } } } function tryGetGlobalSymbols() { @@ -37719,13 +39576,13 @@ var ts; symbols = filterContextualMembersList(contextualTypeMembers, containingObjectLiteral.properties); } } - else if (ts.getAncestor(contextToken, 211 /* ImportClause */)) { + else if (ts.getAncestor(contextToken, 213 /* ImportClause */)) { // cursor is in import clause // try to show exported member for imported module isMemberCompletion = true; isNewIdentifierLocation = true; if (showCompletionsInImportsClause(contextToken)) { - var importDeclaration = ts.getAncestor(contextToken, 210 /* ImportDeclaration */); + var importDeclaration = ts.getAncestor(contextToken, 212 /* ImportDeclaration */); ts.Debug.assert(importDeclaration !== undefined); var exports; if (importDeclaration.moduleSpecifier) { @@ -37804,7 +39661,7 @@ var ts; // import {| // import {a,| if (node.kind === 14 /* OpenBraceToken */ || node.kind === 23 /* CommaToken */) { - return node.parent.kind === 213 /* NamedImports */; + return node.parent.kind === 215 /* NamedImports */; } } return false; @@ -37814,38 +39671,38 @@ var ts; var containingNodeKind = previousToken.parent.kind; switch (previousToken.kind) { case 23 /* CommaToken */: - return containingNodeKind === 158 /* CallExpression */ // func( a, | - || containingNodeKind === 136 /* Constructor */ // constructor( a, | public, protected, private keywords are allowed here, so show completion - || containingNodeKind === 159 /* NewExpression */ // new C(a, | - || containingNodeKind === 154 /* ArrayLiteralExpression */ // [a, | - || containingNodeKind === 170 /* BinaryExpression */ // let x = (a, | - || containingNodeKind === 143 /* FunctionType */; // var x: (s: string, list| + return containingNodeKind === 160 /* CallExpression */ // func( a, | + || containingNodeKind === 137 /* Constructor */ // constructor( a, | public, protected, private keywords are allowed here, so show completion + || containingNodeKind === 161 /* NewExpression */ // new C(a, | + || containingNodeKind === 156 /* ArrayLiteralExpression */ // [a, | + || containingNodeKind === 172 /* BinaryExpression */ // let x = (a, | + || containingNodeKind === 145 /* FunctionType */; // var x: (s: string, list| case 16 /* OpenParenToken */: - return containingNodeKind === 158 /* CallExpression */ // func( | - || containingNodeKind === 136 /* Constructor */ // constructor( | - || containingNodeKind === 159 /* NewExpression */ // new C(a| - || containingNodeKind === 162 /* ParenthesizedExpression */ // let x = (a| - || containingNodeKind === 150 /* ParenthesizedType */; // function F(pred: (a| this can become an arrow function, where 'a' is the argument + return containingNodeKind === 160 /* CallExpression */ // func( | + || containingNodeKind === 137 /* Constructor */ // constructor( | + || containingNodeKind === 161 /* NewExpression */ // new C(a| + || containingNodeKind === 164 /* ParenthesizedExpression */ // let x = (a| + || containingNodeKind === 152 /* ParenthesizedType */; // function F(pred: (a| this can become an arrow function, where 'a' is the argument case 18 /* OpenBracketToken */: - return containingNodeKind === 154 /* ArrayLiteralExpression */; // [ | - case 117 /* ModuleKeyword */: // module | - case 118 /* NamespaceKeyword */: + return containingNodeKind === 156 /* ArrayLiteralExpression */; // [ | + case 118 /* ModuleKeyword */: // module | + case 119 /* NamespaceKeyword */: return true; case 20 /* DotToken */: - return containingNodeKind === 206 /* ModuleDeclaration */; // module A.| + return containingNodeKind === 208 /* ModuleDeclaration */; // module A.| case 14 /* OpenBraceToken */: - return containingNodeKind === 202 /* ClassDeclaration */; // class A{ | + return containingNodeKind === 204 /* ClassDeclaration */; // class A{ | case 53 /* EqualsToken */: - return containingNodeKind === 199 /* VariableDeclaration */ // let x = a| - || containingNodeKind === 170 /* BinaryExpression */; // x = a| + return containingNodeKind === 201 /* VariableDeclaration */ // let x = a| + || containingNodeKind === 172 /* BinaryExpression */; // x = a| case 11 /* TemplateHead */: - return containingNodeKind === 172 /* TemplateExpression */; // `aa ${| + return containingNodeKind === 174 /* TemplateExpression */; // `aa ${| case 12 /* TemplateMiddle */: - return containingNodeKind === 178 /* TemplateSpan */; // `aa ${10} dd ${| + return containingNodeKind === 180 /* TemplateSpan */; // `aa ${10} dd ${| case 108 /* PublicKeyword */: case 106 /* PrivateKeyword */: case 107 /* ProtectedKeyword */: - return containingNodeKind === 133 /* PropertyDeclaration */; // class A{ public | + return containingNodeKind === 134 /* PropertyDeclaration */; // class A{ public | } // Previous token may have been a keyword that was converted to an identifier. switch (previousToken.getText()) { @@ -37861,15 +39718,18 @@ var ts; if (previousToken.kind === 8 /* StringLiteral */ || previousToken.kind === 9 /* RegularExpressionLiteral */ || ts.isTemplateLiteralKind(previousToken.kind)) { - // The position has to be either: 1. entirely within the token text, or - // 2. at the end position of an unterminated token. var start_3 = previousToken.getStart(); var end = previousToken.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) { return true; } - else if (position === end) { - return !!previousToken.isUnterminated; + if (position === end) { + return !!previousToken.isUnterminated || + previousToken.kind === 9 /* RegularExpressionLiteral */; } } return false; @@ -37877,12 +39737,12 @@ var ts; function getContainingObjectLiteralApplicableForCompletion(previousToken) { // The locations in an object literal expression that are applicable for completion are property name definition locations. if (previousToken) { - var parent_8 = previousToken.parent; + var parent_10 = previousToken.parent; switch (previousToken.kind) { case 14 /* OpenBraceToken */: // let x = { | case 23 /* CommaToken */: - if (parent_8 && parent_8.kind === 155 /* ObjectLiteralExpression */) { - return parent_8; + if (parent_10 && parent_10.kind === 157 /* ObjectLiteralExpression */) { + return parent_10; } break; } @@ -37891,16 +39751,16 @@ var ts; } function isFunction(kind) { switch (kind) { - case 163 /* FunctionExpression */: - case 164 /* ArrowFunction */: - case 201 /* FunctionDeclaration */: - case 135 /* MethodDeclaration */: - case 134 /* MethodSignature */: - case 137 /* GetAccessor */: - case 138 /* SetAccessor */: - case 139 /* CallSignature */: - case 140 /* ConstructSignature */: - case 141 /* IndexSignature */: + case 165 /* FunctionExpression */: + case 166 /* ArrowFunction */: + case 203 /* FunctionDeclaration */: + case 136 /* MethodDeclaration */: + case 135 /* MethodSignature */: + case 138 /* GetAccessor */: + case 139 /* SetAccessor */: + case 140 /* CallSignature */: + case 141 /* ConstructSignature */: + case 142 /* IndexSignature */: return true; } return false; @@ -37910,63 +39770,63 @@ var ts; var containingNodeKind = previousToken.parent.kind; switch (previousToken.kind) { case 23 /* CommaToken */: - return containingNodeKind === 199 /* VariableDeclaration */ || - containingNodeKind === 200 /* VariableDeclarationList */ || - containingNodeKind === 181 /* VariableStatement */ || - containingNodeKind === 205 /* EnumDeclaration */ || + return containingNodeKind === 201 /* VariableDeclaration */ || + containingNodeKind === 202 /* VariableDeclarationList */ || + containingNodeKind === 183 /* VariableStatement */ || + containingNodeKind === 207 /* EnumDeclaration */ || isFunction(containingNodeKind) || - containingNodeKind === 202 /* ClassDeclaration */ || - containingNodeKind === 201 /* FunctionDeclaration */ || - containingNodeKind === 203 /* InterfaceDeclaration */ || - containingNodeKind === 152 /* ArrayBindingPattern */ || - containingNodeKind === 151 /* ObjectBindingPattern */; // function func({ x, y| + containingNodeKind === 204 /* ClassDeclaration */ || + containingNodeKind === 203 /* FunctionDeclaration */ || + containingNodeKind === 205 /* InterfaceDeclaration */ || + containingNodeKind === 154 /* ArrayBindingPattern */ || + containingNodeKind === 153 /* ObjectBindingPattern */; // function func({ x, y| case 20 /* DotToken */: - return containingNodeKind === 152 /* ArrayBindingPattern */; // var [.| + return containingNodeKind === 154 /* ArrayBindingPattern */; // var [.| case 51 /* ColonToken */: - return containingNodeKind === 153 /* BindingElement */; // var {x :html| + return containingNodeKind === 155 /* BindingElement */; // var {x :html| case 18 /* OpenBracketToken */: - return containingNodeKind === 152 /* ArrayBindingPattern */; // var [x| + return containingNodeKind === 154 /* ArrayBindingPattern */; // var [x| case 16 /* OpenParenToken */: - return containingNodeKind === 224 /* CatchClause */ || + return containingNodeKind === 226 /* CatchClause */ || isFunction(containingNodeKind); case 14 /* OpenBraceToken */: - return containingNodeKind === 205 /* EnumDeclaration */ || - containingNodeKind === 203 /* InterfaceDeclaration */ || - containingNodeKind === 146 /* TypeLiteral */ || - containingNodeKind === 151 /* ObjectBindingPattern */; // function func({ x| + return containingNodeKind === 207 /* EnumDeclaration */ || + containingNodeKind === 205 /* InterfaceDeclaration */ || + containingNodeKind === 148 /* TypeLiteral */ || + containingNodeKind === 153 /* ObjectBindingPattern */; // function func({ x| case 22 /* SemicolonToken */: - return containingNodeKind === 132 /* PropertySignature */ && + return containingNodeKind === 133 /* PropertySignature */ && previousToken.parent && previousToken.parent.parent && - (previousToken.parent.parent.kind === 203 /* InterfaceDeclaration */ || - previousToken.parent.parent.kind === 146 /* TypeLiteral */); // let x : { a; | + (previousToken.parent.parent.kind === 205 /* InterfaceDeclaration */ || + previousToken.parent.parent.kind === 148 /* TypeLiteral */); // let x : { a; | case 24 /* LessThanToken */: - return containingNodeKind === 202 /* ClassDeclaration */ || - containingNodeKind === 201 /* FunctionDeclaration */ || - containingNodeKind === 203 /* InterfaceDeclaration */ || + return containingNodeKind === 204 /* ClassDeclaration */ || + containingNodeKind === 203 /* FunctionDeclaration */ || + containingNodeKind === 205 /* InterfaceDeclaration */ || isFunction(containingNodeKind); case 109 /* StaticKeyword */: - return containingNodeKind === 133 /* PropertyDeclaration */; + return containingNodeKind === 134 /* PropertyDeclaration */; case 21 /* DotDotDotToken */: - return containingNodeKind === 130 /* Parameter */ || - containingNodeKind === 136 /* Constructor */ || + return containingNodeKind === 131 /* Parameter */ || + containingNodeKind === 137 /* Constructor */ || (previousToken.parent && previousToken.parent.parent && - previousToken.parent.parent.kind === 152 /* ArrayBindingPattern */); // var [...z| + previousToken.parent.parent.kind === 154 /* ArrayBindingPattern */); // var [...z| case 108 /* PublicKeyword */: case 106 /* PrivateKeyword */: case 107 /* ProtectedKeyword */: - return containingNodeKind === 130 /* Parameter */; + return containingNodeKind === 131 /* Parameter */; case 69 /* ClassKeyword */: case 77 /* EnumKeyword */: case 103 /* InterfaceKeyword */: case 83 /* FunctionKeyword */: case 98 /* VarKeyword */: case 116 /* GetKeyword */: - case 121 /* SetKeyword */: + case 122 /* SetKeyword */: case 85 /* ImportKeyword */: case 104 /* LetKeyword */: case 70 /* ConstKeyword */: case 110 /* YieldKeyword */: - case 124 /* TypeKeyword */: + case 125 /* TypeKeyword */: return true; } // Previous token may have been a keyword that was converted to an identifier. @@ -37998,7 +39858,7 @@ var ts; return exports; } if (importDeclaration.importClause.namedBindings && - importDeclaration.importClause.namedBindings.kind === 213 /* NamedImports */) { + importDeclaration.importClause.namedBindings.kind === 215 /* NamedImports */) { ts.forEach(importDeclaration.importClause.namedBindings.elements, function (el) { var name = el.propertyName || el.name; exisingImports[name.text] = true; @@ -38015,7 +39875,7 @@ var ts; } var existingMemberNames = {}; ts.forEach(existingMembers, function (m) { - if (m.kind !== 225 /* PropertyAssignment */ && m.kind !== 226 /* ShorthandPropertyAssignment */) { + if (m.kind !== 227 /* PropertyAssignment */ && m.kind !== 228 /* ShorthandPropertyAssignment */) { // Ignore omitted expressions for missing members in the object literal return; } @@ -38065,10 +39925,10 @@ var ts; for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { var sourceFile = _a[_i]; var nameTable = getNameTable(sourceFile); - for (var name_26 in nameTable) { - if (!allNames[name_26]) { - allNames[name_26] = name_26; - var displayName = getCompletionEntryDisplayName(name_26, target, true); + for (var name_27 in nameTable) { + if (!allNames[name_27]) { + allNames[name_27] = name_27; + var displayName = getCompletionEntryDisplayName(name_27, target, true); if (displayName) { var entry = { name: displayName, @@ -38267,7 +40127,7 @@ var ts; var signature; type = typeChecker.getTypeOfSymbolAtLocation(symbol, location); if (type) { - if (location.parent && location.parent.kind === 156 /* PropertyAccessExpression */) { + if (location.parent && location.parent.kind === 158 /* PropertyAccessExpression */) { var right = location.parent.name; // Either the location is on the right of a property access, or on the left and the right is missing if (right === location || (right && right.getFullWidth() === 0)) { @@ -38276,7 +40136,7 @@ var ts; } // try get the call/construct signature from the type if it matches var callExpression; - if (location.kind === 158 /* CallExpression */ || location.kind === 159 /* NewExpression */) { + if (location.kind === 160 /* CallExpression */ || location.kind === 161 /* NewExpression */) { callExpression = location; } else if (isCallExpressionTarget(location) || isNewExpressionTarget(location)) { @@ -38289,7 +40149,7 @@ var ts; // Use the first candidate: signature = candidateSignatures[0]; } - var useConstructSignatures = callExpression.kind === 159 /* NewExpression */ || callExpression.expression.kind === 91 /* SuperKeyword */; + var useConstructSignatures = callExpression.kind === 161 /* NewExpression */ || callExpression.expression.kind === 91 /* SuperKeyword */; var allSignatures = useConstructSignatures ? type.getConstructSignatures() : type.getCallSignatures(); if (!ts.contains(allSignatures, signature.target || signature)) { // Get the first signature if there @@ -38341,24 +40201,24 @@ var ts; } } else if ((isNameOfFunctionDeclaration(location) && !(symbol.flags & 98304 /* Accessor */)) || - (location.kind === 114 /* ConstructorKeyword */ && location.parent.kind === 136 /* Constructor */)) { + (location.kind === 114 /* ConstructorKeyword */ && location.parent.kind === 137 /* Constructor */)) { // get the signature from the declaration and write it var functionDeclaration = location.parent; - var allSignatures = functionDeclaration.kind === 136 /* Constructor */ ? type.getConstructSignatures() : type.getCallSignatures(); + var allSignatures = functionDeclaration.kind === 137 /* Constructor */ ? type.getConstructSignatures() : type.getCallSignatures(); if (!typeChecker.isImplementationOfOverload(functionDeclaration)) { signature = typeChecker.getSignatureFromDeclaration(functionDeclaration); } else { signature = allSignatures[0]; } - if (functionDeclaration.kind === 136 /* Constructor */) { + if (functionDeclaration.kind === 137 /* Constructor */) { // show (constructor) Type(...) signature symbolKind = ScriptElementKind.constructorImplementationElement; addPrefixForAnyFunctionOrVar(type.symbol, symbolKind); } else { // (function/method) symbol(..signature) - addPrefixForAnyFunctionOrVar(functionDeclaration.kind === 139 /* CallSignature */ && + addPrefixForAnyFunctionOrVar(functionDeclaration.kind === 140 /* CallSignature */ && !(type.symbol.flags & 2048 /* TypeLiteral */ || type.symbol.flags & 4096 /* ObjectLiteral */) ? type.symbol : symbol, symbolKind); } addSignatureDisplayParts(signature, allSignatures); @@ -38381,7 +40241,7 @@ var ts; } if (symbolFlags & 524288 /* TypeAlias */) { addNewLineIfDisplayPartsExist(); - displayParts.push(ts.keywordPart(124 /* TypeKeyword */)); + displayParts.push(ts.keywordPart(125 /* TypeKeyword */)); displayParts.push(ts.spacePart()); addFullSymbolName(symbol); displayParts.push(ts.spacePart()); @@ -38401,9 +40261,9 @@ var ts; } if (symbolFlags & 1536 /* Module */) { addNewLineIfDisplayPartsExist(); - var declaration = ts.getDeclarationOfKind(symbol, 206 /* ModuleDeclaration */); + var declaration = ts.getDeclarationOfKind(symbol, 208 /* ModuleDeclaration */); var isNamespace = declaration && declaration.name && declaration.name.kind === 65 /* Identifier */; - displayParts.push(ts.keywordPart(isNamespace ? 118 /* NamespaceKeyword */ : 117 /* ModuleKeyword */)); + displayParts.push(ts.keywordPart(isNamespace ? 119 /* NamespaceKeyword */ : 118 /* ModuleKeyword */)); displayParts.push(ts.spacePart()); addFullSymbolName(symbol); } @@ -38424,13 +40284,13 @@ var ts; } else { // Method/function type parameter - var signatureDeclaration = ts.getDeclarationOfKind(symbol, 129 /* TypeParameter */).parent; + var signatureDeclaration = ts.getDeclarationOfKind(symbol, 130 /* TypeParameter */).parent; var signature = typeChecker.getSignatureFromDeclaration(signatureDeclaration); - if (signatureDeclaration.kind === 140 /* ConstructSignature */) { + if (signatureDeclaration.kind === 141 /* ConstructSignature */) { displayParts.push(ts.keywordPart(88 /* NewKeyword */)); displayParts.push(ts.spacePart()); } - else if (signatureDeclaration.kind !== 139 /* CallSignature */ && signatureDeclaration.name) { + else if (signatureDeclaration.kind !== 140 /* CallSignature */ && signatureDeclaration.name) { addFullSymbolName(signatureDeclaration.symbol); } displayParts.push.apply(displayParts, ts.signatureToDisplayParts(typeChecker, signature, sourceFile, 32 /* WriteTypeArgumentsOfSignature */)); @@ -38439,7 +40299,7 @@ var ts; if (symbolFlags & 8 /* EnumMember */) { addPrefixForAnyFunctionOrVar(symbol, "enum member"); var declaration = symbol.declarations[0]; - if (declaration.kind === 227 /* EnumMember */) { + if (declaration.kind === 229 /* EnumMember */) { var constantValue = typeChecker.getConstantValue(declaration); if (constantValue !== undefined) { displayParts.push(ts.spacePart()); @@ -38455,13 +40315,13 @@ var ts; displayParts.push(ts.spacePart()); addFullSymbolName(symbol); ts.forEach(symbol.declarations, function (declaration) { - if (declaration.kind === 209 /* ImportEqualsDeclaration */) { + if (declaration.kind === 211 /* ImportEqualsDeclaration */) { var importEqualsDeclaration = declaration; if (ts.isExternalModuleImportEqualsDeclaration(importEqualsDeclaration)) { displayParts.push(ts.spacePart()); displayParts.push(ts.operatorPart(53 /* EqualsToken */)); displayParts.push(ts.spacePart()); - displayParts.push(ts.keywordPart(119 /* RequireKeyword */)); + displayParts.push(ts.keywordPart(120 /* RequireKeyword */)); displayParts.push(ts.punctuationPart(16 /* OpenParenToken */)); displayParts.push(ts.displayPart(ts.getTextOfNode(ts.getExternalModuleImportEqualsDeclarationExpression(importEqualsDeclaration)), SymbolDisplayPartKind.stringLiteral)); displayParts.push(ts.punctuationPart(17 /* CloseParenToken */)); @@ -38588,8 +40448,8 @@ var ts; // Try getting just type at this position and show switch (node.kind) { case 65 /* Identifier */: - case 156 /* PropertyAccessExpression */: - case 127 /* QualifiedName */: + case 158 /* PropertyAccessExpression */: + case 128 /* QualifiedName */: case 93 /* ThisKeyword */: case 91 /* SuperKeyword */: // For the identifiers/this/super etc get the type at position @@ -38647,7 +40507,7 @@ var ts; if (isNewExpressionTarget(location) || location.kind === 114 /* ConstructorKeyword */) { if (symbol.flags & 32 /* Class */) { var classDeclaration = symbol.getDeclarations()[0]; - ts.Debug.assert(classDeclaration && classDeclaration.kind === 202 /* ClassDeclaration */); + ts.Debug.assert(classDeclaration && classDeclaration.kind === 204 /* ClassDeclaration */); return tryAddSignature(classDeclaration.members, true, symbolKind, symbolName, containerName, result); } } @@ -38663,8 +40523,8 @@ var ts; var declarations = []; var definition; ts.forEach(signatureDeclarations, function (d) { - if ((selectConstructors && d.kind === 136 /* Constructor */) || - (!selectConstructors && (d.kind === 201 /* FunctionDeclaration */ || d.kind === 135 /* MethodDeclaration */ || d.kind === 134 /* MethodSignature */))) { + if ((selectConstructors && d.kind === 137 /* Constructor */) || + (!selectConstructors && (d.kind === 203 /* FunctionDeclaration */ || d.kind === 136 /* MethodDeclaration */ || d.kind === 135 /* MethodSignature */))) { declarations.push(d); if (d.body) definition = d; @@ -38733,7 +40593,7 @@ var ts; // go to the declaration of the property name (in this case stay at the same position). However, if go-to-definition // is performed at the location of property access, we would like to go to definition of the property in the short-hand // assignment. This case and others are handled by the following code. - if (node.parent.kind === 226 /* ShorthandPropertyAssignment */) { + if (node.parent.kind === 228 /* ShorthandPropertyAssignment */) { var shorthandSymbol = typeChecker.getShorthandAssignmentValueSymbol(symbol.valueDeclaration); if (!shorthandSymbol) { return []; @@ -38767,7 +40627,7 @@ var ts; var result = []; ts.forEach(type.types, function (t) { if (t.symbol) { - result.push.apply(result, getDefinitionFromSymbol(t.symbol, node)); + ts.addRange(result, getDefinitionFromSymbol(t.symbol, node)); } }); return result; @@ -38862,74 +40722,74 @@ var ts; switch (node.kind) { case 84 /* IfKeyword */: case 76 /* ElseKeyword */: - if (hasKind(node.parent, 184 /* IfStatement */)) { + if (hasKind(node.parent, 186 /* IfStatement */)) { return getIfElseOccurrences(node.parent); } break; case 90 /* ReturnKeyword */: - if (hasKind(node.parent, 192 /* ReturnStatement */)) { + if (hasKind(node.parent, 194 /* ReturnStatement */)) { return getReturnOccurrences(node.parent); } break; case 94 /* ThrowKeyword */: - if (hasKind(node.parent, 196 /* ThrowStatement */)) { + if (hasKind(node.parent, 198 /* ThrowStatement */)) { return getThrowOccurrences(node.parent); } break; case 68 /* CatchKeyword */: - if (hasKind(parent(parent(node)), 197 /* TryStatement */)) { + if (hasKind(parent(parent(node)), 199 /* TryStatement */)) { return getTryCatchFinallyOccurrences(node.parent.parent); } break; case 96 /* TryKeyword */: case 81 /* FinallyKeyword */: - if (hasKind(parent(node), 197 /* TryStatement */)) { + if (hasKind(parent(node), 199 /* TryStatement */)) { return getTryCatchFinallyOccurrences(node.parent); } break; case 92 /* SwitchKeyword */: - if (hasKind(node.parent, 194 /* SwitchStatement */)) { + if (hasKind(node.parent, 196 /* SwitchStatement */)) { return getSwitchCaseDefaultOccurrences(node.parent); } break; case 67 /* CaseKeyword */: case 73 /* DefaultKeyword */: - if (hasKind(parent(parent(parent(node))), 194 /* SwitchStatement */)) { + if (hasKind(parent(parent(parent(node))), 196 /* SwitchStatement */)) { return getSwitchCaseDefaultOccurrences(node.parent.parent.parent); } break; case 66 /* BreakKeyword */: case 71 /* ContinueKeyword */: - if (hasKind(node.parent, 191 /* BreakStatement */) || hasKind(node.parent, 190 /* ContinueStatement */)) { + if (hasKind(node.parent, 193 /* BreakStatement */) || hasKind(node.parent, 192 /* ContinueStatement */)) { return getBreakOrContinueStatementOccurences(node.parent); } break; case 82 /* ForKeyword */: - if (hasKind(node.parent, 187 /* ForStatement */) || - hasKind(node.parent, 188 /* ForInStatement */) || - hasKind(node.parent, 189 /* ForOfStatement */)) { + if (hasKind(node.parent, 189 /* ForStatement */) || + hasKind(node.parent, 190 /* ForInStatement */) || + hasKind(node.parent, 191 /* ForOfStatement */)) { return getLoopBreakContinueOccurrences(node.parent); } break; case 100 /* WhileKeyword */: case 75 /* DoKeyword */: - if (hasKind(node.parent, 186 /* WhileStatement */) || hasKind(node.parent, 185 /* DoStatement */)) { + if (hasKind(node.parent, 188 /* WhileStatement */) || hasKind(node.parent, 187 /* DoStatement */)) { return getLoopBreakContinueOccurrences(node.parent); } break; case 114 /* ConstructorKeyword */: - if (hasKind(node.parent, 136 /* Constructor */)) { + if (hasKind(node.parent, 137 /* Constructor */)) { return getConstructorOccurrences(node.parent); } break; case 116 /* GetKeyword */: - case 121 /* SetKeyword */: - if (hasKind(node.parent, 137 /* GetAccessor */) || hasKind(node.parent, 138 /* SetAccessor */)) { + case 122 /* SetKeyword */: + if (hasKind(node.parent, 138 /* GetAccessor */) || hasKind(node.parent, 139 /* SetAccessor */)) { return getGetAndSetOccurrences(node.parent); } default: if (ts.isModifier(node.kind) && node.parent && - (ts.isDeclaration(node.parent) || node.parent.kind === 181 /* VariableStatement */)) { + (ts.isDeclaration(node.parent) || node.parent.kind === 183 /* VariableStatement */)) { return getModifierOccurrences(node.kind, node.parent); } } @@ -38945,10 +40805,10 @@ var ts; aggregate(node); return statementAccumulator; function aggregate(node) { - if (node.kind === 196 /* ThrowStatement */) { + if (node.kind === 198 /* ThrowStatement */) { statementAccumulator.push(node); } - else if (node.kind === 197 /* TryStatement */) { + else if (node.kind === 199 /* TryStatement */) { var tryStatement = node; if (tryStatement.catchClause) { aggregate(tryStatement.catchClause); @@ -38976,19 +40836,19 @@ var ts; function getThrowStatementOwner(throwStatement) { var child = throwStatement; while (child.parent) { - var parent_9 = child.parent; - if (ts.isFunctionBlock(parent_9) || parent_9.kind === 228 /* SourceFile */) { - return parent_9; + var parent_11 = child.parent; + if (ts.isFunctionBlock(parent_11) || parent_11.kind === 230 /* SourceFile */) { + return parent_11; } // A throw-statement is only owned by a try-statement if the try-statement has // a catch clause, and if the throw-statement occurs within the try block. - if (parent_9.kind === 197 /* TryStatement */) { - var tryStatement = parent_9; + if (parent_11.kind === 199 /* TryStatement */) { + var tryStatement = parent_11; if (tryStatement.tryBlock === child && tryStatement.catchClause) { return child; } } - child = parent_9; + child = parent_11; } return undefined; } @@ -38997,7 +40857,7 @@ var ts; aggregate(node); return statementAccumulator; function aggregate(node) { - if (node.kind === 191 /* BreakStatement */ || node.kind === 190 /* ContinueStatement */) { + if (node.kind === 193 /* BreakStatement */ || node.kind === 192 /* ContinueStatement */) { statementAccumulator.push(node); } else if (!ts.isFunctionLike(node)) { @@ -39011,25 +40871,25 @@ var ts; return actualOwner && actualOwner === owner; } function getBreakOrContinueOwner(statement) { - for (var node_1 = statement.parent; node_1; node_1 = node_1.parent) { - switch (node_1.kind) { - case 194 /* SwitchStatement */: - if (statement.kind === 190 /* ContinueStatement */) { + for (var node_2 = statement.parent; node_2; node_2 = node_2.parent) { + switch (node_2.kind) { + case 196 /* SwitchStatement */: + if (statement.kind === 192 /* ContinueStatement */) { continue; } // Fall through. - case 187 /* ForStatement */: - case 188 /* ForInStatement */: - case 189 /* ForOfStatement */: - case 186 /* WhileStatement */: - case 185 /* DoStatement */: - if (!statement.label || isLabeledBy(node_1, statement.label.text)) { - return node_1; + case 189 /* ForStatement */: + case 190 /* ForInStatement */: + case 191 /* ForOfStatement */: + case 188 /* WhileStatement */: + case 187 /* DoStatement */: + if (!statement.label || isLabeledBy(node_2, statement.label.text)) { + return node_2; } break; default: // Don't cross function boundaries. - if (ts.isFunctionLike(node_1)) { + if (ts.isFunctionLike(node_2)) { return undefined; } break; @@ -39041,18 +40901,18 @@ var ts; var container = declaration.parent; // Make sure we only highlight the keyword when it makes sense to do so. if (ts.isAccessibilityModifier(modifier)) { - if (!(container.kind === 202 /* ClassDeclaration */ || - (declaration.kind === 130 /* Parameter */ && hasKind(container, 136 /* Constructor */)))) { + if (!(container.kind === 204 /* ClassDeclaration */ || + (declaration.kind === 131 /* Parameter */ && hasKind(container, 137 /* Constructor */)))) { return undefined; } } else if (modifier === 109 /* StaticKeyword */) { - if (container.kind !== 202 /* ClassDeclaration */) { + if (container.kind !== 204 /* ClassDeclaration */) { return undefined; } } else if (modifier === 78 /* ExportKeyword */ || modifier === 115 /* DeclareKeyword */) { - if (!(container.kind === 207 /* ModuleBlock */ || container.kind === 228 /* SourceFile */)) { + if (!(container.kind === 209 /* ModuleBlock */ || container.kind === 230 /* SourceFile */)) { return undefined; } } @@ -39064,20 +40924,20 @@ var ts; var modifierFlag = getFlagFromModifier(modifier); var nodes; switch (container.kind) { - case 207 /* ModuleBlock */: - case 228 /* SourceFile */: + case 209 /* ModuleBlock */: + case 230 /* SourceFile */: nodes = container.statements; break; - case 136 /* Constructor */: + case 137 /* Constructor */: nodes = container.parameters.concat(container.parent.members); break; - case 202 /* ClassDeclaration */: + case 204 /* ClassDeclaration */: nodes = container.members; // If we're an accessibility modifier, we're in an instance member and should search // the constructor's parameter list for instance members as well. if (modifierFlag & 112 /* AccessibilityModifier */) { var constructor = ts.forEach(container.members, function (member) { - return member.kind === 136 /* Constructor */ && member; + return member.kind === 137 /* Constructor */ && member; }); if (constructor) { nodes = nodes.concat(constructor.parameters); @@ -39125,13 +40985,13 @@ var ts; } function getGetAndSetOccurrences(accessorDeclaration) { var keywords = []; - tryPushAccessorKeyword(accessorDeclaration.symbol, 137 /* GetAccessor */); - tryPushAccessorKeyword(accessorDeclaration.symbol, 138 /* SetAccessor */); + tryPushAccessorKeyword(accessorDeclaration.symbol, 138 /* GetAccessor */); + tryPushAccessorKeyword(accessorDeclaration.symbol, 139 /* SetAccessor */); return ts.map(keywords, getHighlightSpanForNode); function tryPushAccessorKeyword(accessorSymbol, accessorKind) { var accessor = ts.getDeclarationOfKind(accessorSymbol, accessorKind); if (accessor) { - ts.forEach(accessor.getChildren(), function (child) { return pushKeywordIf(keywords, child, 116 /* GetKeyword */, 121 /* SetKeyword */); }); + ts.forEach(accessor.getChildren(), function (child) { return pushKeywordIf(keywords, child, 116 /* GetKeyword */, 122 /* SetKeyword */); }); } } } @@ -39149,7 +41009,7 @@ var ts; var keywords = []; if (pushKeywordIf(keywords, loopNode.getFirstToken(), 82 /* ForKeyword */, 100 /* WhileKeyword */, 75 /* DoKeyword */)) { // If we succeeded and got a do-while loop, then start looking for a 'while' keyword. - if (loopNode.kind === 185 /* DoStatement */) { + if (loopNode.kind === 187 /* DoStatement */) { var loopTokens = loopNode.getChildren(); for (var i = loopTokens.length - 1; i >= 0; i--) { if (pushKeywordIf(keywords, loopTokens[i], 100 /* WhileKeyword */)) { @@ -39170,13 +41030,13 @@ var ts; var owner = getBreakOrContinueOwner(breakOrContinueStatement); if (owner) { switch (owner.kind) { - case 187 /* ForStatement */: - case 188 /* ForInStatement */: - case 189 /* ForOfStatement */: - case 185 /* DoStatement */: - case 186 /* WhileStatement */: + case 189 /* ForStatement */: + case 190 /* ForInStatement */: + case 191 /* ForOfStatement */: + case 187 /* DoStatement */: + case 188 /* WhileStatement */: return getLoopBreakContinueOccurrences(owner); - case 194 /* SwitchStatement */: + case 196 /* SwitchStatement */: return getSwitchCaseDefaultOccurrences(owner); } } @@ -39230,7 +41090,7 @@ var ts; function getReturnOccurrences(returnStatement) { var func = ts.getContainingFunction(returnStatement); // If we didn't find a containing function with a block body, bail out. - if (!(func && hasKind(func.body, 180 /* Block */))) { + if (!(func && hasKind(func.body, 182 /* Block */))) { return undefined; } var keywords = []; @@ -39246,7 +41106,7 @@ var ts; function getIfElseOccurrences(ifStatement) { var keywords = []; // Traverse upwards through all parent if-statements linked by their else-branches. - while (hasKind(ifStatement.parent, 184 /* IfStatement */) && ifStatement.parent.elseStatement === ifStatement) { + while (hasKind(ifStatement.parent, 186 /* IfStatement */) && ifStatement.parent.elseStatement === ifStatement) { ifStatement = ifStatement.parent; } // Now traverse back down through the else branches, aggregating if/else keywords of if-statements. @@ -39259,7 +41119,7 @@ var ts; break; } } - if (!hasKind(ifStatement.elseStatement, 184 /* IfStatement */)) { + if (!hasKind(ifStatement.elseStatement, 186 /* IfStatement */)) { break; } ifStatement = ifStatement.elseStatement; @@ -39438,17 +41298,17 @@ var ts; } function isImportOrExportSpecifierName(location) { return location.parent && - (location.parent.kind === 214 /* ImportSpecifier */ || location.parent.kind === 218 /* ExportSpecifier */) && + (location.parent.kind === 216 /* ImportSpecifier */ || location.parent.kind === 220 /* ExportSpecifier */) && location.parent.propertyName === location; } function isImportOrExportSpecifierImportSymbol(symbol) { return (symbol.flags & 8388608 /* Alias */) && ts.forEach(symbol.declarations, function (declaration) { - return declaration.kind === 214 /* ImportSpecifier */ || declaration.kind === 218 /* ExportSpecifier */; + return declaration.kind === 216 /* ImportSpecifier */ || declaration.kind === 220 /* ExportSpecifier */; }); } function getDeclaredName(symbol, location) { // Special case for function expressions, whose names are solely local to their bodies. - var functionExpression = ts.forEach(symbol.declarations, function (d) { return d.kind === 163 /* FunctionExpression */ ? d : undefined; }); + var functionExpression = ts.forEach(symbol.declarations, function (d) { return d.kind === 165 /* FunctionExpression */ ? d : undefined; }); // When a name gets interned into a SourceFile's 'identifiers' Map, // its name is escaped and stored in the same way its symbol name/identifier // name should be stored. Function expressions, however, are a special case, @@ -39475,7 +41335,7 @@ var ts; return location.getText(); } // Special case for function expressions, whose names are solely local to their bodies. - var functionExpression = ts.forEach(declarations, function (d) { return d.kind === 163 /* FunctionExpression */ ? d : undefined; }); + var functionExpression = ts.forEach(declarations, function (d) { return d.kind === 165 /* FunctionExpression */ ? d : undefined; }); // When a name gets interned into a SourceFile's 'identifiers' Map, // its name is escaped and stored in the same way its symbol name/identifier // name should be stored. Function expressions, however, are a special case, @@ -39499,7 +41359,7 @@ var ts; if (symbol.flags & (4 /* Property */ | 8192 /* Method */)) { var privateDeclaration = ts.forEach(symbol.getDeclarations(), function (d) { return (d.flags & 32 /* Private */) ? d : undefined; }); if (privateDeclaration) { - return ts.getAncestor(privateDeclaration, 202 /* ClassDeclaration */); + return ts.getAncestor(privateDeclaration, 204 /* ClassDeclaration */); } } // If the symbol is an import we would like to find it if we are looking for what it imports. @@ -39525,7 +41385,7 @@ var ts; // Different declarations have different containers, bail out return undefined; } - if (container.kind === 228 /* SourceFile */ && !ts.isExternalModule(container)) { + if (container.kind === 230 /* SourceFile */ && !ts.isExternalModule(container)) { // This is a global variable and not an external module, any declaration defined // within this scope is visible outside the file return undefined; @@ -39713,13 +41573,13 @@ var ts; // Whether 'super' occurs in a static context within a class. var staticFlag = 128 /* Static */; switch (searchSpaceNode.kind) { - case 133 /* PropertyDeclaration */: - case 132 /* PropertySignature */: - case 135 /* MethodDeclaration */: - case 134 /* MethodSignature */: - case 136 /* Constructor */: - case 137 /* GetAccessor */: - case 138 /* SetAccessor */: + case 134 /* PropertyDeclaration */: + case 133 /* PropertySignature */: + case 136 /* MethodDeclaration */: + case 135 /* MethodSignature */: + case 137 /* Constructor */: + case 138 /* GetAccessor */: + case 139 /* SetAccessor */: staticFlag &= searchSpaceNode.flags; searchSpaceNode = searchSpaceNode.parent; // re-assign to be the owning class break; @@ -39751,27 +41611,27 @@ var ts; // Whether 'this' occurs in a static context within a class. var staticFlag = 128 /* Static */; switch (searchSpaceNode.kind) { - case 135 /* MethodDeclaration */: - case 134 /* MethodSignature */: + case 136 /* MethodDeclaration */: + case 135 /* MethodSignature */: if (ts.isObjectLiteralMethod(searchSpaceNode)) { break; } // fall through - case 133 /* PropertyDeclaration */: - case 132 /* PropertySignature */: - case 136 /* Constructor */: - case 137 /* GetAccessor */: - case 138 /* SetAccessor */: + case 134 /* PropertyDeclaration */: + case 133 /* PropertySignature */: + case 137 /* Constructor */: + case 138 /* GetAccessor */: + case 139 /* SetAccessor */: staticFlag &= searchSpaceNode.flags; searchSpaceNode = searchSpaceNode.parent; // re-assign to be the owning class break; - case 228 /* SourceFile */: + case 230 /* SourceFile */: if (ts.isExternalModule(searchSpaceNode)) { return undefined; } // Fall through - case 201 /* FunctionDeclaration */: - case 163 /* FunctionExpression */: + case 203 /* FunctionDeclaration */: + case 165 /* FunctionExpression */: break; // Computed properties in classes are not handled here because references to this are illegal, // so there is no point finding references to them. @@ -39780,7 +41640,7 @@ var ts; } var references = []; var possiblePositions; - if (searchSpaceNode.kind === 228 /* SourceFile */) { + if (searchSpaceNode.kind === 230 /* SourceFile */) { ts.forEach(sourceFiles, function (sourceFile) { possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "this", sourceFile.getStart(), sourceFile.getEnd()); getThisReferencesInFile(sourceFile, sourceFile, possiblePositions, references); @@ -39811,27 +41671,27 @@ var ts; } var container = ts.getThisContainer(node, false); switch (searchSpaceNode.kind) { - case 163 /* FunctionExpression */: - case 201 /* FunctionDeclaration */: + case 165 /* FunctionExpression */: + case 203 /* FunctionDeclaration */: if (searchSpaceNode.symbol === container.symbol) { result.push(getReferenceEntryFromNode(node)); } break; - case 135 /* MethodDeclaration */: - case 134 /* MethodSignature */: + case 136 /* MethodDeclaration */: + case 135 /* MethodSignature */: if (ts.isObjectLiteralMethod(searchSpaceNode) && searchSpaceNode.symbol === container.symbol) { result.push(getReferenceEntryFromNode(node)); } break; - case 202 /* ClassDeclaration */: + case 204 /* ClassDeclaration */: // Make sure the container belongs to the same class // and has the appropriate static modifier from the original container. if (container.parent && searchSpaceNode.symbol === container.parent.symbol && (container.flags & 128 /* Static */) === staticFlag) { result.push(getReferenceEntryFromNode(node)); } break; - case 228 /* SourceFile */: - if (container.kind === 228 /* SourceFile */ && !ts.isExternalModule(container)) { + case 230 /* SourceFile */: + if (container.kind === 230 /* SourceFile */ && !ts.isExternalModule(container)) { result.push(getReferenceEntryFromNode(node)); } break; @@ -39885,11 +41745,11 @@ var ts; function getPropertySymbolsFromBaseTypes(symbol, propertyName, result) { if (symbol && symbol.flags & (32 /* Class */ | 64 /* Interface */)) { ts.forEach(symbol.getDeclarations(), function (declaration) { - if (declaration.kind === 202 /* ClassDeclaration */) { + if (declaration.kind === 204 /* ClassDeclaration */) { getPropertySymbolFromTypeReference(ts.getClassExtendsHeritageClauseElement(declaration)); ts.forEach(ts.getClassImplementsHeritageClauseElements(declaration), getPropertySymbolFromTypeReference); } - else if (declaration.kind === 203 /* InterfaceDeclaration */) { + else if (declaration.kind === 205 /* InterfaceDeclaration */) { ts.forEach(ts.getInterfaceBaseTypeNodes(declaration), getPropertySymbolFromTypeReference); } }); @@ -39950,19 +41810,19 @@ var ts; if (isNameOfPropertyAssignment(node)) { var objectLiteral = node.parent.parent; var contextualType = typeChecker.getContextualType(objectLiteral); - var name_27 = node.text; + var name_28 = node.text; if (contextualType) { if (contextualType.flags & 16384 /* Union */) { // This is a union type, first see if the property we are looking for is a union property (i.e. exists in all types) // if not, search the constituent types for the property - var unionProperty = contextualType.getProperty(name_27); + var unionProperty = contextualType.getProperty(name_28); if (unionProperty) { return [unionProperty]; } else { var result_4 = []; ts.forEach(contextualType.types, function (t) { - var symbol = t.getProperty(name_27); + var symbol = t.getProperty(name_28); if (symbol) { result_4.push(symbol); } @@ -39971,7 +41831,7 @@ var ts; } } else { - var symbol_1 = contextualType.getProperty(name_27); + var symbol_1 = contextualType.getProperty(name_28); if (symbol_1) { return [symbol_1]; } @@ -40029,10 +41889,10 @@ var ts; } var parent = node.parent; if (parent) { - if (parent.kind === 169 /* PostfixUnaryExpression */ || parent.kind === 168 /* PrefixUnaryExpression */) { + if (parent.kind === 171 /* PostfixUnaryExpression */ || parent.kind === 170 /* PrefixUnaryExpression */) { return true; } - else if (parent.kind === 170 /* BinaryExpression */ && parent.left === node) { + else if (parent.kind === 172 /* BinaryExpression */ && parent.left === node) { var operator = parent.operatorToken.kind; return 53 /* FirstAssignment */ <= operator && operator <= 64 /* LastAssignment */; } @@ -40066,33 +41926,33 @@ var ts; } function getMeaningFromDeclaration(node) { switch (node.kind) { - case 130 /* Parameter */: - case 199 /* VariableDeclaration */: - case 153 /* BindingElement */: - case 133 /* PropertyDeclaration */: - case 132 /* PropertySignature */: - case 225 /* PropertyAssignment */: - case 226 /* ShorthandPropertyAssignment */: - case 227 /* EnumMember */: - case 135 /* MethodDeclaration */: - case 134 /* MethodSignature */: - case 136 /* Constructor */: - case 137 /* GetAccessor */: - case 138 /* SetAccessor */: - case 201 /* FunctionDeclaration */: - case 163 /* FunctionExpression */: - case 164 /* ArrowFunction */: - case 224 /* CatchClause */: + case 131 /* Parameter */: + case 201 /* VariableDeclaration */: + case 155 /* BindingElement */: + case 134 /* PropertyDeclaration */: + case 133 /* PropertySignature */: + case 227 /* PropertyAssignment */: + case 228 /* ShorthandPropertyAssignment */: + case 229 /* EnumMember */: + case 136 /* MethodDeclaration */: + case 135 /* MethodSignature */: + case 137 /* Constructor */: + case 138 /* GetAccessor */: + case 139 /* SetAccessor */: + case 203 /* FunctionDeclaration */: + case 165 /* FunctionExpression */: + case 166 /* ArrowFunction */: + case 226 /* CatchClause */: return 1 /* Value */; - case 129 /* TypeParameter */: - case 203 /* InterfaceDeclaration */: - case 204 /* TypeAliasDeclaration */: - case 146 /* TypeLiteral */: + case 130 /* TypeParameter */: + case 205 /* InterfaceDeclaration */: + case 206 /* TypeAliasDeclaration */: + case 148 /* TypeLiteral */: return 2 /* Type */; - case 202 /* ClassDeclaration */: - case 205 /* EnumDeclaration */: + case 204 /* ClassDeclaration */: + case 207 /* EnumDeclaration */: return 1 /* Value */ | 2 /* Type */; - case 206 /* ModuleDeclaration */: + case 208 /* ModuleDeclaration */: if (node.name.kind === 8 /* StringLiteral */) { return 4 /* Namespace */ | 1 /* Value */; } @@ -40102,15 +41962,15 @@ var ts; else { return 4 /* Namespace */; } - case 213 /* NamedImports */: - case 214 /* ImportSpecifier */: - case 209 /* ImportEqualsDeclaration */: - case 210 /* ImportDeclaration */: - case 215 /* ExportAssignment */: - case 216 /* ExportDeclaration */: + case 215 /* NamedImports */: + case 216 /* ImportSpecifier */: + case 211 /* ImportEqualsDeclaration */: + case 212 /* ImportDeclaration */: + case 217 /* ExportAssignment */: + case 218 /* ExportDeclaration */: return 1 /* Value */ | 2 /* Type */ | 4 /* Namespace */; // An external module can be a Value - case 228 /* SourceFile */: + case 230 /* SourceFile */: return 4 /* Namespace */ | 1 /* Value */; } return 1 /* Value */ | 2 /* Type */ | 4 /* Namespace */; @@ -40120,7 +41980,8 @@ var ts; if (ts.isRightSideOfQualifiedNameOrPropertyAccess(node)) { node = node.parent; } - return node.parent.kind === 142 /* TypeReference */ || node.parent.kind === 177 /* ExpressionWithTypeArguments */; + return node.parent.kind === 144 /* TypeReference */ || + (node.parent.kind === 179 /* ExpressionWithTypeArguments */ && !ts.isExpressionWithTypeArgumentsInClassExtendsClause(node.parent)); } function isNamespaceReference(node) { return isQualifiedNameNamespaceReference(node) || isPropertyAccessNamespaceReference(node); @@ -40128,32 +41989,32 @@ var ts; function isPropertyAccessNamespaceReference(node) { var root = node; var isLastClause = true; - if (root.parent.kind === 156 /* PropertyAccessExpression */) { - while (root.parent && root.parent.kind === 156 /* PropertyAccessExpression */) { + if (root.parent.kind === 158 /* PropertyAccessExpression */) { + while (root.parent && root.parent.kind === 158 /* PropertyAccessExpression */) { root = root.parent; } isLastClause = root.name === node; } - if (!isLastClause && root.parent.kind === 177 /* ExpressionWithTypeArguments */ && root.parent.parent.kind === 223 /* HeritageClause */) { + if (!isLastClause && root.parent.kind === 179 /* ExpressionWithTypeArguments */ && root.parent.parent.kind === 225 /* HeritageClause */) { var decl = root.parent.parent.parent; - return (decl.kind === 202 /* ClassDeclaration */ && root.parent.parent.token === 102 /* ImplementsKeyword */) || - (decl.kind === 203 /* InterfaceDeclaration */ && root.parent.parent.token === 79 /* ExtendsKeyword */); + return (decl.kind === 204 /* ClassDeclaration */ && root.parent.parent.token === 102 /* ImplementsKeyword */) || + (decl.kind === 205 /* InterfaceDeclaration */ && root.parent.parent.token === 79 /* ExtendsKeyword */); } return false; } function isQualifiedNameNamespaceReference(node) { var root = node; var isLastClause = true; - if (root.parent.kind === 127 /* QualifiedName */) { - while (root.parent && root.parent.kind === 127 /* QualifiedName */) { + if (root.parent.kind === 128 /* QualifiedName */) { + while (root.parent && root.parent.kind === 128 /* QualifiedName */) { root = root.parent; } isLastClause = root.right === node; } - return root.parent.kind === 142 /* TypeReference */ && !isLastClause; + return root.parent.kind === 144 /* TypeReference */ && !isLastClause; } function isInRightSideOfImport(node) { - while (node.parent.kind === 127 /* QualifiedName */) { + while (node.parent.kind === 128 /* QualifiedName */) { node = node.parent; } return ts.isInternalModuleImportEqualsDeclaration(node.parent) && node.parent.moduleReference === node; @@ -40163,15 +42024,15 @@ var ts; // import a = |b|; // Namespace // import a = |b.c|; // Value, type, namespace // import a = |b.c|.d; // Namespace - if (node.parent.kind === 127 /* QualifiedName */ && + if (node.parent.kind === 128 /* QualifiedName */ && node.parent.right === node && - node.parent.parent.kind === 209 /* ImportEqualsDeclaration */) { + node.parent.parent.kind === 211 /* ImportEqualsDeclaration */) { return 1 /* Value */ | 2 /* Type */ | 4 /* Namespace */; } return 4 /* Namespace */; } function getMeaningFromLocation(node) { - if (node.parent.kind === 215 /* ExportAssignment */) { + if (node.parent.kind === 217 /* ExportAssignment */) { return 1 /* Value */ | 2 /* Type */ | 4 /* Namespace */; } else if (isInRightSideOfImport(node)) { @@ -40211,8 +42072,8 @@ var ts; return; } switch (node.kind) { - case 156 /* PropertyAccessExpression */: - case 127 /* QualifiedName */: + case 158 /* PropertyAccessExpression */: + case 128 /* QualifiedName */: case 8 /* StringLiteral */: case 80 /* FalseKeyword */: case 95 /* TrueKeyword */: @@ -40235,7 +42096,7 @@ var ts; // If this is name of a module declarations, check if this is right side of dotted module name // If parent of the module declaration which is parent of this node is module declaration and its body is the module declaration that this node is name of // Then this name is name from dotted module - if (nodeForStartPos.parent.parent.kind === 206 /* ModuleDeclaration */ && + if (nodeForStartPos.parent.parent.kind === 208 /* ModuleDeclaration */ && nodeForStartPos.parent.parent.body === nodeForStartPos.parent) { // Use parent module declarations name for start pos nodeForStartPos = nodeForStartPos.parent.parent.name; @@ -40269,6 +42130,7 @@ var ts; var sourceFile = getValidSourceFile(fileName); var typeChecker = program.getTypeChecker(); var result = []; + var classifiableNames = program.getClassifiableNames(); processNode(sourceFile); return { spans: result, endOfLineState: 0 /* None */ }; function pushClassification(start, length, type) { @@ -40278,6 +42140,9 @@ var ts; } function classifySymbol(symbol, meaningAtPosition) { var flags = symbol.getFlags(); + if ((flags & 788448 /* Classifiable */) === 0 /* None */) { + return; + } if (flags & 32 /* Class */) { return 11 /* className */; } @@ -40310,19 +42175,26 @@ var ts; */ function hasValueSideModule(symbol) { return ts.forEach(symbol.declarations, function (declaration) { - return declaration.kind === 206 /* ModuleDeclaration */ && ts.getModuleInstanceState(declaration) == 1 /* Instantiated */; + return declaration.kind === 208 /* ModuleDeclaration */ && + ts.getModuleInstanceState(declaration) === 1 /* Instantiated */; }); } } function processNode(node) { // Only walk into nodes that intersect the requested span. - if (node && ts.textSpanIntersectsWith(span, node.getStart(), node.getWidth())) { - if (node.kind === 65 /* Identifier */ && node.getWidth() > 0) { - var symbol = typeChecker.getSymbolAtLocation(node); - if (symbol) { - var type = classifySymbol(symbol, getMeaningFromLocation(node)); - if (type) { - pushClassification(node.getStart(), node.getWidth(), type); + if (node && ts.textSpanIntersectsWith(span, node.getFullStart(), node.getFullWidth())) { + if (node.kind === 65 /* Identifier */ && !ts.nodeIsMissing(node)) { + var identifier = node; + // 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[identifier.text]) { + var symbol = typeChecker.getSymbolAtLocation(node); + if (symbol) { + var type = classifySymbol(symbol, getMeaningFromLocation(node)); + if (type) { + pushClassification(node.getStart(), node.getWidth(), type); + } } } } @@ -40348,6 +42220,7 @@ var ts; case 15 /* typeParameterName */: return ClassificationTypeNames.typeParameterName; case 16 /* typeAliasName */: return ClassificationTypeNames.typeAliasName; case 17 /* parameterName */: return ClassificationTypeNames.parameterName; + case 18 /* docCommentTagName */: return ClassificationTypeNames.docCommentTagName; } } function convertClassifications(classifications) { @@ -40368,6 +42241,8 @@ var ts; function getEncodedSyntacticClassifications(fileName, span) { // doesn't use compiler - no need to synchronize with host var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); + var spanStart = span.start; + var spanLength = span.length; // Make a scanner we can get trivia from. var triviaScanner = ts.createScanner(2 /* Latest */, false, sourceFile.text); var mergeConflictScanner = ts.createScanner(2 /* Latest */, false, sourceFile.text); @@ -40379,46 +42254,123 @@ var ts; result.push(length); result.push(type); } - function classifyLeadingTrivia(token) { - var tokenStart = ts.skipTrivia(sourceFile.text, token.pos, false); - if (tokenStart === token.pos) { - return; - } - // token has trivia. Classify them appropriately. + function classifyLeadingTriviaAndGetTokenStart(token) { triviaScanner.setTextPos(token.pos); while (true) { var start = triviaScanner.getTextPos(); + // only bother scanning if we have something that could be trivia. + if (!ts.couldStartTrivia(sourceFile.text, start)) { + return start; + } var kind = triviaScanner.scan(); var end = triviaScanner.getTextPos(); var width = end - start; // The moment we get something that isn't trivia, then stop processing. if (!ts.isTrivia(kind)) { - return; + return start; + } + // Don't bother with newlines/whitespace. + if (kind === 4 /* NewLineTrivia */ || kind === 5 /* WhitespaceTrivia */) { + continue; } // Only bother with the trivia if it at least intersects the span of interest. - if (ts.textSpanIntersectsWith(span, start, width)) { - if (ts.isComment(kind)) { - // Simple comment. Just add as is. + if (ts.isComment(kind)) { + classifyComment(token, kind, start, width); + // Classifying a comment might cause us to reuse the trivia scanner + // (because of jsdoc comments). So after we classify the comment make + // sure we set the scanner position back to where it needs to be. + triviaScanner.setTextPos(end); + continue; + } + if (kind === 6 /* ConflictMarkerTrivia */) { + var text = sourceFile.text; + var ch = text.charCodeAt(start); + // for the <<<<<<< and >>>>>>> markers, we just add them in as comments + // in the classification stream. + if (ch === 60 /* lessThan */ || ch === 62 /* greaterThan */) { pushClassification(start, width, 1 /* comment */); continue; } - if (kind === 6 /* ConflictMarkerTrivia */) { - var text = sourceFile.text; - var ch = text.charCodeAt(start); - // for the <<<<<<< and >>>>>>> markers, we just add them in as comments - // in the classification stream. - if (ch === 60 /* lessThan */ || ch === 62 /* greaterThan */) { - 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 */); - classifyDisabledMergeCode(text, start, end); - } + // 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 */); + classifyDisabledMergeCode(text, start, end); } } } + function classifyComment(token, kind, start, width) { + if (kind === 3 /* MultiLineCommentTrivia */) { + // See if this is a doc comment. If so, we'll classify certain portions of it + // specially. + var docCommentAndDiagnostics = ts.parseIsolatedJSDocComment(sourceFile.text, start, width); + if (docCommentAndDiagnostics && docCommentAndDiagnostics.jsDocComment) { + docCommentAndDiagnostics.jsDocComment.parent = token; + classifyJSDocComment(docCommentAndDiagnostics.jsDocComment); + return; + } + } + // Simple comment. Just add as is. + pushCommentRange(start, width); + } + function pushCommentRange(start, width) { + pushClassification(start, width, 1 /* comment */); + } + function classifyJSDocComment(docComment) { + var pos = docComment.pos; + for (var _i = 0, _a = docComment.tags; _i < _a.length; _i++) { + var tag = _a[_i]; + // As we walk through each tag, classify the portion of text from the end of + // the last tag (or the start of the entire doc comment) as 'comment'. + 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 */); + pos = tag.tagName.end; + switch (tag.kind) { + case 249 /* JSDocParameterTag */: + processJSDocParameterTag(tag); + break; + case 252 /* JSDocTemplateTag */: + processJSDocTemplateTag(tag); + break; + case 251 /* JSDocTypeTag */: + processElement(tag.typeExpression); + break; + case 250 /* JSDocReturnTag */: + processElement(tag.typeExpression); + break; + } + pos = tag.end; + } + if (pos !== docComment.end) { + pushCommentRange(pos, docComment.end - pos); + } + 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.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; + } + } + } + function processJSDocTemplateTag(tag) { + for (var _i = 0, _a = tag.getChildren(); _i < _a.length; _i++) { + var child = _a[_i]; + processElement(child); + } + } 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. @@ -40443,11 +42395,16 @@ var ts; } } function classifyToken(token) { - classifyLeadingTrivia(token); - if (token.getWidth() > 0) { + if (ts.nodeIsMissing(token)) { + return; + } + var tokenStart = classifyLeadingTriviaAndGetTokenStart(token); + var tokenWidth = token.end - tokenStart; + ts.Debug.assert(tokenWidth >= 0); + if (tokenWidth > 0) { var type = classifyTokenType(token.kind, token); if (type) { - pushClassification(token.getStart(), token.getWidth(), type); + pushClassification(tokenStart, tokenWidth, type); } } } @@ -40471,16 +42428,16 @@ var ts; if (token) { if (tokenKind === 53 /* EqualsToken */) { // the '=' in a variable declaration is special cased here. - if (token.parent.kind === 199 /* VariableDeclaration */ || - token.parent.kind === 133 /* PropertyDeclaration */ || - token.parent.kind === 130 /* Parameter */) { + if (token.parent.kind === 201 /* VariableDeclaration */ || + token.parent.kind === 134 /* PropertyDeclaration */ || + token.parent.kind === 131 /* Parameter */) { return 5 /* operator */; } } - if (token.parent.kind === 170 /* BinaryExpression */ || - token.parent.kind === 168 /* PrefixUnaryExpression */ || - token.parent.kind === 169 /* PostfixUnaryExpression */ || - token.parent.kind === 171 /* ConditionalExpression */) { + if (token.parent.kind === 172 /* BinaryExpression */ || + token.parent.kind === 170 /* PrefixUnaryExpression */ || + token.parent.kind === 171 /* PostfixUnaryExpression */ || + token.parent.kind === 173 /* ConditionalExpression */) { return 5 /* operator */; } } @@ -40503,32 +42460,32 @@ var ts; else if (tokenKind === 65 /* Identifier */) { if (token) { switch (token.parent.kind) { - case 202 /* ClassDeclaration */: + case 204 /* ClassDeclaration */: if (token.parent.name === token) { return 11 /* className */; } return; - case 129 /* TypeParameter */: + case 130 /* TypeParameter */: if (token.parent.name === token) { return 15 /* typeParameterName */; } return; - case 203 /* InterfaceDeclaration */: + case 205 /* InterfaceDeclaration */: if (token.parent.name === token) { return 13 /* interfaceName */; } return; - case 205 /* EnumDeclaration */: + case 207 /* EnumDeclaration */: if (token.parent.name === token) { return 12 /* enumName */; } return; - case 206 /* ModuleDeclaration */: + case 208 /* ModuleDeclaration */: if (token.parent.name === token) { return 14 /* moduleName */; } return; - case 130 /* Parameter */: + case 131 /* Parameter */: if (token.parent.name === token) { return 17 /* parameterName */; } @@ -40539,11 +42496,14 @@ var ts; } } function processElement(element) { + if (!element) { + return; + } // Ignore nodes that don't intersect the original span to classify. - if (ts.textSpanIntersectsWith(span, element.getFullStart(), element.getFullWidth())) { - var children = element.getChildren(); - for (var _i = 0; _i < children.length; _i++) { - var child = children[_i]; + if (ts.decodedTextSpanIntersectsWith(spanStart, spanLength, element.pos, element.getFullWidth())) { + var children = element.getChildren(sourceFile); + for (var i = 0, n = children.length; i < n; i++) { + var child = children[i]; if (ts.isToken(child)) { classifyToken(child); } @@ -40870,7 +42830,7 @@ var ts; // 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 === 220 /* ExternalModuleReference */ || + node.parent.kind === 222 /* ExternalModuleReference */ || isArgumentOfElementAccessExpression(node)) { nameTable[node.text] = node.text; } @@ -40883,7 +42843,7 @@ var ts; function isArgumentOfElementAccessExpression(node) { return node && node.parent && - node.parent.kind === 157 /* ElementAccessExpression */ && + node.parent.kind === 159 /* ElementAccessExpression */ && node.parent.argumentExpression === node; } /// Classifier @@ -40931,7 +42891,7 @@ var ts; function canFollow(keyword1, keyword2) { if (ts.isAccessibilityModifier(keyword1)) { if (keyword2 === 116 /* GetKeyword */ || - keyword2 === 121 /* SetKeyword */ || + keyword2 === 122 /* SetKeyword */ || keyword2 === 114 /* ConstructorKeyword */ || keyword2 === 109 /* StaticKeyword */) { // Allow things like "public get", "public constructor" and "public static". @@ -40952,7 +42912,7 @@ var ts; var lastEnd = 0; for (var i = 0, n = dense.length; i < n; i += 3) { var start = dense[i]; - var length_1 = dense[i + 1]; + var length_2 = dense[i + 1]; var type = dense[i + 2]; // Make a whitespace entry between the last item and this one. if (lastEnd >= 0) { @@ -40961,8 +42921,8 @@ var ts; entries.push({ length: whitespaceLength_1, classification: TokenClass.Whitespace }); } } - entries.push({ length: length_1, classification: convertClassification(type) }); - lastEnd = start + length_1; + entries.push({ length: length_2, classification: convertClassification(type) }); + lastEnd = start + length_2; } var whitespaceLength = text.length - lastEnd; if (whitespaceLength > 0) { @@ -41090,10 +43050,10 @@ var ts; angleBracketStack--; } else if (token === 112 /* AnyKeyword */ || - token === 122 /* StringKeyword */ || - token === 120 /* NumberKeyword */ || + token === 123 /* StringKeyword */ || + token === 121 /* NumberKeyword */ || token === 113 /* BooleanKeyword */ || - token === 123 /* SymbolKeyword */) { + token === 124 /* SymbolKeyword */) { if (angleBracketStack > 0 && !syntacticClassifierAbsent) { // If it looks like we're could be in something generic, don't classify this // as a keyword. We may just get overwritten by the syntactic classifier, @@ -41264,7 +43224,7 @@ var ts; } } function isKeyword(token) { - return token >= 66 /* FirstKeyword */ && token <= 126 /* LastKeyword */; + return token >= 66 /* FirstKeyword */ && token <= 127 /* LastKeyword */; } function classFromKind(token) { if (isKeyword(token)) { @@ -41322,7 +43282,7 @@ var ts; getNodeConstructor: function (kind) { function Node() { } - var proto = kind === 228 /* SourceFile */ ? new SourceFileObject() : new NodeObject(); + var proto = kind === 230 /* SourceFile */ ? new SourceFileObject() : new NodeObject(); proto.kind = kind; proto.pos = 0; proto.end = 0; @@ -41392,125 +43352,125 @@ var ts; function spanInNode(node) { if (node) { if (ts.isExpression(node)) { - if (node.parent.kind === 185 /* DoStatement */) { + if (node.parent.kind === 187 /* DoStatement */) { // Set span as if on while keyword return spanInPreviousNode(node); } - if (node.parent.kind === 187 /* ForStatement */) { + if (node.parent.kind === 189 /* ForStatement */) { // For now lets set the span on this expression, fix it later return textSpan(node); } - if (node.parent.kind === 170 /* BinaryExpression */ && node.parent.operatorToken.kind === 23 /* CommaToken */) { + if (node.parent.kind === 172 /* BinaryExpression */ && node.parent.operatorToken.kind === 23 /* CommaToken */) { // if this is comma expression, the breakpoint is possible in this expression return textSpan(node); } - if (node.parent.kind == 164 /* ArrowFunction */ && node.parent.body == node) { + if (node.parent.kind === 166 /* ArrowFunction */ && node.parent.body === node) { // If this is body of arrow function, it is allowed to have the breakpoint return textSpan(node); } } switch (node.kind) { - case 181 /* VariableStatement */: + case 183 /* VariableStatement */: // Span on first variable declaration return spanInVariableDeclaration(node.declarationList.declarations[0]); - case 199 /* VariableDeclaration */: - case 133 /* PropertyDeclaration */: - case 132 /* PropertySignature */: + case 201 /* VariableDeclaration */: + case 134 /* PropertyDeclaration */: + case 133 /* PropertySignature */: return spanInVariableDeclaration(node); - case 130 /* Parameter */: + case 131 /* Parameter */: return spanInParameterDeclaration(node); - case 201 /* FunctionDeclaration */: - case 135 /* MethodDeclaration */: - case 134 /* MethodSignature */: - case 137 /* GetAccessor */: - case 138 /* SetAccessor */: - case 136 /* Constructor */: - case 163 /* FunctionExpression */: - case 164 /* ArrowFunction */: + case 203 /* FunctionDeclaration */: + case 136 /* MethodDeclaration */: + case 135 /* MethodSignature */: + case 138 /* GetAccessor */: + case 139 /* SetAccessor */: + case 137 /* Constructor */: + case 165 /* FunctionExpression */: + case 166 /* ArrowFunction */: return spanInFunctionDeclaration(node); - case 180 /* Block */: + case 182 /* Block */: if (ts.isFunctionBlock(node)) { return spanInFunctionBlock(node); } // Fall through - case 207 /* ModuleBlock */: + case 209 /* ModuleBlock */: return spanInBlock(node); - case 224 /* CatchClause */: + case 226 /* CatchClause */: return spanInBlock(node.block); - case 183 /* ExpressionStatement */: + case 185 /* ExpressionStatement */: // span on the expression return textSpan(node.expression); - case 192 /* ReturnStatement */: + case 194 /* ReturnStatement */: // span on return keyword and expression if present return textSpan(node.getChildAt(0), node.expression); - case 186 /* WhileStatement */: + case 188 /* WhileStatement */: // Span on while(...) return textSpan(node, ts.findNextToken(node.expression, node)); - case 185 /* DoStatement */: + case 187 /* DoStatement */: // span in statement of the do statement return spanInNode(node.statement); - case 198 /* DebuggerStatement */: + case 200 /* DebuggerStatement */: // span on debugger keyword return textSpan(node.getChildAt(0)); - case 184 /* IfStatement */: + case 186 /* IfStatement */: // set on if(..) span return textSpan(node, ts.findNextToken(node.expression, node)); - case 195 /* LabeledStatement */: + case 197 /* LabeledStatement */: // span in statement return spanInNode(node.statement); - case 191 /* BreakStatement */: - case 190 /* ContinueStatement */: + case 193 /* BreakStatement */: + case 192 /* ContinueStatement */: // On break or continue keyword and label if present return textSpan(node.getChildAt(0), node.label); - case 187 /* ForStatement */: + case 189 /* ForStatement */: return spanInForStatement(node); - case 188 /* ForInStatement */: - case 189 /* ForOfStatement */: + case 190 /* ForInStatement */: + case 191 /* ForOfStatement */: // span on for (a in ...) return textSpan(node, ts.findNextToken(node.expression, node)); - case 194 /* SwitchStatement */: + case 196 /* SwitchStatement */: // span on switch(...) return textSpan(node, ts.findNextToken(node.expression, node)); - case 221 /* CaseClause */: - case 222 /* DefaultClause */: + case 223 /* CaseClause */: + case 224 /* DefaultClause */: // span in first statement of the clause return spanInNode(node.statements[0]); - case 197 /* TryStatement */: + case 199 /* TryStatement */: // span in try block return spanInBlock(node.tryBlock); - case 196 /* ThrowStatement */: + case 198 /* ThrowStatement */: // span in throw ... return textSpan(node, node.expression); - case 215 /* ExportAssignment */: + case 217 /* ExportAssignment */: // span on export = id return textSpan(node, node.expression); - case 209 /* ImportEqualsDeclaration */: + case 211 /* ImportEqualsDeclaration */: // import statement without including semicolon return textSpan(node, node.moduleReference); - case 210 /* ImportDeclaration */: + case 212 /* ImportDeclaration */: // import statement without including semicolon return textSpan(node, node.moduleSpecifier); - case 216 /* ExportDeclaration */: + case 218 /* ExportDeclaration */: // import statement without including semicolon return textSpan(node, node.moduleSpecifier); - case 206 /* ModuleDeclaration */: + case 208 /* ModuleDeclaration */: // span on complete module if it is instantiated if (ts.getModuleInstanceState(node) !== 1 /* Instantiated */) { return undefined; } - case 202 /* ClassDeclaration */: - case 205 /* EnumDeclaration */: - case 227 /* EnumMember */: - case 158 /* CallExpression */: - case 159 /* NewExpression */: + case 204 /* ClassDeclaration */: + case 207 /* EnumDeclaration */: + case 229 /* EnumMember */: + case 160 /* CallExpression */: + case 161 /* NewExpression */: // span on complete node return textSpan(node); - case 193 /* WithStatement */: + case 195 /* WithStatement */: // span in statement return spanInNode(node.statement); // No breakpoint in interface, type alias - case 203 /* InterfaceDeclaration */: - case 204 /* TypeAliasDeclaration */: + case 205 /* InterfaceDeclaration */: + case 206 /* TypeAliasDeclaration */: return undefined; // Tokens: case 22 /* SemicolonToken */: @@ -41540,11 +43500,11 @@ var ts; return spanInNextNode(node); default: // If this is name of property assignment, set breakpoint in the initializer - if (node.parent.kind === 225 /* PropertyAssignment */ && node.parent.name === node) { + if (node.parent.kind === 227 /* PropertyAssignment */ && node.parent.name === node) { return spanInNode(node.parent.initializer); } // Breakpoint in type assertion goes to its operand - if (node.parent.kind === 161 /* TypeAssertionExpression */ && node.parent.type === node) { + if (node.parent.kind === 163 /* TypeAssertionExpression */ && node.parent.type === node) { return spanInNode(node.parent.expression); } // return type of function go to previous token @@ -41557,12 +43517,12 @@ var ts; } function spanInVariableDeclaration(variableDeclaration) { // If declaration of for in statement, just set the span in parent - if (variableDeclaration.parent.parent.kind === 188 /* ForInStatement */ || - variableDeclaration.parent.parent.kind === 189 /* ForOfStatement */) { + if (variableDeclaration.parent.parent.kind === 190 /* ForInStatement */ || + variableDeclaration.parent.parent.kind === 191 /* ForOfStatement */) { return spanInNode(variableDeclaration.parent.parent); } - var isParentVariableStatement = variableDeclaration.parent.parent.kind === 181 /* VariableStatement */; - var isDeclarationOfForStatement = variableDeclaration.parent.parent.kind === 187 /* ForStatement */ && ts.contains(variableDeclaration.parent.parent.initializer.declarations, variableDeclaration); + var isParentVariableStatement = variableDeclaration.parent.parent.kind === 183 /* VariableStatement */; + var isDeclarationOfForStatement = variableDeclaration.parent.parent.kind === 189 /* ForStatement */ && ts.contains(variableDeclaration.parent.parent.initializer.declarations, variableDeclaration); var declarations = isParentVariableStatement ? variableDeclaration.parent.parent.declarationList.declarations : isDeclarationOfForStatement @@ -41616,7 +43576,7 @@ var ts; } function canFunctionHaveSpanInWholeDeclaration(functionDeclaration) { return !!(functionDeclaration.flags & 1 /* Export */) || - (functionDeclaration.parent.kind === 202 /* ClassDeclaration */ && functionDeclaration.kind !== 136 /* Constructor */); + (functionDeclaration.parent.kind === 204 /* ClassDeclaration */ && functionDeclaration.kind !== 137 /* Constructor */); } function spanInFunctionDeclaration(functionDeclaration) { // No breakpoints in the function signature @@ -41639,18 +43599,18 @@ var ts; } function spanInBlock(block) { switch (block.parent.kind) { - case 206 /* ModuleDeclaration */: + case 208 /* ModuleDeclaration */: if (ts.getModuleInstanceState(block.parent) !== 1 /* Instantiated */) { return undefined; } // Set on parent if on same line otherwise on first statement - case 186 /* WhileStatement */: - case 184 /* IfStatement */: - case 188 /* ForInStatement */: - case 189 /* ForOfStatement */: + case 188 /* WhileStatement */: + case 186 /* IfStatement */: + case 190 /* ForInStatement */: + case 191 /* ForOfStatement */: return spanInNodeIfStartsOnSameLine(block.parent, block.statements[0]); // Set span on previous token if it starts on same line otherwise on the first statement of the block - case 187 /* ForStatement */: + case 189 /* ForStatement */: return spanInNodeIfStartsOnSameLine(ts.findPrecedingToken(block.pos, sourceFile, block.parent), block.statements[0]); } // Default action is to set on first statement @@ -41658,7 +43618,7 @@ var ts; } function spanInForStatement(forStatement) { if (forStatement.initializer) { - if (forStatement.initializer.kind === 200 /* VariableDeclarationList */) { + if (forStatement.initializer.kind === 202 /* VariableDeclarationList */) { var variableDeclarationList = forStatement.initializer; if (variableDeclarationList.declarations.length > 0) { return spanInNode(variableDeclarationList.declarations[0]); @@ -41678,13 +43638,13 @@ var ts; // Tokens: function spanInOpenBraceToken(node) { switch (node.parent.kind) { - case 205 /* EnumDeclaration */: + case 207 /* EnumDeclaration */: var enumDeclaration = node.parent; return spanInNodeIfStartsOnSameLine(ts.findPrecedingToken(node.pos, sourceFile, node.parent), enumDeclaration.members.length ? enumDeclaration.members[0] : enumDeclaration.getLastToken(sourceFile)); - case 202 /* ClassDeclaration */: + case 204 /* ClassDeclaration */: var classDeclaration = node.parent; return spanInNodeIfStartsOnSameLine(ts.findPrecedingToken(node.pos, sourceFile, node.parent), classDeclaration.members.length ? classDeclaration.members[0] : classDeclaration.getLastToken(sourceFile)); - case 208 /* CaseBlock */: + case 210 /* CaseBlock */: return spanInNodeIfStartsOnSameLine(node.parent.parent, node.parent.clauses[0]); } // Default to parent node @@ -41692,25 +43652,25 @@ var ts; } function spanInCloseBraceToken(node) { switch (node.parent.kind) { - case 207 /* ModuleBlock */: + case 209 /* ModuleBlock */: // If this is not instantiated module block no bp span if (ts.getModuleInstanceState(node.parent.parent) !== 1 /* Instantiated */) { return undefined; } - case 205 /* EnumDeclaration */: - case 202 /* ClassDeclaration */: + case 207 /* EnumDeclaration */: + case 204 /* ClassDeclaration */: // Span on close brace token return textSpan(node); - case 180 /* Block */: + case 182 /* Block */: if (ts.isFunctionBlock(node.parent)) { // Span on close brace token return textSpan(node); } // fall through. - case 224 /* CatchClause */: + case 226 /* CatchClause */: return spanInNode(ts.lastOrUndefined(node.parent.statements)); ; - case 208 /* CaseBlock */: + case 210 /* CaseBlock */: // breakpoint in last statement of the last clause var caseBlock = node.parent; var lastClause = ts.lastOrUndefined(caseBlock.clauses); @@ -41724,7 +43684,7 @@ var ts; } } function spanInOpenParenToken(node) { - if (node.parent.kind === 185 /* DoStatement */) { + if (node.parent.kind === 187 /* DoStatement */) { // Go to while keyword and do action instead return spanInPreviousNode(node); } @@ -41734,17 +43694,17 @@ var ts; function spanInCloseParenToken(node) { // Is this close paren token of parameter list, set span in previous token switch (node.parent.kind) { - case 163 /* FunctionExpression */: - case 201 /* FunctionDeclaration */: - case 164 /* ArrowFunction */: - case 135 /* MethodDeclaration */: - case 134 /* MethodSignature */: - case 137 /* GetAccessor */: - case 138 /* SetAccessor */: - case 136 /* Constructor */: - case 186 /* WhileStatement */: - case 185 /* DoStatement */: - case 187 /* ForStatement */: + case 165 /* FunctionExpression */: + case 203 /* FunctionDeclaration */: + case 166 /* ArrowFunction */: + case 136 /* MethodDeclaration */: + case 135 /* MethodSignature */: + case 138 /* GetAccessor */: + case 139 /* SetAccessor */: + case 137 /* Constructor */: + case 188 /* WhileStatement */: + case 187 /* DoStatement */: + case 189 /* ForStatement */: return spanInPreviousNode(node); // Default to parent node default: @@ -41755,19 +43715,19 @@ var ts; } function spanInColonToken(node) { // Is this : specifying return annotation of the function declaration - if (ts.isFunctionLike(node.parent) || node.parent.kind === 225 /* PropertyAssignment */) { + if (ts.isFunctionLike(node.parent) || node.parent.kind === 227 /* PropertyAssignment */) { return spanInPreviousNode(node); } return spanInNode(node.parent); } function spanInGreaterThanOrLessThanToken(node) { - if (node.parent.kind === 161 /* TypeAssertionExpression */) { + if (node.parent.kind === 163 /* TypeAssertionExpression */) { return spanInNode(node.parent.expression); } return spanInNode(node.parent); } function spanInWhileKeyword(node) { - if (node.parent.kind === 185 /* DoStatement */) { + if (node.parent.kind === 187 /* DoStatement */) { // Set span on while expression return textSpan(node, ts.findNextToken(node.parent.expression, node.parent)); } @@ -41818,6 +43778,7 @@ var ts; ScriptSnapshotShimAdapter.prototype.getChangeRange = function (oldSnapshot) { var oldSnapshotShim = oldSnapshot; var encoded = this.scriptSnapshotShim.getChangeRange(oldSnapshotShim.scriptSnapshotShim); + // TODO: should this be '==='? if (encoded == null) { return null; } @@ -41829,12 +43790,18 @@ var ts; var LanguageServiceShimHostAdapter = (function () { function LanguageServiceShimHostAdapter(shimHost) { this.shimHost = shimHost; + this.loggingEnabled = false; + this.tracingEnabled = false; } LanguageServiceShimHostAdapter.prototype.log = function (s) { - this.shimHost.log(s); + if (this.loggingEnabled) { + this.shimHost.log(s); + } }; LanguageServiceShimHostAdapter.prototype.trace = function (s) { - this.shimHost.trace(s); + if (this.tracingEnabled) { + this.shimHost.trace(s); + } }; LanguageServiceShimHostAdapter.prototype.error = function (s) { this.shimHost.error(s); @@ -41846,8 +43813,12 @@ var ts; } return this.shimHost.getProjectVersion(); }; + LanguageServiceShimHostAdapter.prototype.useCaseSensitiveFileNames = function () { + return this.shimHost.useCaseSensitiveFileNames ? this.shimHost.useCaseSensitiveFileNames() : false; + }; LanguageServiceShimHostAdapter.prototype.getCompilationSettings = function () { var settingsJson = this.shimHost.getCompilationSettings(); + // TODO: should this be '==='? if (settingsJson == null || settingsJson == "") { throw Error("LanguageServiceShimHostAdapter.getCompilationSettings: empty compilationSettings"); return null; @@ -41913,13 +43884,13 @@ var ts; return CoreServicesShimHostAdapter; })(); ts.CoreServicesShimHostAdapter = CoreServicesShimHostAdapter; - function simpleForwardCall(logger, actionDescription, action, noPerfLogging) { - if (!noPerfLogging) { + function simpleForwardCall(logger, actionDescription, action, logPerformance) { + if (logPerformance) { logger.log(actionDescription); var start = Date.now(); } var result = action(); - if (!noPerfLogging) { + if (logPerformance) { var end = Date.now(); logger.log(actionDescription + " completed in " + (end - start) + " msec"); if (typeof (result) === "string") { @@ -41932,9 +43903,9 @@ var ts; } return result; } - function forwardJSONCall(logger, actionDescription, action, noPerfLogging) { + function forwardJSONCall(logger, actionDescription, action, logPerformance) { try { - var result = simpleForwardCall(logger, actionDescription, action, noPerfLogging); + var result = simpleForwardCall(logger, actionDescription, action, logPerformance); return JSON.stringify({ result: result }); } catch (err) { @@ -41976,10 +43947,11 @@ var ts; _super.call(this, factory); this.host = host; this.languageService = languageService; + this.logPerformance = false; this.logger = this.host; } LanguageServiceShimObject.prototype.forwardJSONCall = function (actionDescription, action) { - return forwardJSONCall(this.logger, actionDescription, action, false); + return forwardJSONCall(this.logger, actionDescription, action, this.logPerformance); }; /// DISPOSE /** @@ -42286,12 +44258,12 @@ var ts; function ClassifierShimObject(factory, logger) { _super.call(this, factory); this.logger = logger; + this.logPerformance = false; this.classifier = ts.createClassifier(); } ClassifierShimObject.prototype.getEncodedLexicalClassifications = function (text, lexState, syntacticClassifierAbsent) { var _this = this; - return forwardJSONCall(this.logger, "getEncodedLexicalClassifications", function () { return convertClassifications(_this.classifier.getEncodedLexicalClassifications(text, lexState, syntacticClassifierAbsent)); }, - /*noPerfLogging:*/ true); + return forwardJSONCall(this.logger, "getEncodedLexicalClassifications", function () { return convertClassifications(_this.classifier.getEncodedLexicalClassifications(text, lexState, syntacticClassifierAbsent)); }, this.logPerformance); }; /// COLORIZATION ClassifierShimObject.prototype.getClassificationsForLine = function (text, lexState, classifyKeywordsInGenerics) { @@ -42313,9 +44285,10 @@ var ts; _super.call(this, factory); this.logger = logger; this.host = host; + this.logPerformance = false; } CoreServicesShimObject.prototype.forwardJSONCall = function (actionDescription, action) { - return forwardJSONCall(this.logger, actionDescription, action, false); + return forwardJSONCall(this.logger, actionDescription, action, this.logPerformance); }; CoreServicesShimObject.prototype.getPreProcessedFileInfo = function (fileName, sourceTextSnapshot) { return this.forwardJSONCall("getPreProcessedFileInfo('" + fileName + "')", function () { @@ -42372,7 +44345,6 @@ var ts; var TypeScriptServicesFactory = (function () { function TypeScriptServicesFactory() { this._shims = []; - this.documentRegistry = ts.createDocumentRegistry(); } /* * Returns script API version. @@ -42382,6 +44354,9 @@ var ts; }; TypeScriptServicesFactory.prototype.createLanguageServiceShim = function (host) { try { + if (this.documentRegistry === undefined) { + this.documentRegistry = ts.createDocumentRegistry(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames()); + } var hostAdapter = new LanguageServiceShimHostAdapter(host); var languageService = ts.createLanguageService(hostAdapter, this.documentRegistry); return new LanguageServiceShimObject(this, host, languageService); @@ -42444,4 +44419,4 @@ var TypeScript; })(Services = TypeScript.Services || (TypeScript.Services = {})); })(TypeScript || (TypeScript = {})); /* @internal */ -var toolsVersion = "1.4"; +var toolsVersion = "1.5"; diff --git a/package.json b/package.json index ca137dcfb40..d6a8f538b78 100644 --- a/package.json +++ b/package.json @@ -2,7 +2,7 @@ "name": "typescript", "author": "Microsoft Corp.", "homepage": "http://typescriptlang.org/", - "version": "1.5.2", + "version": "1.5.3", "license": "Apache-2.0", "description": "TypeScript is a language for application scale JavaScript development", "keywords": [ diff --git a/scripts/processDiagnosticMessages.ts b/scripts/processDiagnosticMessages.ts index 9cfde5b2964..0a81b993616 100644 --- a/scripts/processDiagnosticMessages.ts +++ b/scripts/processDiagnosticMessages.ts @@ -55,7 +55,7 @@ function buildInfoFileOutput(messageTable: InputDiagnosticMessageTable, nameMap: '// \r\n' + '/// \r\n' + '/* @internal */\r\n' + - 'module ts {\r\n' + + 'namespace ts {\r\n' + ' export var Diagnostics = {\r\n'; var names = Utilities.getObjectKeys(messageTable); for (var i = 0; i < names.length; i++) { diff --git a/src/compiler/binder.ts b/src/compiler/binder.ts index b66497fc40d..eaad8593eee 100644 --- a/src/compiler/binder.ts +++ b/src/compiler/binder.ts @@ -1,7 +1,7 @@ /// /* @internal */ -module ts { +namespace ts { export let bindTime = 0; export const enum ModuleInstanceState { @@ -52,48 +52,86 @@ module ts { } } - export function bindSourceFile(file: SourceFile): void { + const enum ContainerFlags { + // The current node is not a container, and no container manipulation should happen before + // recursing into it. + None = 0, + + // 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... + IsContainer = 1 << 0, + + // 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... + IsBlockScopedContainer = 1 << 1, + + HasLocals = 1 << 2, + + // If the current node is a container that also container that also contains locals. Examples: + // + // Functions, Methods, Modules, Source-files. + IsContainerWithLocals = IsContainer | HasLocals + } + + export function bindSourceFile(file: SourceFile) { let start = new Date().getTime(); bindSourceFileWorker(file); bindTime += new Date().getTime() - start; } - function bindSourceFileWorker(file: SourceFile): void { + function bindSourceFileWorker(file: SourceFile) { let parent: Node; let container: Node; let blockScopeContainer: Node; let lastContainer: Node; + + // 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). + let inStrictMode = !!file.externalModuleIndicator; + let symbolCount = 0; let Symbol = objectAllocator.getSymbolConstructor(); + let classifiableNames: Map = {}; if (!file.locals) { - file.locals = {}; - container = file; - setBlockScopeContainer(file, /*cleanLocals*/ false); bind(file); file.symbolCount = symbolCount; + file.classifiableNames = classifiableNames; } + return; + function createSymbol(flags: SymbolFlags, name: string): Symbol { symbolCount++; return new Symbol(flags, name); } - function setBlockScopeContainer(node: Node, cleanLocals: boolean) { - blockScopeContainer = node; - if (cleanLocals) { - blockScopeContainer.locals = undefined; - } - } + function addDeclarationToSymbol(symbol: Symbol, node: Declaration, symbolFlags: SymbolFlags) { + symbol.flags |= symbolFlags; - function addDeclarationToSymbol(symbol: Symbol, node: Declaration, symbolKind: SymbolFlags) { - symbol.flags |= symbolKind; - if (!symbol.declarations) symbol.declarations = []; - symbol.declarations.push(node); - if (symbolKind & SymbolFlags.HasExports && !symbol.exports) symbol.exports = {}; - if (symbolKind & SymbolFlags.HasMembers && !symbol.members) symbol.members = {}; node.symbol = symbol; - if (symbolKind & SymbolFlags.Value && !symbol.valueDeclaration) symbol.valueDeclaration = node; + + if (!symbol.declarations) { + symbol.declarations = []; + } + symbol.declarations.push(node); + + if (symbolFlags & SymbolFlags.HasExports && !symbol.exports) { + symbol.exports = {}; + } + + if (symbolFlags & SymbolFlags.HasMembers && !symbol.members) { + symbol.members = {}; + } + + if (symbolFlags & SymbolFlags.Value && !symbol.valueDeclaration) { + symbol.valueDeclaration = node; + } } // Should not be called on a declaration with a computed property name, @@ -111,12 +149,12 @@ module ts { return (node.name).text; } switch (node.kind) { - case SyntaxKind.ConstructorType: case SyntaxKind.Constructor: return "__constructor"; case SyntaxKind.FunctionType: case SyntaxKind.CallSignature: return "__call"; + case SyntaxKind.ConstructorType: case SyntaxKind.ConstructSignature: return "__new"; case SyntaxKind.IndexSignature: @@ -135,7 +173,7 @@ module ts { return node.name ? declarationNameToString(node.name) : getDeclarationName(node); } - function declareSymbol(symbols: SymbolTable, parent: Symbol, node: Declaration, includes: SymbolFlags, excludes: SymbolFlags): Symbol { + function declareSymbol(symbolTable: SymbolTable, parent: Symbol, node: Declaration, includes: SymbolFlags, excludes: SymbolFlags): Symbol { Debug.assert(!hasDynamicName(node)); // The exported symbol for an export default function/class node is always named "default" @@ -143,7 +181,32 @@ module ts { let symbol: Symbol; if (name !== undefined) { - symbol = hasProperty(symbols, name) ? symbols[name] : (symbols[name] = createSymbol(0, name)); + // 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 + // witht he '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. + // + // 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 = hasProperty(symbolTable, name) + ? symbolTable[name] + : (symbolTable[name] = createSymbol(SymbolFlags.None, name)); + + if (name && (includes & SymbolFlags.Classifiable)) { + classifiableNames[name] = name; + } + if (symbol.flags & excludes) { if (node.name) { node.name.parent = node; @@ -152,51 +215,34 @@ module ts { // Report errors every position with duplicate declaration // Report errors on previous encountered declarations let message = symbol.flags & SymbolFlags.BlockScopedVariable - ? Diagnostics.Cannot_redeclare_block_scoped_variable_0 + ? Diagnostics.Cannot_redeclare_block_scoped_variable_0 : Diagnostics.Duplicate_identifier_0; - forEach(symbol.declarations, declaration => { file.bindDiagnostics.push(createDiagnosticForNode(declaration.name || declaration, message, getDisplayName(declaration))); }); file.bindDiagnostics.push(createDiagnosticForNode(node.name || node, message, getDisplayName(node))); - symbol = createSymbol(0, name); + symbol = createSymbol(SymbolFlags.None, name); } } else { - symbol = createSymbol(0, "__missing"); + symbol = createSymbol(SymbolFlags.None, "__missing"); } + addDeclarationToSymbol(symbol, node, includes); symbol.parent = parent; - if ((node.kind === SyntaxKind.ClassDeclaration || node.kind === SyntaxKind.ClassExpression) && symbol.exports) { - // 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'. - let prototypeSymbol = createSymbol(SymbolFlags.Property | SymbolFlags.Prototype, "prototype"); - if (hasProperty(symbol.exports, prototypeSymbol.name)) { - if (node.name) { - node.name.parent = node; - } - file.bindDiagnostics.push(createDiagnosticForNode(symbol.exports[prototypeSymbol.name].declarations[0], - Diagnostics.Duplicate_identifier_0, prototypeSymbol.name)); - } - symbol.exports[prototypeSymbol.name] = prototypeSymbol; - prototypeSymbol.parent = symbol; - } - return symbol; } - function declareModuleMember(node: Declaration, symbolKind: SymbolFlags, symbolExcludes: SymbolFlags) { + function declareModuleMember(node: Declaration, symbolFlags: SymbolFlags, symbolExcludes: SymbolFlags): Symbol { let hasExportModifier = getCombinedNodeFlags(node) & NodeFlags.Export; - if (symbolKind & SymbolFlags.Alias) { + if (symbolFlags & SymbolFlags.Alias) { if (node.kind === SyntaxKind.ExportSpecifier || (node.kind === SyntaxKind.ImportEqualsDeclaration && hasExportModifier)) { - declareSymbol(container.symbol.exports, container.symbol, node, symbolKind, symbolExcludes); + return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); } else { - declareSymbol(container.locals, undefined, node, symbolKind, symbolExcludes); + return declareSymbol(container.locals, undefined, node, symbolFlags, symbolExcludes); } } else { @@ -212,70 +258,174 @@ module ts { // 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. if (hasExportModifier || container.flags & NodeFlags.ExportContext) { - let exportKind = (symbolKind & SymbolFlags.Value ? SymbolFlags.ExportValue : 0) | - (symbolKind & SymbolFlags.Type ? SymbolFlags.ExportType : 0) | - (symbolKind & SymbolFlags.Namespace ? SymbolFlags.ExportNamespace : 0); + let exportKind = + (symbolFlags & SymbolFlags.Value ? SymbolFlags.ExportValue : 0) | + (symbolFlags & SymbolFlags.Type ? SymbolFlags.ExportType : 0) | + (symbolFlags & SymbolFlags.Namespace ? SymbolFlags.ExportNamespace : 0); let local = declareSymbol(container.locals, undefined, node, exportKind, symbolExcludes); - local.exportSymbol = declareSymbol(container.symbol.exports, container.symbol, node, symbolKind, symbolExcludes); + local.exportSymbol = declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); node.localSymbol = local; + return local; } else { - declareSymbol(container.locals, undefined, node, symbolKind, symbolExcludes); + return declareSymbol(container.locals, 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 bindChildren(node: Node, symbolKind: SymbolFlags, isBlockScopeContainer: boolean) { - if (symbolKind & SymbolFlags.HasLocals) { - node.locals = {}; - } - + // 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 bindChildren(node: Node) { + // Before we recurse into a node's chilren, we first save the existing parent, container + // and block-container. Then after we pop out of processing the children, we restore + // these saved values. let saveParent = parent; let saveContainer = container; let savedBlockScopeContainer = blockScopeContainer; + + // This node will now be set as the parent of all of its children as we recurse into them. parent = node; - if (symbolKind & SymbolFlags.IsContainer) { - container = node; + + // 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 accidently move any stale data forward from + // a previous compilation. + let containerFlags = getContainerFlags(node); + if (containerFlags & ContainerFlags.IsContainer) { + container = blockScopeContainer = node; + + if (containerFlags & ContainerFlags.HasLocals) { + container.locals = {}; + } addToContainerChain(container); } - - if (isBlockScopeContainer) { - // in incremental scenarios we might reuse nodes that already have locals being allocated - // during the bind step these locals should be dropped to prevent using stale data. - // locals should always be dropped unless they were previously initialized by the binder - // these cases are: - // - node has locals (symbolKind & HasLocals) !== 0 - // - node is a source file - setBlockScopeContainer(node, /*cleanLocals*/ (symbolKind & SymbolFlags.HasLocals) === 0 && node.kind !== SyntaxKind.SourceFile); + else if (containerFlags & ContainerFlags.IsBlockScopedContainer) { + blockScopeContainer = node; + blockScopeContainer.locals = undefined; } forEachChild(node, bind); + container = saveContainer; parent = saveParent; blockScopeContainer = savedBlockScopeContainer; } - function addToContainerChain(node: Node) { - if (lastContainer) { - lastContainer.nextContainer = node; + function getContainerFlags(node: Node): ContainerFlags { + switch (node.kind) { + case SyntaxKind.ClassExpression: + case SyntaxKind.ClassDeclaration: + case SyntaxKind.InterfaceDeclaration: + case SyntaxKind.EnumDeclaration: + case SyntaxKind.TypeLiteral: + case SyntaxKind.ObjectLiteralExpression: + return ContainerFlags.IsContainer; + + case SyntaxKind.CallSignature: + case SyntaxKind.ConstructSignature: + case SyntaxKind.IndexSignature: + case SyntaxKind.MethodDeclaration: + case SyntaxKind.MethodSignature: + case SyntaxKind.FunctionDeclaration: + case SyntaxKind.Constructor: + case SyntaxKind.GetAccessor: + case SyntaxKind.SetAccessor: + case SyntaxKind.FunctionType: + case SyntaxKind.ConstructorType: + case SyntaxKind.FunctionExpression: + case SyntaxKind.ArrowFunction: + case SyntaxKind.ModuleDeclaration: + case SyntaxKind.SourceFile: + case SyntaxKind.TypeAliasDeclaration: + return ContainerFlags.IsContainerWithLocals; + + case SyntaxKind.CatchClause: + case SyntaxKind.ForStatement: + case SyntaxKind.ForInStatement: + case SyntaxKind.ForOfStatement: + case SyntaxKind.CaseBlock: + return ContainerFlags.IsBlockScopedContainer; + + case SyntaxKind.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. Othewise '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 isFunctionLike(node.parent) ? ContainerFlags.None : ContainerFlags.IsBlockScopedContainer; } - lastContainer = node; + return ContainerFlags.None; } - function bindDeclaration(node: Declaration, symbolKind: SymbolFlags, symbolExcludes: SymbolFlags, isBlockScopeContainer: boolean) { + function addToContainerChain(next: Node) { + if (lastContainer) { + lastContainer.nextContainer = next; + } + + lastContainer = next; + } + + function declareSymbolAndAddToSymbolTable(node: Declaration, symbolFlags: SymbolFlags, symbolExcludes: SymbolFlags): void { + // Just call this directly so that the return type of this function stays "void". + declareSymbolAndAddToSymbolTableWorker(node, symbolFlags, symbolExcludes); + } + + function declareSymbolAndAddToSymbolTableWorker(node: Declaration, symbolFlags: SymbolFlags, symbolExcludes: SymbolFlags): Symbol { 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 SyntaxKind.ModuleDeclaration: - declareModuleMember(node, symbolKind, symbolExcludes); - break; + return declareModuleMember(node, symbolFlags, symbolExcludes); + case SyntaxKind.SourceFile: - if (isExternalModule(container)) { - declareModuleMember(node, symbolKind, symbolExcludes); - break; - } + return declareSourceFileMember(node, symbolFlags, symbolExcludes); + + case SyntaxKind.ClassExpression: + case SyntaxKind.ClassDeclaration: + return declareClassMember(node, symbolFlags, symbolExcludes); + + case SyntaxKind.EnumDeclaration: + return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); + + case SyntaxKind.TypeLiteral: + case SyntaxKind.ObjectLiteralExpression: + case SyntaxKind.InterfaceDeclaration: + // 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 SyntaxKind.FunctionType: case SyntaxKind.ConstructorType: case SyntaxKind.CallSignature: @@ -289,29 +439,35 @@ module ts { case SyntaxKind.FunctionDeclaration: case SyntaxKind.FunctionExpression: case SyntaxKind.ArrowFunction: - declareSymbol(container.locals, undefined, node, symbolKind, symbolExcludes); - break; - case SyntaxKind.ClassExpression: - case SyntaxKind.ClassDeclaration: - if (node.flags & NodeFlags.Static) { - declareSymbol(container.symbol.exports, container.symbol, node, symbolKind, symbolExcludes); - break; - } - case SyntaxKind.TypeLiteral: - case SyntaxKind.ObjectLiteralExpression: - case SyntaxKind.InterfaceDeclaration: - declareSymbol(container.symbol.members, container.symbol, node, symbolKind, symbolExcludes); - break; - case SyntaxKind.EnumDeclaration: - declareSymbol(container.symbol.exports, container.symbol, node, symbolKind, symbolExcludes); - break; + case SyntaxKind.TypeAliasDeclaration: + // 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, undefined, node, symbolFlags, symbolExcludes); } - bindChildren(node, symbolKind, isBlockScopeContainer); + } + + function declareClassMember(node: Declaration, symbolFlags: SymbolFlags, symbolExcludes: SymbolFlags) { + return node.flags & NodeFlags.Static + ? declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes) + : declareSymbol(container.symbol.members, container.symbol, node, symbolFlags, symbolExcludes); + } + + function declareSourceFileMember(node: Declaration, symbolFlags: SymbolFlags, symbolExcludes: SymbolFlags) { + return isExternalModule(file) + ? declareModuleMember(node, symbolFlags, symbolExcludes) + : declareSymbol(file.locals, undefined, node, symbolFlags, symbolExcludes); } function isAmbientContext(node: Node): boolean { while (node) { - if (node.flags & NodeFlags.Ambient) return true; + if (node.flags & NodeFlags.Ambient) { + return true; + } + node = node.parent; } return false; @@ -343,15 +499,16 @@ module ts { function bindModuleDeclaration(node: ModuleDeclaration) { setExportContextFlag(node); if (node.name.kind === SyntaxKind.StringLiteral) { - bindDeclaration(node, SymbolFlags.ValueModule, SymbolFlags.ValueModuleExcludes, /*isBlockScopeContainer*/ true); + declareSymbolAndAddToSymbolTable(node, SymbolFlags.ValueModule, SymbolFlags.ValueModuleExcludes); } else { let state = getModuleInstanceState(node); if (state === ModuleInstanceState.NonInstantiated) { - bindDeclaration(node, SymbolFlags.NamespaceModule, SymbolFlags.NamespaceModuleExcludes, /*isBlockScopeContainer*/ true); + declareSymbolAndAddToSymbolTable(node, SymbolFlags.NamespaceModule, SymbolFlags.NamespaceModuleExcludes); } else { - bindDeclaration(node, SymbolFlags.ValueModule, SymbolFlags.ValueModuleExcludes, /*isBlockScopeContainer*/ true); + declareSymbolAndAddToSymbolTable(node, SymbolFlags.ValueModule, SymbolFlags.ValueModuleExcludes); + let currentModuleIsConstEnumOnly = state === ModuleInstanceState.ConstEnumOnly; if (node.symbol.constEnumOnlyModule === undefined) { // non-merged case - use the current state @@ -372,35 +529,72 @@ module ts { // 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. - let symbol = createSymbol(SymbolFlags.Signature, getDeclarationName(node)); addDeclarationToSymbol(symbol, node, SymbolFlags.Signature); - bindChildren(node, SymbolFlags.Signature, /*isBlockScopeContainer:*/ false); let typeLiteralSymbol = createSymbol(SymbolFlags.TypeLiteral, "__type"); addDeclarationToSymbol(typeLiteralSymbol, node, SymbolFlags.TypeLiteral); - typeLiteralSymbol.members = {}; - typeLiteralSymbol.members[node.kind === SyntaxKind.FunctionType ? "__call" : "__new"] = symbol + typeLiteralSymbol.members = { [symbol.name]: symbol }; } - function bindAnonymousDeclaration(node: Declaration, symbolKind: SymbolFlags, name: string, isBlockScopeContainer: boolean) { - let symbol = createSymbol(symbolKind, name); - addDeclarationToSymbol(symbol, node, symbolKind); - bindChildren(node, symbolKind, isBlockScopeContainer); + function bindObjectLiteralExpression(node: ObjectLiteralExpression) { + const enum ElementKind { + Property = 1, + Accessor = 2 + } + + if (inStrictMode) { + let seen: Map = {}; + + for (let prop of node.properties) { + if (prop.name.kind !== SyntaxKind.Identifier) { + continue; + } + + let identifier = prop.name; + + // ECMA-262 11.1.5 Object Initialiser + // 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 + let currentKind = prop.kind === SyntaxKind.PropertyAssignment || prop.kind === SyntaxKind.ShorthandPropertyAssignment || prop.kind === SyntaxKind.MethodDeclaration + ? ElementKind.Property + : ElementKind.Accessor; + + let existingKind = seen[identifier.text]; + if (!existingKind) { + seen[identifier.text] = currentKind; + continue; + } + + if (currentKind === ElementKind.Property && existingKind === ElementKind.Property) { + let span = getErrorSpanForNode(file, identifier); + file.bindDiagnostics.push(createFileDiagnostic(file, span.start, span.length, + Diagnostics.An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode)); + } + } + } + + return bindAnonymousDeclaration(node, SymbolFlags.ObjectLiteral, "__object"); } - function bindCatchVariableDeclaration(node: CatchClause) { - bindChildren(node, /*symbolKind:*/ 0, /*isBlockScopeContainer:*/ true); + function bindAnonymousDeclaration(node: Declaration, symbolFlags: SymbolFlags, name: string) { + let symbol = createSymbol(symbolFlags, name); + addDeclarationToSymbol(symbol, node, symbolFlags); } - function bindBlockScopedDeclaration(node: Declaration, symbolKind: SymbolFlags, symbolExcludes: SymbolFlags) { + function bindBlockScopedDeclaration(node: Declaration, symbolFlags: SymbolFlags, symbolExcludes: SymbolFlags) { switch (blockScopeContainer.kind) { case SyntaxKind.ModuleDeclaration: - declareModuleMember(node, symbolKind, symbolExcludes); + declareModuleMember(node, symbolFlags, symbolExcludes); break; case SyntaxKind.SourceFile: if (isExternalModule(container)) { - declareModuleMember(node, symbolKind, symbolExcludes); + declareModuleMember(node, symbolFlags, symbolExcludes); break; } // fall through. @@ -409,202 +603,428 @@ module ts { blockScopeContainer.locals = {}; addToContainerChain(blockScopeContainer); } - declareSymbol(blockScopeContainer.locals, undefined, node, symbolKind, symbolExcludes); + declareSymbol(blockScopeContainer.locals, undefined, node, symbolFlags, symbolExcludes); } - bindChildren(node, symbolKind, /*isBlockScopeContainer*/ false); } function bindBlockScopedVariableDeclaration(node: Declaration) { bindBlockScopedDeclaration(node, SymbolFlags.BlockScopedVariable, SymbolFlags.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: Identifier) { + if (inStrictMode && + node.originalKeywordKind >= SyntaxKind.FirstFutureReservedWord && + node.originalKeywordKind <= SyntaxKind.LastFutureReservedWord && + !isIdentifierName(node)) { + + // Report error only if there are no parse errors in file + if (!file.parseDiagnostics.length) { + file.bindDiagnostics.push(createDiagnosticForNode(node, + getStrictModeIdentifierMessage(node), declarationNameToString(node))); + } + } + } + + function getStrictModeIdentifierMessage(node: Node) { + // Provide specialized messages to help the user understand why we think they're in + // strict mode. + if (getAncestor(node, SyntaxKind.ClassDeclaration) || getAncestor(node, SyntaxKind.ClassExpression)) { + return Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_strict_mode; + } + + if (file.externalModuleIndicator) { + return Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode; + } + + return Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode; + } + + function checkStrictModeBinaryExpression(node: BinaryExpression) { + if (inStrictMode && isLeftHandSideExpression(node.left) && 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: CatchClause) { + // 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: DeleteExpression) { + // Grammar checking + if (inStrictMode && node.expression.kind === SyntaxKind.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 + let span = getErrorSpanForNode(file, node.expression); + file.bindDiagnostics.push(createFileDiagnostic(file, span.start, span.length, Diagnostics.delete_cannot_be_called_on_an_identifier_in_strict_mode)); + } + } + + function isEvalOrArgumentsIdentifier(node: Node): boolean { + return node.kind === SyntaxKind.Identifier && + ((node).text === "eval" || (node).text === "arguments"); + } + + function checkStrictModeEvalOrArguments(contextNode: Node, name: Node) { + if (name && name.kind === SyntaxKind.Identifier) { + let 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. + let span = getErrorSpanForNode(file, name); + file.bindDiagnostics.push(createFileDiagnostic(file, span.start, span.length, + getStrictModeEvalOrArgumentsMessage(contextNode), identifier.text)); + } + } + } + + function getStrictModeEvalOrArgumentsMessage(node: Node) { + // Provide specialized messages to help the user understand why we think they're in + // strict mode. + if (getAncestor(node, SyntaxKind.ClassDeclaration) || getAncestor(node, SyntaxKind.ClassExpression)) { + return Diagnostics.Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode; + } + + if (file.externalModuleIndicator) { + return Diagnostics.Invalid_use_of_0_Modules_are_automatically_in_strict_mode; + } + + return Diagnostics.Invalid_use_of_0_in_strict_mode; + } + + function checkStrictModeFunctionName(node: FunctionLikeDeclaration) { + 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 checkStrictModeNumericLiteral(node: LiteralExpression) { + if (inStrictMode && node.flags & NodeFlags.OctalLiteral) { + file.bindDiagnostics.push(createDiagnosticForNode(node, Diagnostics.Octal_literals_are_not_allowed_in_strict_mode)); + } + } + + function checkStrictModePostfixUnaryExpression(node: PostfixUnaryExpression) { + // 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: PrefixUnaryExpression) { + // Grammar checking + if (inStrictMode) { + if (node.operator === SyntaxKind.PlusPlusToken || node.operator === SyntaxKind.MinusMinusToken) { + checkStrictModeEvalOrArguments(node, node.operand); + } + } + } + + function checkStrictModeWithStatement(node: WithStatement) { + // Grammar checking for withStatement + if (inStrictMode) { + grammarErrorOnFirstToken(node, Diagnostics.with_statements_are_not_allowed_in_strict_mode); + } + } + + function grammarErrorOnFirstToken(node: Node, message: DiagnosticMessage, arg0?: any, arg1?: any, arg2?: any) { + let span = getSpanOfTokenAtPosition(file, node.pos); + file.bindDiagnostics.push(createFileDiagnostic(file, span.start, span.length, message, arg0, arg1, arg2)); + } + function getDestructuringParameterName(node: Declaration) { return "__" + indexOf((node.parent).parameters, node); } function bind(node: Node) { node.parent = parent; - + + var savedInStrictMode = inStrictMode; + if (!savedInStrictMode) { + updateStrictMode(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. + bindChildren(node); + + inStrictMode = savedInStrictMode; + } + + function updateStrictMode(node: Node) { switch (node.kind) { + case SyntaxKind.SourceFile: + case SyntaxKind.ModuleBlock: + updateStrictModeStatementList((node).statements); + return; + case SyntaxKind.Block: + if (isFunctionLike(node.parent)) { + updateStrictModeStatementList((node).statements); + } + return; + case SyntaxKind.ClassDeclaration: + case SyntaxKind.ClassExpression: + // All classes are automatically in strict mode in ES6. + inStrictMode = true; + return; + } + } + + function updateStrictModeStatementList(statements: NodeArray) { + for (let statement of statements) { + if (!isPrologueDirective(statement)) { + return; + } + + if (isUseStrictPrologueDirective(statement)) { + inStrictMode = true; + return; + } + } + } + + /// Should be called only on prologue directives (isPrologueDirective(node) should be true) + function isUseStrictPrologueDirective(node: ExpressionStatement): boolean { + let nodeText = 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: Node) { + switch (node.kind) { + case SyntaxKind.Identifier: + return checkStrictModeIdentifier(node); + case SyntaxKind.BinaryExpression: + return checkStrictModeBinaryExpression(node); + case SyntaxKind.CatchClause: + return checkStrictModeCatchClause(node); + case SyntaxKind.DeleteExpression: + return checkStrictModeDeleteExpression(node); + case SyntaxKind.NumericLiteral: + return checkStrictModeNumericLiteral(node); + case SyntaxKind.PostfixUnaryExpression: + return checkStrictModePostfixUnaryExpression(node); + case SyntaxKind.PrefixUnaryExpression: + return checkStrictModePrefixUnaryExpression(node); + case SyntaxKind.WithStatement: + return checkStrictModeWithStatement(node); + case SyntaxKind.TypeParameter: - bindDeclaration(node, SymbolFlags.TypeParameter, SymbolFlags.TypeParameterExcludes, /*isBlockScopeContainer*/ false); - break; + return declareSymbolAndAddToSymbolTable(node, SymbolFlags.TypeParameter, SymbolFlags.TypeParameterExcludes); case SyntaxKind.Parameter: - bindParameter(node); - break; + return bindParameter(node); case SyntaxKind.VariableDeclaration: case SyntaxKind.BindingElement: - if (isBindingPattern((node).name)) { - bindChildren(node, 0, /*isBlockScopeContainer*/ false); - } - else if (isBlockOrCatchScoped(node)) { - bindBlockScopedVariableDeclaration(node); - } - else if (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 - bindDeclaration(node, SymbolFlags.FunctionScopedVariable, SymbolFlags.ParameterExcludes, /*isBlockScopeContainer*/ false); - } - else { - bindDeclaration(node, SymbolFlags.FunctionScopedVariable, SymbolFlags.FunctionScopedVariableExcludes, /*isBlockScopeContainer*/ false); - } - break; + return bindVariableDeclarationOrBindingElement(node); case SyntaxKind.PropertyDeclaration: case SyntaxKind.PropertySignature: - bindPropertyOrMethodOrAccessor(node, SymbolFlags.Property | ((node).questionToken ? SymbolFlags.Optional : 0), SymbolFlags.PropertyExcludes, /*isBlockScopeContainer*/ false); - break; + return bindPropertyOrMethodOrAccessor(node, SymbolFlags.Property | ((node).questionToken ? SymbolFlags.Optional : SymbolFlags.None), SymbolFlags.PropertyExcludes); case SyntaxKind.PropertyAssignment: case SyntaxKind.ShorthandPropertyAssignment: - bindPropertyOrMethodOrAccessor(node, SymbolFlags.Property, SymbolFlags.PropertyExcludes, /*isBlockScopeContainer*/ false); - break; + return bindPropertyOrMethodOrAccessor(node, SymbolFlags.Property, SymbolFlags.PropertyExcludes); case SyntaxKind.EnumMember: - bindPropertyOrMethodOrAccessor(node, SymbolFlags.EnumMember, SymbolFlags.EnumMemberExcludes, /*isBlockScopeContainer*/ false); - break; + return bindPropertyOrMethodOrAccessor(node, SymbolFlags.EnumMember, SymbolFlags.EnumMemberExcludes); case SyntaxKind.CallSignature: case SyntaxKind.ConstructSignature: case SyntaxKind.IndexSignature: - bindDeclaration(node, SymbolFlags.Signature, 0, /*isBlockScopeContainer*/ false); - break; + return declareSymbolAndAddToSymbolTable(node, SymbolFlags.Signature, SymbolFlags.None); case SyntaxKind.MethodDeclaration: case SyntaxKind.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. - bindPropertyOrMethodOrAccessor(node, SymbolFlags.Method | ((node).questionToken ? SymbolFlags.Optional : 0), - isObjectLiteralMethod(node) ? SymbolFlags.PropertyExcludes : SymbolFlags.MethodExcludes, /*isBlockScopeContainer*/ true); - break; + return bindPropertyOrMethodOrAccessor(node, SymbolFlags.Method | ((node).questionToken ? SymbolFlags.Optional : SymbolFlags.None), + isObjectLiteralMethod(node) ? SymbolFlags.PropertyExcludes : SymbolFlags.MethodExcludes); case SyntaxKind.FunctionDeclaration: - bindDeclaration(node, SymbolFlags.Function, SymbolFlags.FunctionExcludes, /*isBlockScopeContainer*/ true); - break; + checkStrictModeFunctionName(node); + return declareSymbolAndAddToSymbolTable(node, SymbolFlags.Function, SymbolFlags.FunctionExcludes); case SyntaxKind.Constructor: - bindDeclaration(node, SymbolFlags.Constructor, /*symbolExcludes:*/ 0, /*isBlockScopeContainer:*/ true); - break; + return declareSymbolAndAddToSymbolTable(node, SymbolFlags.Constructor, /*symbolExcludes:*/ SymbolFlags.None); case SyntaxKind.GetAccessor: - bindPropertyOrMethodOrAccessor(node, SymbolFlags.GetAccessor, SymbolFlags.GetAccessorExcludes, /*isBlockScopeContainer*/ true); - break; + return bindPropertyOrMethodOrAccessor(node, SymbolFlags.GetAccessor, SymbolFlags.GetAccessorExcludes); case SyntaxKind.SetAccessor: - bindPropertyOrMethodOrAccessor(node, SymbolFlags.SetAccessor, SymbolFlags.SetAccessorExcludes, /*isBlockScopeContainer*/ true); - break; - + return bindPropertyOrMethodOrAccessor(node, SymbolFlags.SetAccessor, SymbolFlags.SetAccessorExcludes); case SyntaxKind.FunctionType: case SyntaxKind.ConstructorType: - bindFunctionOrConstructorType(node); - break; - + return bindFunctionOrConstructorType(node); case SyntaxKind.TypeLiteral: - bindAnonymousDeclaration(node, SymbolFlags.TypeLiteral, "__type", /*isBlockScopeContainer*/ false); - break; + return bindAnonymousDeclaration(node, SymbolFlags.TypeLiteral, "__type"); case SyntaxKind.ObjectLiteralExpression: - bindAnonymousDeclaration(node, SymbolFlags.ObjectLiteral, "__object", /*isBlockScopeContainer*/ false); - break; + return bindObjectLiteralExpression(node); case SyntaxKind.FunctionExpression: case SyntaxKind.ArrowFunction: - bindAnonymousDeclaration(node, SymbolFlags.Function, "__function", /*isBlockScopeContainer*/ true); - break; + checkStrictModeFunctionName(node); + return bindAnonymousDeclaration(node, SymbolFlags.Function, "__function"); case SyntaxKind.ClassExpression: - bindAnonymousDeclaration(node, SymbolFlags.Class, "__class", /*isBlockScopeContainer*/ false); - break; - case SyntaxKind.CatchClause: - bindCatchVariableDeclaration(node); - break; case SyntaxKind.ClassDeclaration: - bindBlockScopedDeclaration(node, SymbolFlags.Class, SymbolFlags.ClassExcludes); - break; + return bindClassLikeDeclaration(node); case SyntaxKind.InterfaceDeclaration: - bindDeclaration(node, SymbolFlags.Interface, SymbolFlags.InterfaceExcludes, /*isBlockScopeContainer*/ false); - break; + return bindBlockScopedDeclaration(node, SymbolFlags.Interface, SymbolFlags.InterfaceExcludes); case SyntaxKind.TypeAliasDeclaration: - bindDeclaration(node, SymbolFlags.TypeAlias, SymbolFlags.TypeAliasExcludes, /*isBlockScopeContainer*/ false); - break; + return bindBlockScopedDeclaration(node, SymbolFlags.TypeAlias, SymbolFlags.TypeAliasExcludes); case SyntaxKind.EnumDeclaration: - if (isConst(node)) { - bindDeclaration(node, SymbolFlags.ConstEnum, SymbolFlags.ConstEnumExcludes, /*isBlockScopeContainer*/ false); - } - else { - bindDeclaration(node, SymbolFlags.RegularEnum, SymbolFlags.RegularEnumExcludes, /*isBlockScopeContainer*/ false); - } - break; + return bindEnumDeclaration(node); case SyntaxKind.ModuleDeclaration: - bindModuleDeclaration(node); - break; + return bindModuleDeclaration(node); case SyntaxKind.ImportEqualsDeclaration: case SyntaxKind.NamespaceImport: case SyntaxKind.ImportSpecifier: case SyntaxKind.ExportSpecifier: - bindDeclaration(node, SymbolFlags.Alias, SymbolFlags.AliasExcludes, /*isBlockScopeContainer*/ false); - break; + return declareSymbolAndAddToSymbolTable(node, SymbolFlags.Alias, SymbolFlags.AliasExcludes); case SyntaxKind.ImportClause: - if ((node).name) { - bindDeclaration(node, SymbolFlags.Alias, SymbolFlags.AliasExcludes, /*isBlockScopeContainer*/ false); - } - else { - bindChildren(node, 0, /*isBlockScopeContainer*/ false); - } - break; + return bindImportClause(node); case SyntaxKind.ExportDeclaration: - if (!(node).exportClause) { - // All export * declarations are collected in an __export symbol - declareSymbol(container.symbol.exports, container.symbol, node, SymbolFlags.ExportStar, 0); - } - bindChildren(node, 0, /*isBlockScopeContainer*/ false); - break; + return bindExportDeclaration(node); case SyntaxKind.ExportAssignment: - if ((node).expression.kind === SyntaxKind.Identifier) { - // An export default clause with an identifier exports all meanings of that identifier - declareSymbol(container.symbol.exports, container.symbol, node, SymbolFlags.Alias, SymbolFlags.PropertyExcludes | SymbolFlags.AliasExcludes); - } - else { - // An export default clause with an expression exports a value - declareSymbol(container.symbol.exports, container.symbol, node, SymbolFlags.Property, SymbolFlags.PropertyExcludes | SymbolFlags.AliasExcludes); - } - bindChildren(node, 0, /*isBlockScopeContainer*/ false); - break; + return bindExportAssignment(node); case SyntaxKind.SourceFile: - setExportContextFlag(node); - if (isExternalModule(node)) { - bindAnonymousDeclaration(node, SymbolFlags.ValueModule, '"' + removeFileExtension((node).fileName) + '"', /*isBlockScopeContainer*/ true); - break; - } - case SyntaxKind.Block: - // do not treat function block a block-scope container - // all block-scope locals that reside in this block should go to the function locals. - // Otherwise this won't be considered as redeclaration of a block scoped local: - // function foo() { - // let x; - // let x; - // } - // 'let x' will be placed into the function locals and 'let x' - into the locals of the block - bindChildren(node, 0, /*isBlockScopeContainer*/ !isFunctionLike(node.parent)); - break; - case SyntaxKind.CatchClause: - case SyntaxKind.ForStatement: - case SyntaxKind.ForInStatement: - case SyntaxKind.ForOfStatement: - case SyntaxKind.CaseBlock: - bindChildren(node, 0, /*isBlockScopeContainer*/ true); - break; - default: - let saveParent = parent; - parent = node; - forEachChild(node, bind); - parent = saveParent; + return bindSourceFileIfExternalModule(); + } + } + + function bindSourceFileIfExternalModule() { + setExportContextFlag(file); + if (isExternalModule(file)) { + bindAnonymousDeclaration(file, SymbolFlags.ValueModule, '"' + removeFileExtension(file.fileName) + '"'); + } + } + + function bindExportAssignment(node: ExportAssignment) { + if (!container.symbol || !container.symbol.exports) { + // Export assignment in some sort of block construct + bindAnonymousDeclaration(node, SymbolFlags.Alias, getDeclarationName(node)); + } + else if (node.expression.kind === SyntaxKind.Identifier) { + // An export default clause with an identifier exports all meanings of that identifier + declareSymbol(container.symbol.exports, container.symbol, node, SymbolFlags.Alias, SymbolFlags.PropertyExcludes | SymbolFlags.AliasExcludes); + } + else { + // An export default clause with an expression exports a value + declareSymbol(container.symbol.exports, container.symbol, node, SymbolFlags.Property, SymbolFlags.PropertyExcludes | SymbolFlags.AliasExcludes); + } + } + + function bindExportDeclaration(node: ExportDeclaration) { + if (!container.symbol || !container.symbol.exports) { + // Export * in some sort of block construct + bindAnonymousDeclaration(node, SymbolFlags.ExportStar, getDeclarationName(node)); + } + else if (!node.exportClause) { + // All export * declarations are collected in an __export symbol + declareSymbol(container.symbol.exports, container.symbol, node, SymbolFlags.ExportStar, SymbolFlags.None); + } + } + + function bindImportClause(node: ImportClause) { + if (node.name) { + declareSymbolAndAddToSymbolTable(node, SymbolFlags.Alias, SymbolFlags.AliasExcludes); + } + } + + function bindClassLikeDeclaration(node: ClassLikeDeclaration) { + if (node.kind === SyntaxKind.ClassDeclaration) { + bindBlockScopedDeclaration(node, SymbolFlags.Class, SymbolFlags.ClassExcludes); + } + else { + bindAnonymousDeclaration(node, SymbolFlags.Class, "__class"); + } + + let 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. + let prototypeSymbol = createSymbol(SymbolFlags.Property | SymbolFlags.Prototype, "prototype"); + if (hasProperty(symbol.exports, prototypeSymbol.name)) { + if (node.name) { + node.name.parent = node; + } + file.bindDiagnostics.push(createDiagnosticForNode(symbol.exports[prototypeSymbol.name].declarations[0], + Diagnostics.Duplicate_identifier_0, prototypeSymbol.name)); + } + symbol.exports[prototypeSymbol.name] = prototypeSymbol; + prototypeSymbol.parent = symbol; + } + + function bindEnumDeclaration(node: EnumDeclaration) { + return isConst(node) + ? bindBlockScopedDeclaration(node, SymbolFlags.ConstEnum, SymbolFlags.ConstEnumExcludes) + : bindBlockScopedDeclaration(node, SymbolFlags.RegularEnum, SymbolFlags.RegularEnumExcludes); + } + + function bindVariableDeclarationOrBindingElement(node: VariableDeclaration | BindingElement) { + if (inStrictMode) { + checkStrictModeEvalOrArguments(node, node.name) + } + + if (!isBindingPattern(node.name)) { + if (isBlockOrCatchScoped(node)) { + bindBlockScopedVariableDeclaration(node); + } + else if (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, SymbolFlags.FunctionScopedVariable, SymbolFlags.ParameterExcludes); + } + else { + declareSymbolAndAddToSymbolTable(node, SymbolFlags.FunctionScopedVariable, SymbolFlags.FunctionScopedVariableExcludes); + } } } function bindParameter(node: ParameterDeclaration) { + if (inStrictMode) { + // 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 (isBindingPattern(node.name)) { - bindAnonymousDeclaration(node, SymbolFlags.FunctionScopedVariable, getDestructuringParameterName(node), /*isBlockScopeContainer*/ false); + bindAnonymousDeclaration(node, SymbolFlags.FunctionScopedVariable, getDestructuringParameterName(node)); } else { - bindDeclaration(node, SymbolFlags.FunctionScopedVariable, SymbolFlags.ParameterExcludes, /*isBlockScopeContainer*/ false); + declareSymbolAndAddToSymbolTable(node, SymbolFlags.FunctionScopedVariable, SymbolFlags.ParameterExcludes); } // If this is a property-parameter, then also declare the property symbol into the @@ -618,13 +1038,10 @@ module ts { } } - function bindPropertyOrMethodOrAccessor(node: Declaration, symbolKind: SymbolFlags, symbolExcludes: SymbolFlags, isBlockScopeContainer: boolean) { - if (hasDynamicName(node)) { - bindAnonymousDeclaration(node, symbolKind, "__computed", isBlockScopeContainer); - } - else { - bindDeclaration(node, symbolKind, symbolExcludes, isBlockScopeContainer); - } + function bindPropertyOrMethodOrAccessor(node: Declaration, symbolFlags: SymbolFlags, symbolExcludes: SymbolFlags) { + return hasDynamicName(node) + ? bindAnonymousDeclaration(node, symbolFlags, "__computed") + : declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes); } } } diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 3db99a12686..edae2ad7ed7 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -1,7 +1,7 @@ /// /* @internal */ -module ts { +namespace ts { let nextSymbolId = 1; let nextNodeId = 1; let nextMergeId = 1; @@ -91,27 +91,31 @@ module ts { let circularType = createIntrinsicType(TypeFlags.Any, "__circular__"); let emptyObjectType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); + let emptyGenericType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); + emptyGenericType.instantiations = {}; + let anyFunctionType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); let noConstraintType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); - let anySignature = createSignature(undefined, undefined, emptyArray, anyType, 0, false, false); - let unknownSignature = createSignature(undefined, undefined, emptyArray, unknownType, 0, false, false); + let anySignature = createSignature(undefined, undefined, emptyArray, anyType, undefined, 0, false, false); + let unknownSignature = createSignature(undefined, undefined, emptyArray, unknownType, undefined, 0, false, false); let globals: SymbolTable = {}; - let globalArraySymbol: Symbol; let globalESSymbolConstructorSymbol: Symbol; let globalObjectType: ObjectType; let globalFunctionType: ObjectType; - let globalArrayType: ObjectType; + let globalArrayType: GenericType; let globalStringType: ObjectType; let globalNumberType: ObjectType; let globalBooleanType: ObjectType; let globalRegExpType: ObjectType; let globalTemplateStringsArrayType: ObjectType; let globalESSymbolType: ObjectType; - let globalIterableType: ObjectType; + let globalIterableType: GenericType; + let globalIteratorType: GenericType; + let globalIterableIteratorType: GenericType; let anyArrayType: Type; let getGlobalTypedPropertyDescriptorType: () => ObjectType; @@ -152,6 +156,14 @@ module ts { } }; + let subtypeRelation: Map = {}; + let assignableRelation: Map = {}; + let identityRelation: Map = {}; + + initializeTypeChecker(); + + return checker; + function getEmitResolver(sourceFile?: SourceFile) { // 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. @@ -335,28 +347,53 @@ module ts { // Locals of a source file are not in scope (because they get merged into the global symbol table) if (location.locals && !isGlobalSourceFile(location)) { if (result = getSymbol(location.locals, name, meaning)) { - break loop; + // 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. + if (!(meaning & SymbolFlags.Type) || + !(result.flags & (SymbolFlags.Type & ~SymbolFlags.TypeParameter)) || + !isFunctionLike(location) || + lastLocation === (location).body) { + break loop; + } + result = undefined; } } switch (location.kind) { case SyntaxKind.SourceFile: if (!isExternalModule(location)) break; case SyntaxKind.ModuleDeclaration: - if (result = getSymbol(getSymbolOfNode(location).exports, name, meaning & SymbolFlags.ModuleMember)) { - if (result.flags & meaning || !(result.flags & SymbolFlags.Alias && getDeclarationOfAliasSymbol(result).kind === SyntaxKind.ExportSpecifier)) { - break loop; - } - result = undefined; - } - else if (location.kind === SyntaxKind.SourceFile || + let moduleExports = getSymbolOfNode(location).exports; + if (location.kind === SyntaxKind.SourceFile || (location.kind === SyntaxKind.ModuleDeclaration && (location).name.kind === SyntaxKind.StringLiteral)) { - result = getSymbolOfNode(location).exports["default"]; + + // It's an external module. 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. + if (hasProperty(moduleExports, name) && + moduleExports[name].flags === SymbolFlags.Alias && + getDeclarationOfKind(moduleExports[name], SyntaxKind.ExportSpecifier)) { + break; + } + + result = moduleExports["default"]; let localSymbol = getLocalSymbolForExportDefault(result); if (result && localSymbol && (result.flags & meaning) && localSymbol.name === name) { break loop; } result = undefined; } + + if (result = getSymbol(moduleExports, name, meaning & SymbolFlags.ModuleMember)) { + break loop; + } break; case SyntaxKind.EnumDeclaration: if (result = getSymbol(getSymbolOfNode(location).exports, name, meaning & SymbolFlags.EnumMember)) { @@ -420,27 +457,32 @@ module ts { case SyntaxKind.SetAccessor: case SyntaxKind.FunctionDeclaration: case SyntaxKind.ArrowFunction: - if (name === "arguments") { + if (meaning & SymbolFlags.Variable && name === "arguments") { result = argumentsSymbol; break loop; } break; case SyntaxKind.FunctionExpression: - if (name === "arguments") { + if (meaning & SymbolFlags.Variable && name === "arguments") { result = argumentsSymbol; break loop; } - let functionName = (location).name; - if (functionName && name === functionName.text) { - result = location.symbol; - break loop; + + if (meaning & SymbolFlags.Function) { + let functionName = (location).name; + if (functionName && name === functionName.text) { + result = location.symbol; + break loop; + } } break; case SyntaxKind.ClassExpression: - let className = (location).name; - if (className && name === className.text) { - result = location.symbol; - break loop; + if (meaning & SymbolFlags.Class) { + let className = (location).name; + if (className && name === className.text) { + result = location.symbol; + break loop; + } } break; case SyntaxKind.Decorator: @@ -730,7 +772,7 @@ module ts { let target = resolveAlias(symbol); if (target) { let markAlias = - (target === unknownSymbol && compilerOptions.separateCompilation) || + (target === unknownSymbol && compilerOptions.isolatedModules) || (target !== unknownSymbol && (target.flags & SymbolFlags.Value) && !isConstEnumOrConstEnumOnlyModule(target)); if (markAlias) { @@ -1332,7 +1374,15 @@ module ts { function symbolToString(symbol: Symbol, enclosingDeclaration?: Node, meaning?: SymbolFlags): string { let writer = getSingleLineStringWriter(); getSymbolDisplayBuilder().buildSymbolDisplay(symbol, writer, enclosingDeclaration, meaning); + let result = writer.string(); + releaseStringWriter(writer); + return result; + } + + function signatureToString(signature: Signature, enclosingDeclaration?: Node, flags?: TypeFormatFlags): string { + let writer = getSingleLineStringWriter(); + getSymbolDisplayBuilder().buildSignatureDisplay(signature, writer, enclosingDeclaration, flags); let result = writer.string(); releaseStringWriter(writer); @@ -1342,7 +1392,6 @@ module ts { function typeToString(type: Type, enclosingDeclaration?: Node, flags?: TypeFormatFlags): string { let writer = getSingleLineStringWriter(); getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); - let result = writer.string(); releaseStringWriter(writer); @@ -1350,7 +1399,6 @@ module ts { if (maxLength && result.length >= maxLength) { result = result.substr(0, maxLength - "...".length) + "..."; } - return result; } @@ -1465,7 +1513,7 @@ module ts { return appendParentTypeArgumentsAndSymbolName(symbol); } - function buildTypeDisplay(type: Type, writer: SymbolWriter, enclosingDeclaration?: Node, globalFlags?: TypeFormatFlags, typeStack?: Type[]) { + function buildTypeDisplay(type: Type, writer: SymbolWriter, enclosingDeclaration?: Node, globalFlags?: TypeFormatFlags, symbolStack?: Symbol[]) { let globalFlagsToPass = globalFlags & TypeFormatFlags.WriteOwnNameForAnyLike; return writeType(type, globalFlags); @@ -1473,8 +1521,9 @@ module ts { // Write undefined/null type as any if (type.flags & TypeFlags.Intrinsic) { // Special handling for unknown / resolving types, they should show up as any and not unknown or __resolving - writer.writeKeyword(!(globalFlags & TypeFormatFlags.WriteOwnNameForAnyLike) && - (type.flags & TypeFlags.Any) ? "any" : (type).intrinsicName); + writer.writeKeyword(!(globalFlags & TypeFormatFlags.WriteOwnNameForAnyLike) && isTypeAny(type) + ? "any" + : (type).intrinsicName); } else if (type.flags & TypeFlags.Reference) { writeTypeReference(type, flags); @@ -1519,17 +1568,55 @@ module ts { } } + function writeSymbolTypeReference(symbol: Symbol, typeArguments: Type[], pos: number, end: number) { + // Unnamed function expressions, arrow functions, and unnamed class expressions have reserved names that + // we don't want to display + if (!isReservedMemberName(symbol.name)) { + buildSymbolDisplay(symbol, writer, enclosingDeclaration, SymbolFlags.Type); + } + if (pos < end) { + writePunctuation(writer, SyntaxKind.LessThanToken); + writeType(typeArguments[pos++], TypeFormatFlags.None); + while (pos < end) { + writePunctuation(writer, SyntaxKind.CommaToken); + writeSpace(writer); + writeType(typeArguments[pos++], TypeFormatFlags.None); + } + writePunctuation(writer, SyntaxKind.GreaterThanToken); + } + } + function writeTypeReference(type: TypeReference, flags: TypeFormatFlags) { + let typeArguments = type.typeArguments; if (type.target === globalArrayType && !(flags & TypeFormatFlags.WriteArrayAsGenericType)) { - writeType(type.typeArguments[0], TypeFormatFlags.InElementType); + writeType(typeArguments[0], TypeFormatFlags.InElementType); writePunctuation(writer, SyntaxKind.OpenBracketToken); writePunctuation(writer, SyntaxKind.CloseBracketToken); } else { - buildSymbolDisplay(type.target.symbol, writer, enclosingDeclaration, SymbolFlags.Type); - writePunctuation(writer, SyntaxKind.LessThanToken); - writeTypeList(type.typeArguments, /*union*/ false); - writePunctuation(writer, SyntaxKind.GreaterThanToken); + // 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. + let outerTypeParameters = type.target.outerTypeParameters; + let i = 0; + if (outerTypeParameters) { + let length = outerTypeParameters.length; + while (i < length) { + // Find group of type arguments for type parameters with the same declaring container. + let start = i; + let parent = getParentSymbolOfTypeParameter(outerTypeParameters[i]); + do { + i++; + } while (i < length && 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 (!rangeEquals(outerTypeParameters, typeArguments, start, i)) { + writeSymbolTypeReference(parent, typeArguments, start, i); + writePunctuation(writer, SyntaxKind.DotToken); + } + } + } + writeSymbolTypeReference(type.symbol, typeArguments, i, typeArguments.length); } } @@ -1550,49 +1637,54 @@ module ts { } function writeAnonymousType(type: ObjectType, flags: TypeFormatFlags) { - // Always use 'typeof T' for type of class, enum, and module objects - if (type.symbol && type.symbol.flags & (SymbolFlags.Class | SymbolFlags.Enum | SymbolFlags.ValueModule)) { - writeTypeofSymbol(type, flags); - } - // Use 'typeof T' for types of functions and methods that circularly reference themselves - else if (shouldWriteTypeOfFunctionSymbol()) { - writeTypeofSymbol(type, flags); - } - else if (typeStack && contains(typeStack, type)) { - // If type is an anonymous type literal in a type alias declaration, use type alias name - let typeAlias = getTypeAliasForTypeLiteral(type); - if (typeAlias) { - // The specified symbol flags need to be reinterpreted as type flags - buildSymbolDisplay(typeAlias, writer, enclosingDeclaration, SymbolFlags.Type, SymbolFormatFlags.None, flags); + let symbol = type.symbol; + if (symbol) { + // Always use 'typeof T' for type of class, enum, and module objects + if (symbol.flags & (SymbolFlags.Class | SymbolFlags.Enum | SymbolFlags.ValueModule)) { + writeTypeofSymbol(type, flags); + } + else if (shouldWriteTypeOfFunctionSymbol()) { + writeTypeofSymbol(type, flags); + } + else if (contains(symbolStack, symbol)) { + // If type is an anonymous type literal in a type alias declaration, use type alias name + let typeAlias = getTypeAliasForTypeLiteral(type); + if (typeAlias) { + // The specified symbol flags need to be reinterpreted as type flags + buildSymbolDisplay(typeAlias, writer, enclosingDeclaration, SymbolFlags.Type, SymbolFormatFlags.None, flags); + } + else { + // Recursive usage, use any + writeKeyword(writer, SyntaxKind.AnyKeyword); + } } else { - // Recursive usage, use any - writeKeyword(writer, SyntaxKind.AnyKeyword); + // 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 { - if (!typeStack) { - typeStack = []; - } - typeStack.push(type); + // Anonymous types with no symbol are never circular writeLiteralType(type, flags); - typeStack.pop(); } function shouldWriteTypeOfFunctionSymbol() { - if (type.symbol) { - let isStaticMethodSymbol = !!(type.symbol.flags & SymbolFlags.Method && // typeof static method - ts.forEach(type.symbol.declarations, declaration => declaration.flags & NodeFlags.Static)); - let isNonLocalFunctionSymbol = !!(type.symbol.flags & SymbolFlags.Function) && - (type.symbol.parent || // is exported function symbol - ts.forEach(type.symbol.declarations, declaration => - declaration.parent.kind === SyntaxKind.SourceFile || declaration.parent.kind === SyntaxKind.ModuleBlock)); - - if (isStaticMethodSymbol || isNonLocalFunctionSymbol) { - // typeof is allowed only for static/non local functions - return !!(flags & TypeFormatFlags.UseTypeOfFunction) || // use typeof if format flags specify it - (typeStack && contains(typeStack, type)); // it is type of the symbol uses itself recursively - } + let isStaticMethodSymbol = !!(symbol.flags & SymbolFlags.Method && // typeof static method + forEach(symbol.declarations, declaration => declaration.flags & NodeFlags.Static)); + let isNonLocalFunctionSymbol = !!(symbol.flags & SymbolFlags.Function) && + (symbol.parent || // is exported function symbol + forEach(symbol.declarations, declaration => + declaration.parent.kind === SyntaxKind.SourceFile || declaration.parent.kind === SyntaxKind.ModuleBlock)); + if (isStaticMethodSymbol || isNonLocalFunctionSymbol) { + // typeof is allowed only for static/non local functions + return !!(flags & TypeFormatFlags.UseTypeOfFunction) || // use typeof if format flags specify it + (contains(symbolStack, symbol)); // it is type of the symbol uses itself recursively } } } @@ -1627,7 +1719,7 @@ module ts { if (flags & TypeFormatFlags.InElementType) { writePunctuation(writer, SyntaxKind.OpenParenToken); } - buildSignatureDisplay(resolved.callSignatures[0], writer, enclosingDeclaration, globalFlagsToPass | TypeFormatFlags.WriteArrowStyleSignature, typeStack); + buildSignatureDisplay(resolved.callSignatures[0], writer, enclosingDeclaration, globalFlagsToPass | TypeFormatFlags.WriteArrowStyleSignature, symbolStack); if (flags & TypeFormatFlags.InElementType) { writePunctuation(writer, SyntaxKind.CloseParenToken); } @@ -1639,7 +1731,7 @@ module ts { } writeKeyword(writer, SyntaxKind.NewKeyword); writeSpace(writer); - buildSignatureDisplay(resolved.constructSignatures[0], writer, enclosingDeclaration, globalFlagsToPass | TypeFormatFlags.WriteArrowStyleSignature, typeStack); + buildSignatureDisplay(resolved.constructSignatures[0], writer, enclosingDeclaration, globalFlagsToPass | TypeFormatFlags.WriteArrowStyleSignature, symbolStack); if (flags & TypeFormatFlags.InElementType) { writePunctuation(writer, SyntaxKind.CloseParenToken); } @@ -1651,7 +1743,7 @@ module ts { writer.writeLine(); writer.increaseIndent(); for (let signature of resolved.callSignatures) { - buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, typeStack); + buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, symbolStack); writePunctuation(writer, SyntaxKind.SemicolonToken); writer.writeLine(); } @@ -1659,7 +1751,7 @@ module ts { writeKeyword(writer, SyntaxKind.NewKeyword); writeSpace(writer); - buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, typeStack); + buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, symbolStack); writePunctuation(writer, SyntaxKind.SemicolonToken); writer.writeLine(); } @@ -1700,7 +1792,7 @@ module ts { if (p.flags & SymbolFlags.Optional) { writePunctuation(writer, SyntaxKind.QuestionToken); } - buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, typeStack); + buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, symbolStack); writePunctuation(writer, SyntaxKind.SemicolonToken); writer.writeLine(); } @@ -1725,36 +1817,37 @@ module ts { function buildTypeParameterDisplayFromSymbol(symbol: Symbol, writer: SymbolWriter, enclosingDeclaraiton?: Node, flags?: TypeFormatFlags) { let targetSymbol = getTargetSymbol(symbol); if (targetSymbol.flags & SymbolFlags.Class || targetSymbol.flags & SymbolFlags.Interface) { - buildDisplayForTypeParametersAndDelimiters(getTypeParametersOfClassOrInterface(symbol), writer, enclosingDeclaraiton, flags); + buildDisplayForTypeParametersAndDelimiters(getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol), writer, enclosingDeclaraiton, flags); } } - function buildTypeParameterDisplay(tp: TypeParameter, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags, typeStack?: Type[]) { + function buildTypeParameterDisplay(tp: TypeParameter, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags, symbolStack?: Symbol[]) { appendSymbolNameOnly(tp.symbol, writer); let constraint = getConstraintOfTypeParameter(tp); if (constraint) { writeSpace(writer); writeKeyword(writer, SyntaxKind.ExtendsKeyword); writeSpace(writer); - buildTypeDisplay(constraint, writer, enclosingDeclaration, flags, typeStack); + buildTypeDisplay(constraint, writer, enclosingDeclaration, flags, symbolStack); } } - function buildParameterDisplay(p: Symbol, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags, typeStack?: Type[]) { - if (hasDotDotDotToken(p.valueDeclaration)) { + function buildParameterDisplay(p: Symbol, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags, symbolStack?: Symbol[]) { + let parameterNode = p.valueDeclaration; + if (isRestParameter(parameterNode)) { writePunctuation(writer, SyntaxKind.DotDotDotToken); } appendSymbolNameOnly(p, writer); - if (hasQuestionToken(p.valueDeclaration) || (p.valueDeclaration).initializer) { + if (isOptionalParameter(parameterNode)) { writePunctuation(writer, SyntaxKind.QuestionToken); } writePunctuation(writer, SyntaxKind.ColonToken); writeSpace(writer); - buildTypeDisplay(getTypeOfSymbol(p), writer, enclosingDeclaration, flags, typeStack); + buildTypeDisplay(getTypeOfSymbol(p), writer, enclosingDeclaration, flags, symbolStack); } - function buildDisplayForTypeParametersAndDelimiters(typeParameters: TypeParameter[], writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags, typeStack?: Type[]) { + function buildDisplayForTypeParametersAndDelimiters(typeParameters: TypeParameter[], writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags, symbolStack?: Symbol[]) { if (typeParameters && typeParameters.length) { writePunctuation(writer, SyntaxKind.LessThanToken); for (let i = 0; i < typeParameters.length; i++) { @@ -1762,13 +1855,13 @@ module ts { writePunctuation(writer, SyntaxKind.CommaToken); writeSpace(writer); } - buildTypeParameterDisplay(typeParameters[i], writer, enclosingDeclaration, flags, typeStack); + buildTypeParameterDisplay(typeParameters[i], writer, enclosingDeclaration, flags, symbolStack); } writePunctuation(writer, SyntaxKind.GreaterThanToken); } } - function buildDisplayForTypeArgumentsAndDelimiters(typeParameters: TypeParameter[], mapper: TypeMapper, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags, typeStack?: Type[]) { + function buildDisplayForTypeArgumentsAndDelimiters(typeParameters: TypeParameter[], mapper: TypeMapper, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags, symbolStack?: Symbol[]) { if (typeParameters && typeParameters.length) { writePunctuation(writer, SyntaxKind.LessThanToken); for (let i = 0; i < typeParameters.length; i++) { @@ -1782,19 +1875,19 @@ module ts { } } - function buildDisplayForParametersAndDelimiters(parameters: Symbol[], writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags, typeStack?: Type[]) { + function buildDisplayForParametersAndDelimiters(parameters: Symbol[], writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags, symbolStack?: Symbol[]) { writePunctuation(writer, SyntaxKind.OpenParenToken); for (let i = 0; i < parameters.length; i++) { if (i > 0) { writePunctuation(writer, SyntaxKind.CommaToken); writeSpace(writer); } - buildParameterDisplay(parameters[i], writer, enclosingDeclaration, flags, typeStack); + buildParameterDisplay(parameters[i], writer, enclosingDeclaration, flags, symbolStack); } writePunctuation(writer, SyntaxKind.CloseParenToken); } - function buildReturnTypeDisplay(signature: Signature, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags, typeStack?: Type[]) { + function buildReturnTypeDisplay(signature: Signature, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags, symbolStack?: Symbol[]) { if (flags & TypeFormatFlags.WriteArrowStyleSignature) { writeSpace(writer); writePunctuation(writer, SyntaxKind.EqualsGreaterThanToken); @@ -1803,21 +1896,21 @@ module ts { writePunctuation(writer, SyntaxKind.ColonToken); } writeSpace(writer); - buildTypeDisplay(getReturnTypeOfSignature(signature), writer, enclosingDeclaration, flags, typeStack); + buildTypeDisplay(getReturnTypeOfSignature(signature), writer, enclosingDeclaration, flags, symbolStack); } - function buildSignatureDisplay(signature: Signature, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags, typeStack?: Type[]) { + function buildSignatureDisplay(signature: Signature, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags, symbolStack?: Symbol[]) { if (signature.target && (flags & TypeFormatFlags.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, typeStack); + buildDisplayForTypeParametersAndDelimiters(signature.typeParameters, writer, enclosingDeclaration, flags, symbolStack); } - buildDisplayForParametersAndDelimiters(signature.parameters, writer, enclosingDeclaration, flags, typeStack); - buildReturnTypeDisplay(signature, writer, enclosingDeclaration, flags, typeStack); + buildDisplayForParametersAndDelimiters(signature.parameters, writer, enclosingDeclaration, flags, symbolStack); + buildReturnTypeDisplay(signature, writer, enclosingDeclaration, flags, symbolStack); } return _displayBuilder || (_displayBuilder = { @@ -2072,6 +2165,10 @@ module ts { return prop ? getTypeOfSymbol(prop) : undefined; } + function isTypeAny(type: Type) { + return type && (type.flags & TypeFlags.Any) !== 0; + } + // Return the inferred type for a binding element function getTypeForBindingElement(declaration: BindingElement): Type { let pattern = declaration.parent; @@ -2083,7 +2180,7 @@ module ts { // 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 || parentType === anyType) { + if (!parentType || isTypeAny(parentType)) { if (declaration.initializer) { return checkExpressionCached(declaration.initializer); } @@ -2110,7 +2207,7 @@ module ts { // fact an iterable or array (depending on target language). let elementType = checkIteratedTypeOrElementType(parentType, pattern, /*allowStringInput*/ false); if (!declaration.dotDotDotToken) { - if (elementType.flags & TypeFlags.Any) { + if (isTypeAny(elementType)) { return elementType; } @@ -2147,7 +2244,7 @@ module ts { // 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 getIteratedType. + // or it may have led to an error inside getElementTypeOfIterable. return checkRightHandSideOfForOf((declaration.parent.parent).expression) || anyType; } if (isBindingPattern(declaration.parent)) { @@ -2314,7 +2411,7 @@ module ts { // Variable has initializer that circularly references the variable itself type = anyType; if (compilerOptions.noImplicitAny) { - error(symbol.valueDeclaration, Diagnostics._0_implicitly_has_type_any_because_it_is_does_not_have_a_type_annotation_and_is_referenced_directly_or_indirectly_in_its_own_initializer, + error(symbol.valueDeclaration, 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)); } } @@ -2462,80 +2559,190 @@ module ts { } } - // Return combined list of type parameters from all declarations of a class or interface. Elsewhere we check they're all - // the same, but even if they're not we still need the complete list to ensure instantiations supply type arguments - // for all type parameters. - function getTypeParametersOfClassOrInterface(symbol: Symbol): TypeParameter[] { - let result: TypeParameter[]; - forEach(symbol.declarations, node => { - if (node.kind === SyntaxKind.InterfaceDeclaration || node.kind === SyntaxKind.ClassDeclaration) { - let declaration = node; - if (declaration.typeParameters && declaration.typeParameters.length) { - forEach(declaration.typeParameters, node => { - let tp = getDeclaredTypeOfTypeParameter(getSymbolOfNode(node)); - if (!result) { - result = [tp]; - } - else if (!contains(result, tp)) { - result.push(tp); - } - }); + // 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: TypeParameter[], declarations: TypeParameterDeclaration[]): TypeParameter[] { + for (let declaration of declarations) { + let tp = getDeclaredTypeOfTypeParameter(getSymbolOfNode(declaration)); + if (!typeParameters) { + typeParameters = [tp]; + } + else if (!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: TypeParameter[], node: Node): TypeParameter[]{ + while (true) { + node = node.parent; + if (!node) { + return typeParameters; + } + if (node.kind === SyntaxKind.ClassDeclaration || node.kind === SyntaxKind.FunctionDeclaration || + node.kind === SyntaxKind.FunctionExpression || node.kind === SyntaxKind.MethodDeclaration || + node.kind === SyntaxKind.ArrowFunction) { + let 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: Symbol): TypeParameter[] { + var kind = symbol.flags & SymbolFlags.Class ? SyntaxKind.ClassDeclaration : SyntaxKind.InterfaceDeclaration; + return appendOuterTypeParameters(undefined, getDeclarationOfKind(symbol, kind)); + } + + // The local type parameters are the combined set of type parameters from all declarations of the class, + // interface, or type alias. + function getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol: Symbol): TypeParameter[] { + let result: TypeParameter[]; + for (let node of symbol.declarations) { + if (node.kind === SyntaxKind.InterfaceDeclaration || node.kind === SyntaxKind.ClassDeclaration || node.kind === SyntaxKind.TypeAliasDeclaration) { + let 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: Symbol): TypeParameter[] { + return concatenate(getOuterTypeParametersOfClassOrInterface(symbol), getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol)); + } + + function isConstructorType(type: Type): boolean { + return type.flags & TypeFlags.ObjectType && getSignaturesOfType(type, SignatureKind.Construct).length > 0; + } + + function getBaseTypeNodeOfClass(type: InterfaceType): ExpressionWithTypeArguments { + return getClassExtendsHeritageClauseElement(type.symbol.valueDeclaration); + } + + function getConstructorsForTypeArguments(type: ObjectType, typeArgumentNodes: TypeNode[]): Signature[] { + let typeArgCount = typeArgumentNodes ? typeArgumentNodes.length : 0; + return filter(getSignaturesOfType(type, SignatureKind.Construct), + sig => (sig.typeParameters ? sig.typeParameters.length : 0) === typeArgCount); + } + + function getInstantiatedConstructorsForTypeArguments(type: ObjectType, typeArgumentNodes: TypeNode[]): Signature[] { + let signatures = getConstructorsForTypeArguments(type, typeArgumentNodes); + if (typeArgumentNodes) { + let typeArguments = map(typeArgumentNodes, getTypeFromTypeNode); + signatures = map(signatures, sig => getSignatureInstantiation(sig, typeArguments)); + } + 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, or + // an object type with at least one construct signature. + function getBaseConstructorTypeOfClass(type: InterfaceType): ObjectType { + if (!type.resolvedBaseConstructorType) { + let baseTypeNode = getBaseTypeNodeOfClass(type); + if (!baseTypeNode) { + return type.resolvedBaseConstructorType = undefinedType; + } + if (!pushTypeResolution(type)) { + return unknownType; + } + let baseConstructorType = checkExpression(baseTypeNode.expression); + if (baseConstructorType.flags & TypeFlags.ObjectType) { + // 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. + resolveObjectOrUnionTypeMembers(baseConstructorType); + } + if (!popTypeResolution()) { + error(type.symbol.valueDeclaration, Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_base_expression, symbolToString(type.symbol)); + return type.resolvedBaseConstructorType = unknownType; + } + if (baseConstructorType !== unknownType && baseConstructorType !== nullType && !isConstructorType(baseConstructorType)) { + error(baseTypeNode.expression, Diagnostics.Type_0_is_not_a_constructor_function_type, typeToString(baseConstructorType)); + return type.resolvedBaseConstructorType = unknownType; + } + type.resolvedBaseConstructorType = baseConstructorType; + } + return type.resolvedBaseConstructorType; + } + function getBaseTypes(type: InterfaceType): ObjectType[] { - let typeWithBaseTypes = type; - if (!typeWithBaseTypes.baseTypes) { + if (!type.resolvedBaseTypes) { if (type.symbol.flags & SymbolFlags.Class) { - resolveBaseTypesOfClass(typeWithBaseTypes); + resolveBaseTypesOfClass(type); } else if (type.symbol.flags & SymbolFlags.Interface) { - resolveBaseTypesOfInterface(typeWithBaseTypes); + resolveBaseTypesOfInterface(type); } else { Debug.fail("type must be class or interface"); } } - - return typeWithBaseTypes.baseTypes; + return type.resolvedBaseTypes; } - function resolveBaseTypesOfClass(type: InterfaceTypeWithBaseTypes): void { - type.baseTypes = []; - let declaration = getDeclarationOfKind(type.symbol, SyntaxKind.ClassDeclaration); - let baseTypeNode = getClassExtendsHeritageClauseElement(declaration); - if (baseTypeNode) { - let baseType = getTypeFromTypeNode(baseTypeNode); - if (baseType !== unknownType) { - if (getTargetType(baseType).flags & TypeFlags.Class) { - if (type !== baseType && !hasBaseType(baseType, type)) { - type.baseTypes.push(baseType); - } - else { - error(declaration, Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, /*enclosingDeclaration*/ undefined, TypeFormatFlags.WriteArrayAsGenericType)); - } - } - else { - error(baseTypeNode, Diagnostics.A_class_may_only_extend_another_class); - } - } + function resolveBaseTypesOfClass(type: InterfaceType): void { + type.resolvedBaseTypes = emptyArray; + let baseContructorType = getBaseConstructorTypeOfClass(type); + if (!(baseContructorType.flags & TypeFlags.ObjectType)) { + return; } + let baseTypeNode = getBaseTypeNodeOfClass(type); + let baseType: Type; + if (baseContructorType.symbol && baseContructorType.symbol.flags & SymbolFlags.Class) { + // When base constructor type is a class 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, baseContructorType.symbol); + } + 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. + let constructors = getInstantiatedConstructorsForTypeArguments(baseContructorType, baseTypeNode.typeArguments); + if (!constructors.length) { + error(baseTypeNode.expression, Diagnostics.No_base_constructor_has_the_specified_number_of_type_arguments); + return; + } + baseType = getReturnTypeOfSignature(constructors[0]); + } + if (baseType === unknownType) { + return; + } + if (!(getTargetType(baseType).flags & (TypeFlags.Class | TypeFlags.Interface))) { + error(baseTypeNode.expression, Diagnostics.Base_constructor_return_type_0_is_not_a_class_or_interface_type, typeToString(baseType)); + return; + } + if (type === baseType || hasBaseType(baseType, type)) { + error(type.symbol.valueDeclaration, Diagnostics.Type_0_recursively_references_itself_as_a_base_type, + typeToString(type, /*enclosingDeclaration*/ undefined, TypeFormatFlags.WriteArrayAsGenericType)); + return; + } + type.resolvedBaseTypes = [baseType]; } - function resolveBaseTypesOfInterface(type: InterfaceTypeWithBaseTypes): void { - type.baseTypes = []; + function resolveBaseTypesOfInterface(type: InterfaceType): void { + type.resolvedBaseTypes = []; for (let declaration of type.symbol.declarations) { if (declaration.kind === SyntaxKind.InterfaceDeclaration && getInterfaceBaseTypeNodes(declaration)) { for (let node of getInterfaceBaseTypeNodes(declaration)) { let baseType = getTypeFromTypeNode(node); - if (baseType !== unknownType) { if (getTargetType(baseType).flags & (TypeFlags.Class | TypeFlags.Interface)) { if (type !== baseType && !hasBaseType(baseType, type)) { - type.baseTypes.push(baseType); + type.resolvedBaseTypes.push(baseType); } else { error(declaration, Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, /*enclosingDeclaration*/ undefined, TypeFormatFlags.WriteArrayAsGenericType)); @@ -2555,10 +2762,13 @@ module ts { if (!links.declaredType) { let kind = symbol.flags & SymbolFlags.Class ? TypeFlags.Class : TypeFlags.Interface; let type = links.declaredType = createObjectType(kind, symbol); - let typeParameters = getTypeParametersOfClassOrInterface(symbol); - if (typeParameters) { + let outerTypeParameters = getOuterTypeParametersOfClassOrInterface(symbol); + let localTypeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); + if (outerTypeParameters || localTypeParameters) { type.flags |= TypeFlags.Reference; - type.typeParameters = typeParameters; + type.typeParameters = concatenate(outerTypeParameters, localTypeParameters); + type.outerTypeParameters = outerTypeParameters; + type.localTypeParameters = localTypeParameters; (type).instantiations = {}; (type).instantiations[getTypeListId(type.typeParameters)] = type; (type).target = type; @@ -2578,7 +2788,16 @@ module ts { } let declaration = getDeclarationOfKind(symbol, SyntaxKind.TypeAliasDeclaration); let type = getTypeFromTypeNode(declaration.type); - if (!popTypeResolution()) { + if (popTypeResolution()) { + links.typeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); + if (links.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.instantiations = {}; + links.instantiations[getTypeListId(links.typeParameters)] = type; + } + } + else { type = unknownType; error(declaration.name, Diagnostics.Type_alias_0_circularly_references_itself, symbolToString(symbol)); } @@ -2672,7 +2891,7 @@ module ts { function resolveDeclaredMembers(type: InterfaceType): InterfaceTypeWithDeclaredMembers { if (!(type).declaredProperties) { - var symbol = type.symbol; + let symbol = type.symbol; (type).declaredProperties = getNamedMembers(symbol.members); (type).declaredCallSignatures = getSignaturesOfSymbol(symbol.members["__call"]); (type).declaredConstructSignatures = getSignaturesOfSymbol(symbol.members["__new"]); @@ -2723,12 +2942,13 @@ module ts { } function createSignature(declaration: SignatureDeclaration, typeParameters: TypeParameter[], parameters: Symbol[], - resolvedReturnType: Type, minArgumentCount: number, hasRestParameter: boolean, hasStringLiterals: boolean): Signature { + resolvedReturnType: Type, typePredicate: TypePredicate, minArgumentCount: number, hasRestParameter: boolean, hasStringLiterals: boolean): Signature { let sig = new Signature(checker); sig.declaration = declaration; sig.typeParameters = typeParameters; sig.parameters = parameters; sig.resolvedReturnType = resolvedReturnType; + sig.typePredicate = typePredicate; sig.minArgumentCount = minArgumentCount; sig.hasRestParameter = hasRestParameter; sig.hasStringLiterals = hasStringLiterals; @@ -2736,24 +2956,30 @@ module ts { } function cloneSignature(sig: Signature): Signature { - return createSignature(sig.declaration, sig.typeParameters, sig.parameters, sig.resolvedReturnType, + return createSignature(sig.declaration, sig.typeParameters, sig.parameters, sig.resolvedReturnType, sig.typePredicate, sig.minArgumentCount, sig.hasRestParameter, sig.hasStringLiterals); } - function getDefaultConstructSignatures(classType: InterfaceType): Signature[]{ - let baseTypes = getBaseTypes(classType); - if (baseTypes.length) { - let baseType = baseTypes[0]; - let baseSignatures = getSignaturesOfType(getTypeOfSymbol(baseType.symbol), SignatureKind.Construct); - return map(baseSignatures, baseSignature => { - let signature = baseType.flags & TypeFlags.Reference ? - getSignatureInstantiation(baseSignature, (baseType).typeArguments) : cloneSignature(baseSignature); - signature.typeParameters = classType.typeParameters; - signature.resolvedReturnType = classType; - return signature; - }); + function getDefaultConstructSignatures(classType: InterfaceType): Signature[] { + if (!getBaseTypes(classType).length) { + return [createSignature(undefined, classType.localTypeParameters, emptyArray, classType, undefined, 0, false, false)]; } - return [createSignature(undefined, classType.typeParameters, emptyArray, classType, 0, false, false)]; + let baseConstructorType = getBaseConstructorTypeOfClass(classType); + let baseSignatures = getSignaturesOfType(baseConstructorType, SignatureKind.Construct); + let baseTypeNode = getBaseTypeNodeOfClass(classType); + let typeArguments = map(baseTypeNode.typeArguments, getTypeFromTypeNode); + let typeArgCount = typeArguments ? typeArguments.length : 0; + let result: Signature[] = []; + for (let baseSig of baseSignatures) { + let typeParamCount = baseSig.typeParameters ? baseSig.typeParameters.length : 0; + if (typeParamCount === typeArgCount) { + let sig = typeParamCount ? getSignatureInstantiation(baseSig, typeArguments) : cloneSignature(baseSig); + sig.typeParameters = classType.localTypeParameters; + sig.resolvedReturnType = classType; + result.push(sig); + } + } + return result; } function createTupleTypeMemberSymbols(memberTypes: Type[]): SymbolTable { @@ -2865,10 +3091,10 @@ module ts { if (!constructSignatures.length) { constructSignatures = getDefaultConstructSignatures(classType); } - let baseTypes = getBaseTypes(classType); - if (baseTypes.length) { + let baseConstructorType = getBaseConstructorTypeOfClass(classType); + if (baseConstructorType.flags & TypeFlags.ObjectType) { members = createSymbolTable(getNamedMembers(members)); - addInheritedMembers(members, getPropertiesOfObjectType(getTypeOfSymbol(baseTypes[0].symbol))); + addInheritedMembers(members, getPropertiesOfObjectType(baseConstructorType)); } } stringIndexType = undefined; @@ -3098,11 +3324,15 @@ module ts { return result; } + function isOptionalParameter(node: ParameterDeclaration) { + return hasQuestionToken(node) || !!node.initializer; + } + function getSignatureFromDeclaration(declaration: SignatureDeclaration): Signature { let links = getNodeLinks(declaration); if (!links.resolvedSignature) { let classType = declaration.kind === SyntaxKind.Constructor ? getDeclaredTypeOfClassOrInterface((declaration.parent).symbol) : undefined; - let typeParameters = classType ? classType.typeParameters : + let typeParameters = classType ? classType.localTypeParameters : declaration.typeParameters ? getTypeParametersFromDeclaration(declaration.typeParameters) : undefined; let parameters: Symbol[] = []; let hasStringLiterals = false; @@ -3125,11 +3355,20 @@ module ts { } let returnType: Type; + let typePredicate: TypePredicate; if (classType) { returnType = classType; } else if (declaration.type) { returnType = getTypeFromTypeNode(declaration.type); + if (declaration.type.kind === SyntaxKind.TypePredicate) { + let typePredicateNode = declaration.type; + typePredicate = { + parameterName: typePredicateNode.parameterName ? typePredicateNode.parameterName.text : undefined, + parameterIndex: typePredicateNode.parameterName ? getTypePredicateParameterIndex(declaration.parameters, typePredicateNode.parameterName) : undefined, + type: getTypeFromTypeNode(typePredicateNode.type) + }; + } } else { // TypeScript 1.0 spec (April 2014): @@ -3144,8 +3383,8 @@ module ts { } } - links.resolvedSignature = createSignature(declaration, typeParameters, parameters, returnType, - minArgumentCount, hasRestParameters(declaration), hasStringLiterals); + links.resolvedSignature = createSignature(declaration, typeParameters, parameters, returnType, typePredicate, + minArgumentCount, hasRestParameter(declaration), hasStringLiterals); } return links.resolvedSignature; } @@ -3304,6 +3543,10 @@ module ts { return type.constraint === noConstraintType ? undefined : type.constraint; } + function getParentSymbolOfTypeParameter(typeParameter: TypeParameter): Symbol { + return getSymbolOfNode(getDeclarationOfKind(typeParameter.symbol, SyntaxKind.TypeParameter).parent); + } + function getTypeListId(types: Type[]) { switch (types.length) { case 1: @@ -3379,7 +3622,7 @@ module ts { // -> typeParameter and symbol.declaration originate from the same type parameter list // -> illegal for all declarations in symbol // forEach === exists - links.isIllegalTypeReferenceInConstraint = forEach(symbol.declarations, d => d.parent == typeParameter.parent); + links.isIllegalTypeReferenceInConstraint = forEach(symbol.declarations, d => d.parent === typeParameter.parent); } } if (links.isIllegalTypeReferenceInConstraint) { @@ -3395,50 +3638,83 @@ module ts { } } - function getTypeFromTypeReferenceOrExpressionWithTypeArguments(node: TypeReferenceNode | ExpressionWithTypeArguments): Type { + // Get type from reference to class or interface + function getTypeFromClassOrInterfaceReference(node: TypeReferenceNode | ExpressionWithTypeArguments, symbol: Symbol): Type { + let type = getDeclaredTypeOfSymbol(symbol); + let typeParameters = (type).localTypeParameters; + if (typeParameters) { + if (!node.typeArguments || node.typeArguments.length !== typeParameters.length) { + error(node, Diagnostics.Generic_type_0_requires_1_type_argument_s, typeToString(type, /*enclosingDeclaration*/ undefined, TypeFormatFlags.WriteArrayAsGenericType), 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. + return createTypeReference(type, concatenate((type).outerTypeParameters, + map(node.typeArguments, getTypeFromTypeNode))); + } + if (node.typeArguments) { + error(node, Diagnostics.Type_0_is_not_generic, typeToString(type)); + return unknownType; + } + return type; + } + + // Get type from reference to type alias. When a type alias is generic, the declared type of the type alias may include + // references to the type parameters of the alias. We replace those with the actual type arguments by instantiating the + // declared type. Instantiations are cached using the type identities of the type arguments as the key. + function getTypeFromTypeAliasReference(node: TypeReferenceNode | ExpressionWithTypeArguments, symbol: Symbol): Type { + let type = getDeclaredTypeOfSymbol(symbol); + let links = getSymbolLinks(symbol); + let typeParameters = links.typeParameters; + if (typeParameters) { + if (!node.typeArguments || node.typeArguments.length !== typeParameters.length) { + error(node, Diagnostics.Generic_type_0_requires_1_type_argument_s, symbolToString(symbol), typeParameters.length); + return unknownType; + } + let typeArguments = map(node.typeArguments, getTypeFromTypeNode); + let id = getTypeListId(typeArguments); + return links.instantiations[id] || (links.instantiations[id] = instantiateType(type, createTypeMapper(typeParameters, typeArguments))); + } + if (node.typeArguments) { + error(node, 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: TypeReferenceNode | ExpressionWithTypeArguments, symbol: Symbol): Type { + if (symbol.flags & SymbolFlags.TypeParameter && isTypeParameterReferenceIllegalInConstraint(node, symbol)) { + // TypeScript 1.0 spec (April 2014): 3.4.1 + // Type parameters declared in a particular type parameter list + // may not be referenced in constraints in that type parameter list + // Implementation: such type references are resolved to 'unknown' type that usually denotes error + return unknownType; + } + if (node.typeArguments) { + error(node, Diagnostics.Type_0_is_not_generic, symbolToString(symbol)); + return unknownType; + } + return getDeclaredTypeOfSymbol(symbol); + } + + function getTypeFromTypeReference(node: TypeReferenceNode | ExpressionWithTypeArguments): Type { let links = getNodeLinks(node); if (!links.resolvedType) { - let type: Type; - - // We don't currently support heritage clauses with complex expressions in them. - // For these cases, we just set the type to be the unknownType. - if (node.kind !== SyntaxKind.ExpressionWithTypeArguments || isSupportedExpressionWithTypeArguments(node)) { - let typeNameOrExpression = node.kind === SyntaxKind.TypeReference - ? (node).typeName - : (node).expression; - - let symbol = resolveEntityName(typeNameOrExpression, SymbolFlags.Type); - if (symbol) { - if ((symbol.flags & SymbolFlags.TypeParameter) && isTypeParameterReferenceIllegalInConstraint(node, symbol)) { - // TypeScript 1.0 spec (April 2014): 3.4.1 - // Type parameters declared in a particular type parameter list - // may not be referenced in constraints in that type parameter list - // Implementation: such type references are resolved to 'unknown' type that usually denotes error - type = unknownType; - } - else { - type = getDeclaredTypeOfSymbol(symbol); - if (type.flags & (TypeFlags.Class | TypeFlags.Interface) && type.flags & TypeFlags.Reference) { - let typeParameters = (type).typeParameters; - if (node.typeArguments && node.typeArguments.length === typeParameters.length) { - type = createTypeReference(type, map(node.typeArguments, getTypeFromTypeNode)); - } - else { - error(node, Diagnostics.Generic_type_0_requires_1_type_argument_s, typeToString(type, /*enclosingDeclaration*/ undefined, TypeFormatFlags.WriteArrayAsGenericType), typeParameters.length); - type = undefined; - } - } - else { - if (node.typeArguments) { - error(node, Diagnostics.Type_0_is_not_generic, typeToString(type)); - type = undefined; - } - } - } - } - } - - links.resolvedType = type || unknownType; + // We only support expressions that are simple qualified names. For other expressions this produces undefined. + let typeNameOrExpression = node.kind === SyntaxKind.TypeReference ? (node).typeName : + isSupportedExpressionWithTypeArguments(node) ? (node).expression : + undefined; + let symbol = typeNameOrExpression && resolveEntityName(typeNameOrExpression, SymbolFlags.Type) || unknownSymbol; + let type = symbol === unknownSymbol ? unknownType : + symbol.flags & (SymbolFlags.Class | SymbolFlags.Interface) ? getTypeFromClassOrInterfaceReference(node, symbol) : + symbol.flags & SymbolFlags.TypeAlias ? getTypeFromTypeAliasReference(node, symbol) : + getTypeFromNonGenericTypeReference(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; } @@ -3450,7 +3726,7 @@ module ts { // 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(checkExpressionOrQualifiedName(node.exprName)); + links.resolvedType = getWidenedType(checkExpression(node.exprName)); } return links.resolvedType; } @@ -3470,16 +3746,16 @@ module ts { } if (!symbol) { - return emptyObjectType; + return arity ? emptyGenericType : emptyObjectType; } let type = getDeclaredTypeOfSymbol(symbol); if (!(type.flags & TypeFlags.ObjectType)) { error(getTypeDeclaration(symbol), Diagnostics.Global_type_0_must_be_a_class_or_interface_type, symbol.name); - return emptyObjectType; + return arity ? emptyGenericType : emptyObjectType; } if (((type).typeParameters ? (type).typeParameters.length : 0) !== arity) { error(getTypeDeclaration(symbol), Diagnostics.Global_type_0_must_have_1_type_parameter_s, symbol.name, arity); - return emptyObjectType; + return arity ? emptyGenericType : emptyObjectType; } return type; } @@ -3514,16 +3790,23 @@ module ts { : emptyObjectType; } + /** + * Instantiates a global type that is generic with some element type, and returns that instantiation. + */ + function createTypeFromGenericGlobalType(genericGlobalType: GenericType, elementType: Type): Type { + return genericGlobalType !== emptyGenericType ? createTypeReference(genericGlobalType, [elementType]) : emptyObjectType; + } + function createIterableType(elementType: Type): Type { - return globalIterableType !== emptyObjectType ? createTypeReference(globalIterableType, [elementType]) : emptyObjectType; + return createTypeFromGenericGlobalType(globalIterableType, elementType); + } + + function createIterableIteratorType(elementType: Type): Type { + return createTypeFromGenericGlobalType(globalIterableIteratorType, elementType); } function createArrayType(elementType: Type): Type { - // globalArrayType will be undefined if we get here during creation of the Array type. This for example happens if - // user code augments the Array type with call or construct signatures that have an array type as the return type. - // We instead use globalArraySymbol to obtain the (not yet fully constructed) Array type. - let arrayType = globalArrayType || getDeclaredTypeOfSymbol(globalArraySymbol); - return arrayType !== emptyObjectType ? createTypeReference(arrayType, [elementType]) : emptyObjectType; + return createTypeFromGenericGlobalType(globalArrayType, elementType); } function getTypeFromArrayTypeNode(node: ArrayTypeNode): Type { @@ -3593,9 +3876,9 @@ module ts { } } - function containsAnyType(types: Type[]) { + function containsTypeAny(types: Type[]) { for (let type of types) { - if (type.flags & TypeFlags.Any) { + if (isTypeAny(type)) { return true; } } @@ -3623,7 +3906,7 @@ module ts { let sortedTypes: Type[] = []; addTypesToSortedSet(sortedTypes, types); if (noSubtypeReduction) { - if (containsAnyType(sortedTypes)) { + if (containsTypeAny(sortedTypes)) { return anyType; } removeAllButLast(sortedTypes, undefinedType); @@ -3715,9 +3998,11 @@ module ts { case SyntaxKind.StringLiteral: return getTypeFromStringLiteral(node); case SyntaxKind.TypeReference: - return getTypeFromTypeReferenceOrExpressionWithTypeArguments(node); + return getTypeFromTypeReference(node); + case SyntaxKind.TypePredicate: + return booleanType; case SyntaxKind.ExpressionWithTypeArguments: - return getTypeFromTypeReferenceOrExpressionWithTypeArguments(node); + return getTypeFromTypeReference(node); case SyntaxKind.TypeQuery: return getTypeFromTypeQueryNode(node); case SyntaxKind.ArrayType: @@ -3835,13 +4120,22 @@ module ts { function instantiateSignature(signature: Signature, mapper: TypeMapper, eraseTypeParameters?: boolean): Signature { let freshTypeParameters: TypeParameter[]; + let freshTypePredicate: TypePredicate; if (signature.typeParameters && !eraseTypeParameters) { freshTypeParameters = instantiateList(signature.typeParameters, mapper, instantiateTypeParameter); mapper = combineTypeMappers(createTypeMapper(signature.typeParameters, freshTypeParameters), mapper); } + if (signature.typePredicate) { + freshTypePredicate = { + parameterName: signature.typePredicate.parameterName, + parameterIndex: signature.typePredicate.parameterIndex, + type: instantiateType(signature.typePredicate.type, mapper) + } + } let result = createSignature(signature.declaration, freshTypeParameters, instantiateList(signature.parameters, mapper, instantiateSymbol), signature.resolvedReturnType ? instantiateType(signature.resolvedReturnType, mapper) : undefined, + freshTypePredicate, signature.minArgumentCount, signature.hasRestParameter, signature.hasStringLiterals); result.target = signature; result.mapper = mapper; @@ -3873,19 +4167,8 @@ module ts { } function instantiateAnonymousType(type: ObjectType, mapper: TypeMapper): ObjectType { - // If this type has already been instantiated using this mapper, returned the cached result. This guards against - // infinite instantiations of cyclic types, e.g. "var x: { a: T, b: typeof x };" - if (mapper.mappings) { - let cached = mapper.mappings[type.id]; - if (cached) { - return cached; - } - } - else { - mapper.mappings = {}; - } - // Instantiate the given type using the given mapper and cache the result - let result = createObjectType(TypeFlags.Anonymous, type.symbol); + // Mark the anonymous type as instantiated such that our infinite instantiation detection logic can recognize it + let result = createObjectType(TypeFlags.Anonymous | TypeFlags.Instantiated, type.symbol); result.properties = instantiateList(getPropertiesOfObjectType(type), mapper, instantiateSymbol); result.members = createSymbolTable(result.properties); result.callSignatures = instantiateList(getSignaturesOfType(type, SignatureKind.Call), mapper, instantiateSignature); @@ -3894,7 +4177,6 @@ module ts { let numberIndexType = getIndexTypeOfType(type, IndexKind.Number); if (stringIndexType) result.stringIndexType = instantiateType(stringIndexType, mapper); if (numberIndexType) result.numberIndexType = instantiateType(numberIndexType, mapper); - mapper.mappings[type.id] = result; return result; } @@ -3904,7 +4186,7 @@ module ts { return mapper(type); } if (type.flags & TypeFlags.Anonymous) { - return type.symbol && type.symbol.flags & (SymbolFlags.Function | SymbolFlags.Method | SymbolFlags.TypeLiteral | SymbolFlags.ObjectLiteral) ? + return type.symbol && type.symbol.flags & (SymbolFlags.Function | SymbolFlags.Method | SymbolFlags.Class | SymbolFlags.TypeLiteral | SymbolFlags.ObjectLiteral) ? instantiateAnonymousType(type, mapper) : type; } if (type.flags & TypeFlags.Reference) { @@ -3954,14 +4236,14 @@ module ts { return !node.typeParameters && node.parameters.length && !forEach(node.parameters, p => p.type); } - function getTypeWithoutConstructors(type: Type): Type { + function getTypeWithoutSignatures(type: Type): Type { if (type.flags & TypeFlags.ObjectType) { let resolved = resolveObjectOrUnionTypeMembers(type); if (resolved.constructSignatures.length) { let result = createObjectType(TypeFlags.Anonymous, type.symbol); result.members = resolved.members; result.properties = resolved.properties; - result.callSignatures = resolved.callSignatures; + result.callSignatures = emptyArray; result.constructSignatures = emptyArray; type = result; } @@ -3971,10 +4253,6 @@ module ts { // TYPE CHECKING - let subtypeRelation: Map = {}; - let assignableRelation: Map = {}; - let identityRelation: Map = {}; - function isTypeIdenticalTo(source: Type, target: Type): boolean { return checkTypeRelatedTo(source, target, identityRelation, /*errorNode*/ undefined); } @@ -4059,13 +4337,13 @@ module ts { // 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 Ternary.True; if (relation !== identityRelation) { - if (target.flags & TypeFlags.Any) return Ternary.True; + if (isTypeAny(target)) return Ternary.True; if (source === undefinedType) return Ternary.True; if (source === nullType && target !== undefinedType) return Ternary.True; if (source.flags & TypeFlags.Enum && target === numberType) return Ternary.True; if (source.flags & TypeFlags.StringLiteral && target === stringType) return Ternary.True; if (relation === assignableRelation) { - if (source.flags & TypeFlags.Any) return Ternary.True; + if (isTypeAny(source)) return Ternary.True; if (source === numberType && target.flags & TypeFlags.Enum) return Ternary.True; } } @@ -4266,8 +4544,8 @@ module ts { maybeStack[depth][id] = RelationComparisonResult.Succeeded; depth++; let saveExpandingFlags = expandingFlags; - if (!(expandingFlags & 1) && isDeeplyNestedGeneric(source, sourceStack)) expandingFlags |= 1; - if (!(expandingFlags & 2) && isDeeplyNestedGeneric(target, targetStack)) expandingFlags |= 2; + if (!(expandingFlags & 1) && isDeeplyNestedGeneric(source, sourceStack, depth)) expandingFlags |= 1; + if (!(expandingFlags & 2) && isDeeplyNestedGeneric(target, targetStack, depth)) expandingFlags |= 2; let result: Ternary; if (expandingFlags === 3) { result = Ternary.Maybe; @@ -4303,26 +4581,6 @@ module ts { return result; } - // Return true if the given type is part of a deeply nested chain of generic instantiations. We consider this to be the case - // when structural type comparisons have been started for 10 or more instantiations of the same generic type. 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 10 levels, but unequal at - // some level beyond that. - function isDeeplyNestedGeneric(type: ObjectType, stack: ObjectType[]): boolean { - if (type.flags & TypeFlags.Reference && depth >= 10) { - let target = (type).target; - let count = 0; - for (let i = 0; i < depth; i++) { - let t = stack[i]; - if (t.flags & TypeFlags.Reference && (t).target === target) { - count++; - if (count >= 10) return true; - } - } - } - return false; - } - function propertiesRelatedTo(source: ObjectType, target: ObjectType, reportErrors: boolean): Ternary { if (relation === identityRelation) { return propertiesIdenticalTo(source, target); @@ -4509,6 +4767,44 @@ module ts { } result &= related; } + + if (source.typePredicate && target.typePredicate) { + let hasDifferentParameterIndex = source.typePredicate.parameterIndex !== target.typePredicate.parameterIndex; + let hasDifferentTypes: boolean; + if (hasDifferentParameterIndex || + (hasDifferentTypes = !isTypeIdenticalTo(source.typePredicate.type, target.typePredicate.type))) { + + if (reportErrors) { + let sourceParamText = source.typePredicate.parameterName; + let targetParamText = target.typePredicate.parameterName; + let sourceTypeText = typeToString(source.typePredicate.type); + let targetTypeText = typeToString(target.typePredicate.type); + + if (hasDifferentParameterIndex) { + reportError(Diagnostics.Parameter_0_is_not_in_the_same_position_as_parameter_1, + sourceParamText, + targetParamText); + } + else if (hasDifferentTypes) { + reportError(Diagnostics.Type_0_is_not_assignable_to_type_1, + sourceTypeText, + targetTypeText); + } + + reportError(Diagnostics.Type_predicate_0_is_not_assignable_to_1, + `${sourceParamText} is ${sourceTypeText}`, + `${targetParamText} is ${targetTypeText}`); + } + return Ternary.False; + } + } + else if (!source.typePredicate && target.typePredicate) { + if (reportErrors) { + reportError(Diagnostics.Signature_0_must_have_a_type_predicate, signatureToString(source)); + } + return Ternary.False; + } + let t = getReturnTypeOfSignature(target); if (t === voidType) return result; let s = getReturnTypeOfSignature(source); @@ -4603,6 +4899,27 @@ module ts { } } + // Return true if the given type is part of a deeply nested chain of generic instantiations. We consider this to be the case + // when structural type comparisons have been started for 10 or more instantiations of the same generic type. 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 10 levels, but unequal at + // some level beyond that. + function isDeeplyNestedGeneric(type: Type, stack: Type[], depth: number): boolean { + // We track type references (created by createTypeReference) and instantiated types (created by instantiateType) + if (type.flags & (TypeFlags.Reference | TypeFlags.Instantiated) && depth >= 5) { + let symbol = type.symbol; + let count = 0; + for (let i = 0; i < depth; i++) { + let t = stack[i]; + if (t.flags & (TypeFlags.Reference | TypeFlags.Instantiated) && t.symbol === symbol) { + count++; + if (count >= 5) return true; + } + } + } + return false; + } + function isPropertyIdenticalTo(sourceProp: Symbol, targetProp: Symbol): boolean { return compareProperties(sourceProp, targetProp, compareTypes) !== Ternary.False; } @@ -4917,21 +5234,6 @@ module ts { return false; } - function isWithinDepthLimit(type: Type, stack: Type[]) { - if (depth >= 5) { - let target = (type).target; - let count = 0; - for (let i = 0; i < depth; i++) { - let t = stack[i]; - if (t.flags & TypeFlags.Reference && (t).target === target) { - count++; - } - } - return count < 5; - } - return true; - } - function inferFromTypes(source: Type, target: Type) { if (source === anyFunctionType) { return; @@ -4999,22 +5301,27 @@ module ts { else if (source.flags & TypeFlags.ObjectType && (target.flags & (TypeFlags.Reference | TypeFlags.Tuple) || (target.flags & TypeFlags.Anonymous) && target.symbol && target.symbol.flags & (SymbolFlags.Method | SymbolFlags.TypeLiteral))) { // If source is an object type, and target is a type reference, a tuple type, the type of a method, or a type literal, infer from members - if (!isInProcess(source, target) && isWithinDepthLimit(source, sourceStack) && isWithinDepthLimit(target, targetStack)) { - if (depth === 0) { - sourceStack = []; - targetStack = []; - } - sourceStack[depth] = source; - targetStack[depth] = target; - depth++; - inferFromProperties(source, target); - inferFromSignatures(source, target, SignatureKind.Call); - inferFromSignatures(source, target, SignatureKind.Construct); - inferFromIndexTypes(source, target, IndexKind.String, IndexKind.String); - inferFromIndexTypes(source, target, IndexKind.Number, IndexKind.Number); - inferFromIndexTypes(source, target, IndexKind.String, IndexKind.Number); - depth--; + if (isInProcess(source, target)) { + return; } + if (isDeeplyNestedGeneric(source, sourceStack, depth) && isDeeplyNestedGeneric(target, targetStack, depth)) { + return; + } + + if (depth === 0) { + sourceStack = []; + targetStack = []; + } + sourceStack[depth] = source; + targetStack[depth] = target; + depth++; + inferFromProperties(source, target); + inferFromSignatures(source, target, SignatureKind.Call); + inferFromSignatures(source, target, SignatureKind.Construct); + inferFromIndexTypes(source, target, IndexKind.String, IndexKind.String); + inferFromIndexTypes(source, target, IndexKind.Number, IndexKind.Number); + inferFromIndexTypes(source, target, IndexKind.String, IndexKind.Number); + depth--; } } @@ -5041,7 +5348,17 @@ module ts { function inferFromSignature(source: Signature, target: Signature) { forEachMatchingParameterType(source, target, inferFromTypes); - inferFromTypes(getReturnTypeOfSignature(source), getReturnTypeOfSignature(target)); + if (source.typePredicate && target.typePredicate) { + if (target.typePredicate.parameterIndex === source.typePredicate.parameterIndex) { + // Return types from type predicates are treated as booleans. In order to infer types + // from type predicates we would need to infer using the type within the type predicate + // (i.e. 'Foo' from 'x is Foo'). + inferFromTypes(source.typePredicate.type, target.typePredicate.type); + } + } + else { + inferFromTypes(getReturnTypeOfSignature(source), getReturnTypeOfSignature(target)); + } } function inferFromIndexTypes(source: Type, target: Type, sourceKind: IndexKind, targetKind: IndexKind) { @@ -5289,55 +5606,58 @@ module ts { function getNarrowedTypeOfSymbol(symbol: Symbol, node: Node) { let type = getTypeOfSymbol(symbol); // Only narrow when symbol is variable of type any or an object, union, or type parameter type - if (node && symbol.flags & SymbolFlags.Variable && type.flags & (TypeFlags.Any | TypeFlags.ObjectType | TypeFlags.Union | TypeFlags.TypeParameter)) { - loop: while (node.parent) { - let child = node; - node = node.parent; - let narrowedType = type; - switch (node.kind) { - case SyntaxKind.IfStatement: - // In a branch of an if statement, narrow based on controlling expression - if (child !== (node).expression) { - narrowedType = narrowType(type, (node).expression, /*assumeTrue*/ child === (node).thenStatement); - } - break; - case SyntaxKind.ConditionalExpression: - // In a branch of a conditional expression, narrow based on controlling condition - if (child !== (node).condition) { - narrowedType = narrowType(type, (node).condition, /*assumeTrue*/ child === (node).whenTrue); - } - break; - case SyntaxKind.BinaryExpression: - // In the right operand of an && or ||, narrow based on left operand - if (child === (node).right) { - if ((node).operatorToken.kind === SyntaxKind.AmpersandAmpersandToken) { - narrowedType = narrowType(type, (node).left, /*assumeTrue*/ true); + if (node && symbol.flags & SymbolFlags.Variable) { + if (isTypeAny(type) || type.flags & (TypeFlags.ObjectType | TypeFlags.Union | TypeFlags.TypeParameter)) { + loop: while (node.parent) { + let child = node; + node = node.parent; + let narrowedType = type; + switch (node.kind) { + case SyntaxKind.IfStatement: + // In a branch of an if statement, narrow based on controlling expression + if (child !== (node).expression) { + narrowedType = narrowType(type, (node).expression, /*assumeTrue*/ child === (node).thenStatement); } - else if ((node).operatorToken.kind === SyntaxKind.BarBarToken) { - narrowedType = narrowType(type, (node).left, /*assumeTrue*/ false); + break; + case SyntaxKind.ConditionalExpression: + // In a branch of a conditional expression, narrow based on controlling condition + if (child !== (node).condition) { + narrowedType = narrowType(type, (node).condition, /*assumeTrue*/ child === (node).whenTrue); } - } - break; - case SyntaxKind.SourceFile: - case SyntaxKind.ModuleDeclaration: - case SyntaxKind.FunctionDeclaration: - case SyntaxKind.MethodDeclaration: - case SyntaxKind.MethodSignature: - case SyntaxKind.GetAccessor: - case SyntaxKind.SetAccessor: - case SyntaxKind.Constructor: - // Stop at the first containing function or module declaration - break loop; - } - // Use narrowed type if construct contains no assignments to variable - if (narrowedType !== type) { - if (isVariableAssignedWithin(symbol, node)) { - break; + break; + case SyntaxKind.BinaryExpression: + // In the right operand of an && or ||, narrow based on left operand + if (child === (node).right) { + if ((node).operatorToken.kind === SyntaxKind.AmpersandAmpersandToken) { + narrowedType = narrowType(type, (node).left, /*assumeTrue*/ true); + } + else if ((node).operatorToken.kind === SyntaxKind.BarBarToken) { + narrowedType = narrowType(type, (node).left, /*assumeTrue*/ false); + } + } + break; + case SyntaxKind.SourceFile: + case SyntaxKind.ModuleDeclaration: + case SyntaxKind.FunctionDeclaration: + case SyntaxKind.MethodDeclaration: + case SyntaxKind.MethodSignature: + case SyntaxKind.GetAccessor: + case SyntaxKind.SetAccessor: + case SyntaxKind.Constructor: + // Stop at the first containing function or module declaration + break loop; + } + // Use narrowed type if construct contains no assignments to variable + if (narrowedType !== type) { + if (isVariableAssignedWithin(symbol, node)) { + break; + } + type = narrowedType; } - type = narrowedType; } } } + return type; function narrowTypeByEquality(type: Type, expr: BinaryExpression, assumeTrue: boolean): Type { @@ -5410,7 +5730,7 @@ module ts { function narrowTypeByInstanceof(type: Type, expr: BinaryExpression, assumeTrue: boolean): Type { // Check that type is not any, assumed result is true, and we have variable symbol on the left - if (type.flags & TypeFlags.Any || !assumeTrue || expr.left.kind !== SyntaxKind.Identifier || getResolvedSymbol(expr.left) !== symbol) { + if (isTypeAny(type) || !assumeTrue || expr.left.kind !== SyntaxKind.Identifier || getResolvedSymbol(expr.left) !== symbol) { return type; } // Check that right operand is a function type with a prototype property @@ -5422,9 +5742,9 @@ module ts { let targetType: Type; let prototypeProperty = getPropertyOfType(rightType, "prototype"); if (prototypeProperty) { - // Target type is type of the protoype property + // Target type is type of the prototype property let prototypePropertyType = getTypeOfSymbol(prototypeProperty); - if (prototypePropertyType !== anyType) { + if (!isTypeAny(prototypePropertyType)) { targetType = prototypePropertyType; } } @@ -5438,30 +5758,57 @@ module ts { else if (rightType.flags & TypeFlags.Anonymous) { constructSignatures = getSignaturesOfType(rightType, SignatureKind.Construct); } - if (constructSignatures && constructSignatures.length) { targetType = getUnionType(map(constructSignatures, signature => getReturnTypeOfSignature(getErasedSignature(signature)))); } } if (targetType) { - // Narrow to the target type if it's a subtype of the current type - if (isTypeSubtypeOf(targetType, type)) { - return targetType; - } - // If the current type is a union type, remove all constituents that aren't subtypes of the target. - if (type.flags & TypeFlags.Union) { - return getUnionType(filter((type).types, t => isTypeSubtypeOf(t, targetType))); - } + return getNarrowedType(type, targetType); } return type; } + function getNarrowedType(originalType: Type, narrowedTypeCandidate: Type) { + // Narrow to the target type if it's a subtype of the current type + if (isTypeSubtypeOf(narrowedTypeCandidate, originalType)) { + return narrowedTypeCandidate; + } + // If the current type is a union type, remove all constituents that aren't subtypes of the target. + if (originalType.flags & TypeFlags.Union) { + return getUnionType(filter((originalType).types, t => isTypeSubtypeOf(t, narrowedTypeCandidate))); + } + return originalType; + } + + function narrowTypeByTypePredicate(type: Type, expr: CallExpression, assumeTrue: boolean): Type { + if (type.flags & TypeFlags.Any) { + return type; + } + let signature = getResolvedSignature(expr); + + if (signature.typePredicate && + expr.arguments[signature.typePredicate.parameterIndex] && + getSymbolAtLocation(expr.arguments[signature.typePredicate.parameterIndex]) === symbol) { + + if (!assumeTrue) { + if (type.flags & TypeFlags.Union) { + return getUnionType(filter((type).types, t => !isTypeSubtypeOf(t, signature.typePredicate.type))); + } + return type; + } + return getNarrowedType(type, signature.typePredicate.type); + } + 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: Type, expr: Expression, assumeTrue: boolean): Type { switch (expr.kind) { + case SyntaxKind.CallExpression: + return narrowTypeByTypePredicate(type, expr, assumeTrue); case SyntaxKind.ParenthesizedExpression: return narrowType(type, (expr).expression, assumeTrue); case SyntaxKind.BinaryExpression: @@ -5640,16 +5987,14 @@ module ts { function checkSuperExpression(node: Node): Type { let isCallExpression = node.parent.kind === SyntaxKind.CallExpression && (node.parent).expression === node; - let enclosingClass = getAncestor(node, SyntaxKind.ClassDeclaration); - let baseClass: Type; - if (enclosingClass && getClassExtendsHeritageClauseElement(enclosingClass)) { - let classType = getDeclaredTypeOfSymbol(getSymbolOfNode(enclosingClass)); - let baseTypes = getBaseTypes(classType); - baseClass = baseTypes.length && baseTypes[0]; - } + let classDeclaration = getAncestor(node, SyntaxKind.ClassDeclaration); + let classType = classDeclaration && getDeclaredTypeOfSymbol(getSymbolOfNode(classDeclaration)); + let baseClassType = classType && getBaseTypes(classType)[0]; - if (!baseClass) { - error(node, Diagnostics.super_can_only_be_referenced_in_a_derived_class); + if (!baseClassType) { + if (!classDeclaration || !getClassExtendsHeritageClauseElement(classDeclaration)) { + error(node, Diagnostics.super_can_only_be_referenced_in_a_derived_class); + } return unknownType; } @@ -5703,11 +6048,11 @@ module ts { if ((container.flags & NodeFlags.Static) || isCallExpression) { getNodeLinks(node).flags |= NodeCheckFlags.SuperStatic; - returnType = getTypeOfSymbol(baseClass.symbol); + returnType = getBaseConstructorTypeOfClass(classType); } else { getNodeLinks(node).flags |= NodeCheckFlags.SuperInstance; - returnType = baseClass; + returnType = baseClassType; } if (container.kind === SyntaxKind.Constructor && isInConstructorArgumentInitializer(node, container)) { @@ -5748,7 +6093,7 @@ module ts { let contextualSignature = getContextualSignature(func); if (contextualSignature) { - let funcHasRestParameters = hasRestParameters(func); + let funcHasRestParameters = hasRestParameter(func); let len = func.parameters.length - (funcHasRestParameters ? 1 : 0); let indexOfParameter = indexOf(func.parameters, parameter); if (indexOfParameter < len) { @@ -5791,20 +6136,44 @@ module ts { } function getContextualTypeForReturnExpression(node: Expression): Type { + let func = getContainingFunction(node); + if (func && !func.asteriskToken) { + return getContextualReturnType(func); + } + + return undefined; + } + + function getContextualTypeForYieldOperand(node: YieldExpression): Type { let func = getContainingFunction(node); if (func) { - // 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 (func.type || func.kind === SyntaxKind.Constructor || func.kind === SyntaxKind.GetAccessor && getSetAccessorTypeAnnotationNode(getDeclarationOfKind(func.symbol, SyntaxKind.SetAccessor))) { - return getReturnTypeOfSignature(getSignatureFromDeclaration(func)); - } - // 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 - let signature = getContextualSignatureForFunctionLikeDeclaration(func); - if (signature) { - return getReturnTypeOfSignature(signature); + let contextualReturnType = getContextualReturnType(func); + if (contextualReturnType) { + return node.asteriskToken + ? contextualReturnType + : getElementTypeOfIterableIterator(contextualReturnType); } } + + return undefined; + } + + function getContextualReturnType(functionDecl: FunctionLikeDeclaration): Type { + // 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 === SyntaxKind.Constructor || + functionDecl.kind === SyntaxKind.GetAccessor && getSetAccessorTypeAnnotationNode(getDeclarationOfKind(functionDecl.symbol, SyntaxKind.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 + let signature = getContextualSignatureForFunctionLikeDeclaration(functionDecl); + if (signature) { + return getReturnTypeOfSignature(signature); + } + return undefined; } @@ -5942,7 +6311,7 @@ module ts { let index = indexOf(arrayLiteral.elements, node); return getTypeOfPropertyOfContextualType(type, "" + index) || getIndexTypeOfContextualType(type, IndexKind.Number) - || (languageVersion >= ScriptTarget.ES6 ? checkIteratedType(type, /*expressionForError*/ undefined) : undefined); + || (languageVersion >= ScriptTarget.ES6 ? getElementTypeOfIterable(type, /*errorNode*/ undefined) : undefined); } return undefined; } @@ -5974,6 +6343,8 @@ module ts { case SyntaxKind.ArrowFunction: case SyntaxKind.ReturnStatement: return getContextualTypeForReturnExpression(node); + case SyntaxKind.YieldExpression: + return getContextualTypeForYieldOperand(parent); case SyntaxKind.CallExpression: case SyntaxKind.NewExpression: return getContextualTypeForArgument(parent, node); @@ -6013,8 +6384,10 @@ module ts { } function getContextualSignatureForFunctionLikeDeclaration(node: FunctionLikeDeclaration): Signature { - // Only function expressions and arrow functions are contextually typed. - return isFunctionExpressionOrArrowFunction(node) ? getContextualSignature(node) : undefined; + // Only function expressions, arrow functions, and object literal methods are contextually typed. + return isFunctionExpressionOrArrowFunction(node) || isObjectLiteralMethod(node) + ? getContextualSignature(node) + : undefined; } // Return the contextual signature for a given expression node. A contextual type provides a @@ -6129,7 +6502,7 @@ module ts { // if there is no index type / iterated type. let restArrayType = checkExpression((e).expression, contextualMapper); let restElementType = getIndexTypeOfType(restArrayType, IndexKind.Number) || - (languageVersion >= ScriptTarget.ES6 ? checkIteratedType(restArrayType, /*expressionForError*/ undefined) : undefined); + (languageVersion >= ScriptTarget.ES6 ? getElementTypeOfIterable(restArrayType, /*errorNode*/ undefined) : undefined); if (restElementType) { elementTypes.push(restElementType); @@ -6157,7 +6530,11 @@ module ts { function isNumericComputedName(name: ComputedPropertyName): boolean { // It seems odd to consider an expression of type Any to result in a numeric name, // but this behavior is consistent with checkIndexedAccess - return allConstituentTypesHaveKind(checkComputedPropertyName(name), TypeFlags.Any | TypeFlags.NumberLike); + return isTypeAnyOrAllConstituentTypesHaveKind(checkComputedPropertyName(name), TypeFlags.NumberLike); + } + + function isTypeAnyOrAllConstituentTypesHaveKind(type: Type, kind: TypeFlags): boolean { + return isTypeAny(type) || allConstituentTypesHaveKind(type, kind); } function isNumericLiteralName(name: string) { @@ -6192,7 +6569,7 @@ module ts { // 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 (!allConstituentTypesHaveKind(links.resolvedType, TypeFlags.Any | TypeFlags.NumberLike | TypeFlags.StringLike | TypeFlags.ESSymbol)) { + if (!isTypeAnyOrAllConstituentTypesHaveKind(links.resolvedType, TypeFlags.NumberLike | TypeFlags.StringLike | TypeFlags.ESSymbol)) { error(node, Diagnostics.A_computed_property_name_must_be_of_type_string_number_symbol_or_any); } else { @@ -6343,40 +6720,40 @@ module ts { } function checkPropertyAccessExpressionOrQualifiedName(node: PropertyAccessExpression | QualifiedName, left: Expression | QualifiedName, right: Identifier) { - let type = checkExpressionOrQualifiedName(left); - if (type === unknownType) return type; - if (type !== anyType) { - let apparentType = getApparentType(getWidenedType(type)); - if (apparentType === unknownType) { - // handle cases when type is Type parameter with invalid constraint - return unknownType; - } - let prop = getPropertyOfType(apparentType, right.text); - if (!prop) { - if (right.text) { - error(right, Diagnostics.Property_0_does_not_exist_on_type_1, declarationNameToString(right), typeToString(type)); - } - return unknownType; - } - getNodeLinks(node).resolvedSymbol = prop; - if (prop.parent && prop.parent.flags & SymbolFlags.Class) { - // 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 (left.kind === SyntaxKind.SuperKeyword && getDeclarationKindFromSymbol(prop) !== SyntaxKind.MethodDeclaration) { - error(right, Diagnostics.Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword); - } - else { - checkClassPropertyAccess(node, left, type, prop); - } - } - return getTypeOfSymbol(prop); + let type = checkExpression(left); + if (isTypeAny(type)) { + return type; } - return anyType; + + let apparentType = getApparentType(getWidenedType(type)); + if (apparentType === unknownType) { + // handle cases when type is Type parameter with invalid constraint + return unknownType; + } + let prop = getPropertyOfType(apparentType, right.text); + if (!prop) { + if (right.text) { + error(right, Diagnostics.Property_0_does_not_exist_on_type_1, declarationNameToString(right), typeToString(type)); + } + return unknownType; + } + getNodeLinks(node).resolvedSymbol = prop; + if (prop.parent && prop.parent.flags & SymbolFlags.Class) { + // 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 (left.kind === SyntaxKind.SuperKeyword && getDeclarationKindFromSymbol(prop) !== SyntaxKind.MethodDeclaration) { + error(right, Diagnostics.Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword); + } + else { + checkClassPropertyAccess(node, left, type, prop); + } + } + return getTypeOfSymbol(prop); } function isValidPropertyAccess(node: PropertyAccessExpression | QualifiedName, propertyName: string): boolean { @@ -6384,8 +6761,8 @@ module ts { ? (node).expression : (node).left; - let type = checkExpressionOrQualifiedName(left); - if (type !== unknownType && type !== anyType) { + let type = checkExpression(left); + if (type !== unknownType && !isTypeAny(type)) { let prop = getPropertyOfType(getWidenedType(type), propertyName); if (prop && prop.parent && prop.parent.flags & SymbolFlags.Class) { if (left.kind === SyntaxKind.SuperKeyword && getDeclarationKindFromSymbol(prop) !== SyntaxKind.MethodDeclaration) { @@ -6458,10 +6835,10 @@ module ts { } // Check for compatible indexer types. - if (allConstituentTypesHaveKind(indexType, TypeFlags.Any | TypeFlags.StringLike | TypeFlags.NumberLike | TypeFlags.ESSymbol)) { + if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, TypeFlags.StringLike | TypeFlags.NumberLike | TypeFlags.ESSymbol)) { // Try to use a number indexer. - if (allConstituentTypesHaveKind(indexType, TypeFlags.Any | TypeFlags.NumberLike)) { + if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, TypeFlags.NumberLike)) { let numberIndexType = getIndexTypeOfType(objectType, IndexKind.Number); if (numberIndexType) { return numberIndexType; @@ -6475,7 +6852,7 @@ module ts { } // Fall back to any. - if (compilerOptions.noImplicitAny && !compilerOptions.suppressImplicitAnyIndexErrors && objectType !== anyType) { + if (compilerOptions.noImplicitAny && !compilerOptions.suppressImplicitAnyIndexErrors && !isTypeAny(objectType)) { error(node, Diagnostics.Index_signature_of_object_type_implicitly_has_an_any_type); } @@ -6900,27 +7277,6 @@ module ts { return args; } - /** - * In a 'super' call, type arguments are not provided within the CallExpression node itself. - * Instead, they must be fetched from the class declaration's base type node. - * - * If 'node' is a 'super' call (e.g. super(...), new super(...)), then we attempt to fetch - * the type arguments off the containing class's first heritage clause (if one exists). Note that if - * type arguments are supplied on the 'super' call, they are ignored (though this is syntactically incorrect). - * - * In all other cases, the call's explicit type arguments are returned. - */ - function getEffectiveTypeArguments(callExpression: CallExpression): TypeNode[] { - if (callExpression.expression.kind === SyntaxKind.SuperKeyword) { - let containingClass = getAncestor(callExpression, SyntaxKind.ClassDeclaration); - let baseClassTypeNode = containingClass && getClassExtendsHeritageClauseElement(containingClass); - return baseClassTypeNode && baseClassTypeNode.typeArguments; - } - else { - // Ordinary case - simple function invocation. - return callExpression.typeArguments; - } - } /** * Returns the effective argument count for a node that works like a function invocation. @@ -7199,7 +7555,7 @@ module ts { let typeArguments: TypeNode[]; if (!isTaggedTemplate && !isDecorator) { - typeArguments = getEffectiveTypeArguments(node); + typeArguments = (node).typeArguments; // We already perform checking on the type arguments on the class declaration itself. if ((node).expression.kind !== SyntaxKind.SuperKeyword) { @@ -7308,7 +7664,7 @@ module ts { checkApplicableSignature(node, args, candidateForArgumentError, assignableRelation, /*excludeArgument*/ undefined, /*reportErrors*/ true); } else if (candidateForTypeArgumentError) { - if (!isTaggedTemplate && !isDecorator && (node).typeArguments) { + if (!isTaggedTemplate && !isDecorator && typeArguments) { checkTypeArguments(candidateForTypeArgumentError, (node).typeArguments, [], /*reportErrors*/ true, headMessage) } else { @@ -7428,7 +7784,11 @@ module ts { if (node.expression.kind === SyntaxKind.SuperKeyword) { let superType = checkSuperExpression(node.expression); if (superType !== unknownType) { - return resolveCall(node, getSignaturesOfType(superType, SignatureKind.Construct), candidatesOutArray); + // 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. + let baseTypeNode = getClassExtendsHeritageClauseElement(getAncestor(node, SyntaxKind.ClassDeclaration)); + let baseConstructors = getInstantiatedConstructorsForTypeArguments(superType, baseTypeNode.typeArguments); + return resolveCall(node, baseConstructors, candidatesOutArray); } return resolveUntypedCall(node); } @@ -7455,8 +7815,10 @@ module ts { // types are provided for the argument expressions, and the result is always of type Any. // We exclude union types because we may have a union of function types that happen to have // no common signatures. - if (funcType === anyType || (!callSignatures.length && !constructSignatures.length && !(funcType.flags & TypeFlags.Union) && isTypeAssignableTo(funcType, globalFunctionType))) { - if (node.typeArguments) { + if (isTypeAny(funcType) || (!callSignatures.length && !constructSignatures.length && !(funcType.flags & TypeFlags.Union) && isTypeAssignableTo(funcType, globalFunctionType))) { + // The unknownType indicates that an error already occured (and was reported). No + // need to report another error in this case. + if (funcType !== unknownType && node.typeArguments) { error(node, Diagnostics.Untyped_function_calls_may_not_accept_type_arguments); } return resolveUntypedCall(node); @@ -7485,15 +7847,6 @@ module ts { } let expressionType = checkExpression(node.expression); - // TS 1.0 spec: 4.11 - // If ConstructExpr is of type Any, Args can be any argument - // list and the result of the operation is of type Any. - if (expressionType === anyType) { - if (node.typeArguments) { - error(node, Diagnostics.Untyped_function_calls_may_not_accept_type_arguments); - } - return resolveUntypedCall(node); - } // If ConstructExpr'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 @@ -7506,6 +7859,16 @@ module ts { return resolveErrorCall(node); } + // TS 1.0 spec: 4.11 + // If ConstructExpr 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, 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 @@ -7543,7 +7906,7 @@ module ts { let callSignatures = getSignaturesOfType(apparentType, SignatureKind.Call); - if (tagType === anyType || (!callSignatures.length && !(tagType.flags & TypeFlags.Union) && isTypeAssignableTo(tagType, globalFunctionType))) { + if (isTypeAny(tagType) || (!callSignatures.length && !(tagType.flags & TypeFlags.Union) && isTypeAssignableTo(tagType, globalFunctionType))) { return resolveUntypedCall(node); } @@ -7705,17 +8068,42 @@ module ts { type = checkExpressionCached(func.body, contextualMapper); } else { - // Aggregate the types of expressions within all the return statements. - let types = checkAndAggregateReturnExpressionTypes(func.body, contextualMapper); - if (types.length === 0) { - return voidType; + let types: Type[]; + let funcIsGenerator = !!func.asteriskToken; + if (funcIsGenerator) { + types = checkAndAggregateYieldOperandTypes(func.body, contextualMapper); + if (types.length === 0) { + let iterableIteratorAny = createIterableIteratorType(anyType); + if (compilerOptions.noImplicitAny) { + error(func.asteriskToken, + Diagnostics.Generator_implicitly_has_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_type, typeToString(iterableIteratorAny)); + } + return iterableIteratorAny; + } } - // When return statements are contextually typed we allow the return type to be a union type. Otherwise we require the - // return expressions to have a best common supertype. + else { + types = checkAndAggregateReturnExpressionTypes(func.body, contextualMapper); + if (types.length === 0) { + return voidType; + } + } + + // When yield/return statements are contextually typed we allow the return type to be a union type. + // Otherwise we require the yield/return expressions to have a best common supertype. type = contextualSignature ? getUnionType(types) : getCommonSupertype(types); if (!type) { - error(func, Diagnostics.No_best_common_type_exists_among_return_expressions); - return unknownType; + if (funcIsGenerator) { + error(func, Diagnostics.No_best_common_type_exists_among_yield_expressions); + return createIterableIteratorType(unknownType); + } + else { + error(func, Diagnostics.No_best_common_type_exists_among_return_expressions); + return unknownType; + } + } + + if (funcIsGenerator) { + type = createIterableIteratorType(type); } } if (!contextualSignature) { @@ -7724,7 +8112,28 @@ module ts { return getWidenedType(type); } - /// Returns a set of types relating to every return expression relating to a function block. + function checkAndAggregateYieldOperandTypes(body: Block, contextualMapper?: TypeMapper): Type[] { + let aggregatedTypes: Type[] = []; + + forEachYieldExpression(body, yieldExpression => { + let expr = yieldExpression.expression; + if (expr) { + let type = checkExpressionCached(expr, contextualMapper); + + if (yieldExpression.asteriskToken) { + // A yield* expression effectively yields everything that its operand yields + type = checkElementTypeOfIterable(type, yieldExpression.expression); + } + + if (!contains(aggregatedTypes, type)) { + aggregatedTypes.push(type); + } + } + }); + + return aggregatedTypes; + } + function checkAndAggregateReturnExpressionTypes(body: Block, contextualMapper?: TypeMapper): Type[] { let aggregatedTypes: Type[] = []; @@ -7761,7 +8170,7 @@ module ts { } // Functions that return 'void' or 'any' don't need any return expressions. - if (returnType === voidType || returnType === anyType) { + if (returnType === voidType || isTypeAny(returnType)) { return; } @@ -7792,9 +8201,9 @@ module ts { Debug.assert(node.kind !== SyntaxKind.MethodDeclaration || isObjectLiteralMethod(node)); // Grammar checking - let hasGrammarError = checkGrammarDeclarationNameInStrictMode(node) || checkGrammarFunctionLikeDeclaration(node); + let hasGrammarError = checkGrammarFunctionLikeDeclaration(node); if (!hasGrammarError && node.kind === SyntaxKind.FunctionExpression) { - checkGrammarFunctionName(node.name) || checkGrammarForGenerator(node); + checkGrammarForGenerator(node); } // The identityMapper object is used to indicate that function expressions are wildcards @@ -7842,6 +8251,15 @@ module ts { } 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 === SyntaxKind.Block) { checkSourceElement(node.body); } @@ -7856,7 +8274,7 @@ module ts { } function checkArithmeticOperandType(operand: Node, type: Type, diagnostic: DiagnosticMessage): boolean { - if (!allConstituentTypesHaveKind(type, TypeFlags.Any | TypeFlags.NumberLike)) { + if (!isTypeAnyOrAllConstituentTypesHaveKind(type, TypeFlags.NumberLike)) { error(operand, diagnostic); return false; } @@ -7942,14 +8360,7 @@ module ts { } function checkDeleteExpression(node: DeleteExpression): Type { - // Grammar checking - if (node.parserContextFlags & ParserContextFlags.StrictMode && node.expression.kind === SyntaxKind.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 - grammarErrorOnNode(node.expression, Diagnostics.delete_cannot_be_called_on_an_identifier_in_strict_mode); - } - - let operandType = checkExpression(node.expression); + checkExpression(node.expression); return booleanType; } @@ -7964,14 +8375,6 @@ module ts { } function checkPrefixUnaryExpression(node: PrefixUnaryExpression): Type { - // 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 ((node.operator === SyntaxKind.PlusPlusToken || node.operator === SyntaxKind.MinusMinusToken)) { - checkGrammarEvalOrArgumentsInStrictMode(node, node.operand); - } - let operandType = checkExpression(node.operand); switch (node.operator) { case SyntaxKind.PlusToken: @@ -7998,12 +8401,6 @@ module ts { } function checkPostfixUnaryExpression(node: PostfixUnaryExpression): Type { - // 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. - checkGrammarEvalOrArgumentsInStrictMode(node, node.operand); - let operandType = checkExpression(node.operand); let ok = checkArithmeticOperandType(node.operand, operandType, Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type); if (ok) { @@ -8068,7 +8465,7 @@ module ts { error(node.left, 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 (!(rightType.flags & TypeFlags.Any || isTypeSubtypeOf(rightType, globalFunctionType))) { + if (!(isTypeAny(rightType) || isTypeSubtypeOf(rightType, globalFunctionType))) { error(node.right, 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; @@ -8079,10 +8476,10 @@ module ts { // The in operator requires the left operand to be of type Any, the String primitive type, or the Number primitive type, // and the right operand to be of type Any, an object type, or a type parameter type. // The result is always of the Boolean primitive type. - if (!allConstituentTypesHaveKind(leftType, TypeFlags.Any | TypeFlags.StringLike | TypeFlags.NumberLike | TypeFlags.ESSymbol)) { + if (!isTypeAnyOrAllConstituentTypesHaveKind(leftType, TypeFlags.StringLike | TypeFlags.NumberLike | TypeFlags.ESSymbol)) { error(node.left, Diagnostics.The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol); } - if (!allConstituentTypesHaveKind(rightType, TypeFlags.Any | TypeFlags.ObjectType | TypeFlags.TypeParameter)) { + if (!isTypeAnyOrAllConstituentTypesHaveKind(rightType, TypeFlags.ObjectType | TypeFlags.TypeParameter)) { error(node.right, Diagnostics.The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter); } return booleanType; @@ -8094,10 +8491,11 @@ module ts { if (p.kind === SyntaxKind.PropertyAssignment || p.kind === SyntaxKind.ShorthandPropertyAssignment) { // TODO(andersh): Computed property support let name = (p).name; - let type = sourceType.flags & TypeFlags.Any ? sourceType : - getTypeOfPropertyOfType(sourceType, name.text) || - isNumericLiteralName(name.text) && getIndexTypeOfType(sourceType, IndexKind.Number) || - getIndexTypeOfType(sourceType, IndexKind.String); + let type = isTypeAny(sourceType) + ? sourceType + : getTypeOfPropertyOfType(sourceType, name.text) || + isNumericLiteralName(name.text) && getIndexTypeOfType(sourceType, IndexKind.Number) || + getIndexTypeOfType(sourceType, IndexKind.String); if (type) { checkDestructuringAssignment((p).initializer || name, type); } @@ -8123,8 +8521,9 @@ module ts { if (e.kind !== SyntaxKind.OmittedExpression) { if (e.kind !== SyntaxKind.SpreadElementExpression) { let propName = "" + i; - let type = sourceType.flags & TypeFlags.Any ? sourceType : - isTupleLikeType(sourceType) + let type = isTypeAny(sourceType) + ? sourceType + : isTupleLikeType(sourceType) ? getTypeOfPropertyOfType(sourceType, propName) : elementType; if (type) { @@ -8181,13 +8580,6 @@ module ts { } function checkBinaryExpression(node: BinaryExpression, contextualMapper?: TypeMapper) { - // Grammar checking - if (isLeftHandSideExpression(node.left) && 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) - checkGrammarEvalOrArgumentsInStrictMode(node, node.left); - } - let operator = node.operatorToken.kind; if (operator === SyntaxKind.EqualsToken && (node.left.kind === SyntaxKind.ObjectLiteralExpression || node.left.kind === SyntaxKind.ArrayLiteralExpression)) { return checkDestructuringAssignment(node.left, checkExpression(node.right, contextualMapper), contextualMapper); @@ -8263,10 +8655,10 @@ module ts { // If one or both operands are of the String primitive type, the result is of the String primitive type. resultType = stringType; } - else if (leftType.flags & TypeFlags.Any || rightType.flags & TypeFlags.Any) { + 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 = anyType; + resultType = leftType === unknownType || rightType === unknownType ? unknownType : anyType; } // Symbols are not allowed at all in arithmetic expressions @@ -8367,14 +8759,58 @@ module ts { } } - function checkYieldExpression(node: YieldExpression): void { + function isYieldExpressionInClass(node: YieldExpression): boolean { + let current: Node = node + let parent = node.parent; + while (parent) { + if (isFunctionLike(parent) && current === (parent).body) { + return false; + } + else if (current.kind === SyntaxKind.ClassDeclaration || current.kind === SyntaxKind.ClassExpression) { + return true; + } + + current = parent; + parent = parent.parent; + } + + return false; + } + + function checkYieldExpression(node: YieldExpression): Type { // Grammar checking - if (!(node.parserContextFlags & ParserContextFlags.Yield)) { - grammarErrorOnFirstToken(node, Diagnostics.yield_expression_must_be_contained_within_a_generator_declaration); + if (!(node.parserContextFlags & ParserContextFlags.Yield) || isYieldExpressionInClass(node)) { + grammarErrorOnFirstToken(node, Diagnostics.A_yield_expression_is_only_allowed_in_a_generator_body); } - else { - grammarErrorOnFirstToken(node, Diagnostics.yield_expressions_are_not_currently_supported); + + if (node.expression) { + let func = 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. + if (func && func.asteriskToken) { + let expressionType = checkExpressionCached(node.expression, /*contextualMapper*/ undefined); + let expressionElementType: Type; + let nodeIsYieldStar = !!node.asteriskToken; + if (nodeIsYieldStar) { + expressionElementType = checkElementTypeOfIterable(expressionType, node.expression); + } + // 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) { + let signatureElementType = getElementTypeOfIterableIterator(getTypeFromTypeNode(func.type)) || anyType; + if (nodeIsYieldStar) { + checkTypeAssignableTo(expressionElementType, signatureElementType, node.expression, /*headMessage*/ undefined); + } + else { + checkTypeAssignableTo(expressionType, signatureElementType, node.expression, /*headMessage*/ undefined); + } + } + } } + + // Both yield and yield* expressions have type 'any' + return anyType; } function checkConditionalExpression(node: ConditionalExpression, contextualMapper?: TypeMapper): Type { @@ -8456,11 +8892,6 @@ module ts { return type; } - function checkExpression(node: Expression, contextualMapper?: TypeMapper): Type { - checkGrammarIdentifierInStrictMode(node); - return checkExpressionOrQualifiedName(node, contextualMapper); - } - // 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.12.2 in spec) and provides the type mapper to use in @@ -8468,9 +8899,9 @@ module ts { // object, it serves as an indicator that all contained function and arrow expressions should be considered to // have the wildcard function type; this form of type check is used during overload resolution to exclude // contextually typed function and arrow expressions in the initial phase. - function checkExpressionOrQualifiedName(node: Expression | QualifiedName, contextualMapper?: TypeMapper): Type { + function checkExpression(node: Expression | QualifiedName, contextualMapper?: TypeMapper): Type { let type: Type; - if (node.kind == SyntaxKind.QualifiedName) { + if (node.kind === SyntaxKind.QualifiedName) { type = checkQualifiedName(node); } else { @@ -8564,8 +8995,7 @@ module ts { case SyntaxKind.OmittedExpression: return undefinedType; case SyntaxKind.YieldExpression: - checkYieldExpression(node); - return unknownType; + return checkYieldExpression(node); } return unknownType; } @@ -8573,8 +9003,6 @@ module ts { // DECLARATION AND STATEMENT TYPE CHECKING function checkTypeParameter(node: TypeParameterDeclaration) { - checkGrammarDeclarationNameInStrictMode(node); - // Grammar Checking if (node.expression) { grammarErrorOnFirstToken(node.expression, Diagnostics.Type_expected); @@ -8593,11 +9021,9 @@ module ts { // 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). - // It is a SyntaxError if the identifier eval or arguments appears within a FormalParameterList of a - // strict mode FunctionLikeDeclaration or FunctionExpression(13.1) // Grammar checking - checkGrammarDecorators(node) || checkGrammarModifiers(node) || checkGrammarEvalOrArgumentsInStrictMode(node, node.name); + checkGrammarDecorators(node) || checkGrammarModifiers(node); checkVariableLikeDeclaration(node); let func = getContainingFunction(node); @@ -8618,6 +9044,44 @@ module ts { } } + function isSyntacticallyValidGenerator(node: SignatureDeclaration): boolean { + if (!(node).asteriskToken || !(node).body) { + return false; + } + + return node.kind === SyntaxKind.MethodDeclaration || + node.kind === SyntaxKind.FunctionDeclaration || + node.kind === SyntaxKind.FunctionExpression; + } + + function getTypePredicateParameterIndex(parameterList: NodeArray, parameter: Identifier): number { + if (parameterList) { + for (let i = 0; i < parameterList.length; i++) { + let param = parameterList[i]; + if (param.name.kind === SyntaxKind.Identifier && + (param.name).text === parameter.text) { + + return i; + } + } + } + return -1; + } + + function isInLegalTypePredicatePosition(node: Node): boolean { + switch (node.parent.kind) { + case SyntaxKind.ArrowFunction: + case SyntaxKind.CallSignature: + case SyntaxKind.FunctionDeclaration: + case SyntaxKind.FunctionExpression: + case SyntaxKind.FunctionType: + case SyntaxKind.MethodDeclaration: + case SyntaxKind.MethodSignature: + return node === (node.parent).type; + } + return false; + } + function checkSignatureDeclaration(node: SignatureDeclaration) { // Grammar checking if (node.kind === SyntaxKind.IndexSignature) { @@ -8635,7 +9099,65 @@ module ts { forEach(node.parameters, checkParameter); if (node.type) { - checkSourceElement(node.type); + if (node.type.kind === SyntaxKind.TypePredicate) { + let typePredicate = getSignatureFromDeclaration(node).typePredicate; + let typePredicateNode = node.type; + if (isInLegalTypePredicatePosition(typePredicateNode)) { + if (typePredicate.parameterIndex >= 0) { + if (node.parameters[typePredicate.parameterIndex].dotDotDotToken) { + error(typePredicateNode.parameterName, + Diagnostics.A_type_predicate_cannot_reference_a_rest_parameter); + } + else { + checkTypeAssignableTo(typePredicate.type, + getTypeAtLocation(node.parameters[typePredicate.parameterIndex]), + typePredicateNode.type); + } + } + else if (typePredicateNode.parameterName) { + let hasReportedError = false; + for (var param of node.parameters) { + if (hasReportedError) { + break; + } + if (param.name.kind === SyntaxKind.ObjectBindingPattern || + param.name.kind === SyntaxKind.ArrayBindingPattern) { + + (function checkBindingPattern(pattern: BindingPattern) { + for (let element of pattern.elements) { + if (element.name.kind === SyntaxKind.Identifier && + (element.name).text === typePredicate.parameterName) { + + error(typePredicateNode.parameterName, + Diagnostics.A_type_predicate_cannot_reference_element_0_in_a_binding_pattern, + typePredicate.parameterName); + hasReportedError = true; + break; + } + else if (element.name.kind === SyntaxKind.ArrayBindingPattern || + element.name.kind === SyntaxKind.ObjectBindingPattern) { + + checkBindingPattern(element.name); + } + } + })(param.name); + } + } + if (!hasReportedError) { + error(typePredicateNode.parameterName, + Diagnostics.Cannot_find_parameter_0, + typePredicate.parameterName); + } + } + } + else { + error(typePredicateNode, + Diagnostics.A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods); + } + } + else { + checkSourceElement(node.type); + } } if (produceDiagnostics) { @@ -8650,6 +9172,27 @@ module ts { break; } } + + if (node.type) { + if (languageVersion >= ScriptTarget.ES6 && isSyntacticallyValidGenerator(node)) { + let returnType = getTypeFromTypeNode(node.type); + if (returnType === voidType) { + error(node.type, Diagnostics.A_generator_cannot_have_a_void_type_annotation); + } + else { + let generatorElementType = getElementTypeOfIterableIterator(returnType) || anyType; + let iterableIteratorInstantiation = createIterableIteratorType(generatorElementType); + + // 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); + } + } + } } checkSpecializedSignatureDeclaration(node); @@ -8842,32 +9385,28 @@ module ts { checkDecorators(node); } - function checkTypeReferenceNode(node: TypeReferenceNode) { - checkGrammarTypeReferenceInStrictMode(node.typeName); - return checkTypeReferenceOrExpressionWithTypeArguments(node); + function checkTypeArgumentConstraints(typeParameters: TypeParameter[], typeArguments: TypeNode[]): boolean { + let result = true; + for (let i = 0; i < typeParameters.length; i++) { + let constraint = getConstraintOfTypeParameter(typeParameters[i]); + if (constraint) { + let typeArgument = typeArguments[i]; + result = result && checkTypeAssignableTo(getTypeFromTypeNode(typeArgument), constraint, typeArgument, Diagnostics.Type_0_does_not_satisfy_the_constraint_1); + } + } + return result; } - function checkExpressionWithTypeArguments(node: ExpressionWithTypeArguments) { - checkGrammarExpressionWithTypeArgumentsInStrictMode(node.expression); - - return checkTypeReferenceOrExpressionWithTypeArguments(node); - } - - function checkTypeReferenceOrExpressionWithTypeArguments(node: TypeReferenceNode | ExpressionWithTypeArguments) { - // Grammar checking + function checkTypeReferenceNode(node: TypeReferenceNode | ExpressionWithTypeArguments) { checkGrammarTypeArguments(node, node.typeArguments); - - let type = getTypeFromTypeReferenceOrExpressionWithTypeArguments(node); + let type = getTypeFromTypeReference(node); if (type !== unknownType && node.typeArguments) { // Do type argument local checks only if referenced type is successfully resolved - let len = node.typeArguments.length; - for (let i = 0; i < len; i++) { - checkSourceElement(node.typeArguments[i]); - let constraint = getConstraintOfTypeParameter((type).target.typeParameters[i]); - if (produceDiagnostics && constraint) { - let typeArgument = (type).typeArguments[i]; - checkTypeAssignableTo(typeArgument, constraint, node, Diagnostics.Type_0_does_not_satisfy_the_constraint_1); - } + forEach(node.typeArguments, checkSourceElement); + if (produceDiagnostics) { + let symbol = getNodeLinks(node).resolvedSymbol; + let typeParameters = symbol.flags & SymbolFlags.TypeAlias ? getSymbolLinks(symbol).typeParameters : (type).target.localTypeParameters; + checkTypeArgumentConstraints(typeParameters, node.typeArguments); } } } @@ -9301,12 +9840,12 @@ module ts { // serialize the type metadata. if (node && node.kind === SyntaxKind.TypeReference) { let type = getTypeFromTypeNode(node); - let shouldCheckIfUnknownType = type === unknownType && compilerOptions.separateCompilation; + let shouldCheckIfUnknownType = type === unknownType && compilerOptions.isolatedModules; if (!type || (!shouldCheckIfUnknownType && type.flags & (TypeFlags.Intrinsic | TypeFlags.NumberLike | TypeFlags.StringLike))) { return; } if (shouldCheckIfUnknownType || type.symbol.valueDeclaration) { - checkExpressionOrQualifiedName((node).typeName); + checkExpression((node).typeName); } } } @@ -9354,6 +9893,10 @@ module ts { if (!nodeCanBeDecorated(node)) { return; } + + if (!compilerOptions.experimentalDecorators) { + error(node, Diagnostics.Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Specify_experimentalDecorators_to_remove_this_warning); + } if (compilerOptions.emitDecoratorMetadata) { // we only need to perform these checks if we are emitting serialized type metadata for the target of a decorator. @@ -9388,10 +9931,7 @@ module ts { function checkFunctionDeclaration(node: FunctionDeclaration): void { if (produceDiagnostics) { - checkFunctionLikeDeclaration(node) || - checkGrammarDisallowedModifiersInBlockOrObjectLiteralExpression(node) || - checkGrammarFunctionName(node.name) || - checkGrammarForGenerator(node); + checkFunctionLikeDeclaration(node) || checkGrammarForGenerator(node); checkCollisionWithCapturedSuperVariable(node, node.name); checkCollisionWithCapturedThisVariable(node, node.name); @@ -9400,7 +9940,6 @@ module ts { } function checkFunctionLikeDeclaration(node: FunctionLikeDeclaration): void { - checkGrammarDeclarationNameInStrictMode(node); checkDecorators(node); checkSignatureDeclaration(node); @@ -9440,10 +9979,19 @@ module ts { checkIfNonVoidFunctionHasReturnExpressionsOrSingleThrowStatment(node, getTypeFromTypeNode(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 (compilerOptions.noImplicitAny && nodeIsMissing(node.body) && !node.type && !isPrivateWithinAmbient(node)) { - reportImplicitAnyError(node, anyType); + 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 (compilerOptions.noImplicitAny && nodeIsMissing(node.body) && !isPrivateWithinAmbient(node)) { + reportImplicitAnyError(node, anyType); + } + + if (node.asteriskToken && 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)); + } } } @@ -9461,7 +10009,7 @@ module ts { function checkCollisionWithArgumentsInGeneratedCode(node: SignatureDeclaration) { // no rest parameters \ declaration context \ overload - no codegen impact - if (!hasRestParameters(node) || isInAmbientContext(node) || nodeIsMissing((node).body)) { + if (!hasRestParameter(node) || isInAmbientContext(node) || nodeIsMissing((node).body)) { return; } @@ -9677,7 +10225,6 @@ module ts { // Check variable, parameter, or property declaration function checkVariableLikeDeclaration(node: VariableLikeDeclaration) { - checkGrammarDeclarationNameInStrictMode(node); checkDecorators(node); checkSourceElement(node.type); // For a computed property, just check the initializer and exit @@ -9751,7 +10298,7 @@ module ts { function checkVariableStatement(node: VariableStatement) { // Grammar checking - checkGrammarDecorators(node) || checkGrammarDisallowedModifiersInBlockOrObjectLiteralExpression(node) || checkGrammarModifiers(node) || checkGrammarVariableDeclarationList(node.declarationList) || checkGrammarForDisallowedLetOrConstStatement(node); + checkGrammarDecorators(node) || checkGrammarModifiers(node) || checkGrammarVariableDeclarationList(node.declarationList) || checkGrammarForDisallowedLetOrConstStatement(node); forEach(node.declarationList.declarations, checkSourceElement); } @@ -9809,7 +10356,7 @@ module ts { function checkForStatement(node: ForStatement) { // Grammar checking if (!checkGrammarStatementInAmbientContext(node)) { - if (node.initializer && node.initializer.kind == SyntaxKind.VariableDeclarationList) { + if (node.initializer && node.initializer.kind === SyntaxKind.VariableDeclarationList) { checkGrammarVariableDeclarationList(node.initializer); } } @@ -9858,7 +10405,7 @@ module ts { // 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 - // getIteratedType. + // getElementTypeOfIterable. if (iteratedType) { checkTypeAssignableTo(iteratedType, leftType, varExpr, /*headMessage*/ undefined); } @@ -9895,7 +10442,7 @@ module ts { if (varExpr.kind === SyntaxKind.ArrayLiteralExpression || varExpr.kind === SyntaxKind.ObjectLiteralExpression) { error(varExpr, Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern); } - else if (!allConstituentTypesHaveKind(leftType, TypeFlags.Any | TypeFlags.StringLike)) { + else if (!isTypeAnyOrAllConstituentTypesHaveKind(leftType, TypeFlags.StringLike)) { error(varExpr, Diagnostics.The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any); } else { @@ -9907,7 +10454,7 @@ module ts { let rightType = checkExpression(node.expression); // 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 (!allConstituentTypesHaveKind(rightType, TypeFlags.Any | TypeFlags.ObjectType | TypeFlags.TypeParameter)) { + if (!isTypeAnyOrAllConstituentTypesHaveKind(rightType, TypeFlags.ObjectType | TypeFlags.TypeParameter)) { error(node.expression, Diagnostics.The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter); } @@ -9929,12 +10476,12 @@ module ts { } function checkIteratedTypeOrElementType(inputType: Type, errorNode: Node, allowStringInput: boolean): Type { - if (inputType.flags & TypeFlags.Any) { + if (isTypeAny(inputType)) { return inputType; } if (languageVersion >= ScriptTarget.ES6) { - return checkIteratedType(inputType, errorNode) || anyType; + return checkElementTypeOfIterable(inputType, errorNode); } if (allowStringInput) { @@ -9955,100 +10502,143 @@ module ts { /** * When errorNode is undefined, it means we should not report any errors. */ - function checkIteratedType(iterable: Type, errorNode: Node): Type { - Debug.assert(languageVersion >= ScriptTarget.ES6); - let iteratedType = getIteratedType(iterable, errorNode); + function checkElementTypeOfIterable(iterable: Type, errorNode: Node): Type { + let elementType = getElementTypeOfIterable(iterable, errorNode); // Now even though we have extracted the iteratedType, we will have to validate that the type // passed in is actually an Iterable. - if (errorNode && iteratedType) { - checkTypeAssignableTo(iterable, createIterableType(iteratedType), errorNode); + if (errorNode && elementType) { + checkTypeAssignableTo(iterable, createIterableType(elementType), errorNode); } - return iteratedType; - - function getIteratedType(iterable: Type, errorNode: Node) { - // 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]: { // iteratorFunction - // (): { // iterator - // next: { // iteratorNextFunction - // (): { // iteratorNextResult - // value: T // iteratorNextValue - // } - // } - // } - // } - // } - // - // 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'. - - if (allConstituentTypesHaveKind(iterable, TypeFlags.Any)) { - return undefined; - } + return elementType || anyType; + } + + /** + * 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]: { // iteratorFunction + * (): Iterator + * } + * } + * + * 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'. + */ + function getElementTypeOfIterable(type: Type, errorNode: Node): Type { + if (isTypeAny(type)) { + return undefined; + } + let typeAsIterable = type; + if (!typeAsIterable.iterableElementType) { // As an optimization, if the type is instantiated directly using the globalIterableType (Iterable), // then just grab its type argument. - if ((iterable.flags & TypeFlags.Reference) && (iterable).target === globalIterableType) { - return (iterable).typeArguments[0]; + if ((type.flags & TypeFlags.Reference) && (type).target === globalIterableType) { + typeAsIterable.iterableElementType = (type).typeArguments[0]; } - - let iteratorFunction = getTypeOfPropertyOfType(iterable, getPropertyNameForKnownSymbolName("iterator")); - if (iteratorFunction && allConstituentTypesHaveKind(iteratorFunction, TypeFlags.Any)) { - return undefined; - } - - let iteratorFunctionSignatures = iteratorFunction ? getSignaturesOfType(iteratorFunction, SignatureKind.Call) : emptyArray; - if (iteratorFunctionSignatures.length === 0) { - if (errorNode) { - error(errorNode, Diagnostics.Type_must_have_a_Symbol_iterator_method_that_returns_an_iterator); + else { + let iteratorFunction = getTypeOfPropertyOfType(type, getPropertyNameForKnownSymbolName("iterator")); + if (isTypeAny(iteratorFunction)) { + return undefined; } - return undefined; - } - let iterator = getUnionType(map(iteratorFunctionSignatures, getReturnTypeOfSignature)); - if (allConstituentTypesHaveKind(iterator, TypeFlags.Any)) { - return undefined; - } - - let iteratorNextFunction = getTypeOfPropertyOfType(iterator, "next"); - if (iteratorNextFunction && allConstituentTypesHaveKind(iteratorNextFunction, TypeFlags.Any)) { - return undefined; - } - - let iteratorNextFunctionSignatures = iteratorNextFunction ? getSignaturesOfType(iteratorNextFunction, SignatureKind.Call) : emptyArray; - if (iteratorNextFunctionSignatures.length === 0) { - if (errorNode) { - error(errorNode, Diagnostics.An_iterator_must_have_a_next_method); + let iteratorFunctionSignatures = iteratorFunction ? getSignaturesOfType(iteratorFunction, SignatureKind.Call) : emptyArray; + if (iteratorFunctionSignatures.length === 0) { + if (errorNode) { + error(errorNode, Diagnostics.Type_must_have_a_Symbol_iterator_method_that_returns_an_iterator); + } + return undefined; } - return undefined; - } - let iteratorNextResult = getUnionType(map(iteratorNextFunctionSignatures, getReturnTypeOfSignature)); - if (allConstituentTypesHaveKind(iteratorNextResult, TypeFlags.Any)) { - return undefined; + typeAsIterable.iterableElementType = getElementTypeOfIterator(getUnionType(map(iteratorFunctionSignatures, getReturnTypeOfSignature)), errorNode); } - - let iteratorNextValue = getTypeOfPropertyOfType(iteratorNextResult, "value"); - if (!iteratorNextValue) { - if (errorNode) { - error(errorNode, Diagnostics.The_type_returned_by_the_next_method_of_an_iterator_must_have_a_value_property); - } - return undefined; - } - - return iteratorNextValue; } + + return typeAsIterable.iterableElementType; + } + + /** + * This function has very similar logic as getElementTypeOfIterable, except that it operates on + * Iterators instead of Iterables. Here is the structure: + * + * { // iterator + * next: { // iteratorNextFunction + * (): { // iteratorNextResult + * value: T // iteratorNextValue + * } + * } + * } + * + */ + function getElementTypeOfIterator(type: Type, errorNode: Node): Type { + if (isTypeAny(type)) { + return undefined; + } + + let typeAsIterator = type; + if (!typeAsIterator.iteratorElementType) { + // As an optimization, if the type is instantiated directly using the globalIteratorType (Iterator), + // then just grab its type argument. + if ((type.flags & TypeFlags.Reference) && (type).target === globalIteratorType) { + typeAsIterator.iteratorElementType = (type).typeArguments[0]; + } + else { + let iteratorNextFunction = getTypeOfPropertyOfType(type, "next"); + if (isTypeAny(iteratorNextFunction)) { + return undefined; + } + + let iteratorNextFunctionSignatures = iteratorNextFunction ? getSignaturesOfType(iteratorNextFunction, SignatureKind.Call) : emptyArray; + if (iteratorNextFunctionSignatures.length === 0) { + if (errorNode) { + error(errorNode, Diagnostics.An_iterator_must_have_a_next_method); + } + return undefined; + } + + let iteratorNextResult = getUnionType(map(iteratorNextFunctionSignatures, getReturnTypeOfSignature)); + if (isTypeAny(iteratorNextResult)) { + return undefined; + } + + let iteratorNextValue = getTypeOfPropertyOfType(iteratorNextResult, "value"); + if (!iteratorNextValue) { + if (errorNode) { + error(errorNode, Diagnostics.The_type_returned_by_the_next_method_of_an_iterator_must_have_a_value_property); + } + return undefined; + } + + typeAsIterator.iteratorElementType = iteratorNextValue; + } + } + + return typeAsIterator.iteratorElementType; + } + + function getElementTypeOfIterableIterator(type: Type): Type { + if (isTypeAny(type)) { + return undefined; + } + + // As an optimization, if the type is instantiated directly using the globalIterableIteratorType (IterableIterator), + // then just grab its type argument. + if ((type.flags & TypeFlags.Reference) && (type).target === globalIterableIteratorType) { + return (type).typeArguments[0]; + } + + return getElementTypeOfIterable(type, /*errorNode*/ undefined) || + getElementTypeOfIterator(type, /*errorNode*/ undefined); } /** @@ -10140,32 +10730,35 @@ module ts { if (node.expression) { let func = getContainingFunction(node); if (func) { - let returnType = getReturnTypeOfSignature(getSignatureFromDeclaration(func)); + let signature = getSignatureFromDeclaration(func); + let returnType = getReturnTypeOfSignature(signature); let exprType = checkExpressionCached(node.expression); + + if (func.asteriskToken) { + // 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 === SyntaxKind.SetAccessor) { error(node.expression, Diagnostics.Setters_cannot_return_a_value); } - else { - if (func.kind === SyntaxKind.Constructor) { - if (!isTypeAssignableTo(exprType, returnType)) { - error(node.expression, Diagnostics.Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class); - } - } - else if (func.type || isGetAccessorWithAnnotatatedSetAccessor(func)) { - checkTypeAssignableTo(exprType, returnType, node.expression, /*headMessage*/ undefined); + else if (func.kind === SyntaxKind.Constructor) { + if (!isTypeAssignableTo(exprType, returnType)) { + error(node.expression, Diagnostics.Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class); } } + else if (func.type || isGetAccessorWithAnnotatatedSetAccessor(func) || signature.typePredicate) { + checkTypeAssignableTo(exprType, returnType, node.expression, /*headMessage*/ undefined); + } } } } function checkWithStatement(node: WithStatement) { - // Grammar checking for withStatement - if (!checkGrammarStatementInAmbientContext(node)) { - if (node.parserContextFlags & ParserContextFlags.StrictMode) { - grammarErrorOnFirstToken(node, Diagnostics.with_statements_are_not_allowed_in_strict_mode); - } - } + checkGrammarStatementInAmbientContext(node); checkExpression(node.expression); error(node.expression, Diagnostics.All_symbols_within_a_with_block_will_be_resolved_to_any); @@ -10269,10 +10862,6 @@ module ts { grammarErrorOnNode(localSymbol.valueDeclaration, Diagnostics.Cannot_redeclare_identifier_0_in_catch_clause, identifierName); } } - - // 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 - checkGrammarEvalOrArgumentsInStrictMode(node, catchClause.variableDeclaration.name); } } @@ -10411,12 +11000,7 @@ module ts { } function checkClassDeclaration(node: ClassDeclaration) { - checkGrammarDeclarationNameInStrictMode(node); // Grammar checking - if (node.parent.kind !== SyntaxKind.ModuleBlock && node.parent.kind !== SyntaxKind.SourceFile) { - grammarErrorOnNode(node, Diagnostics.class_declarations_are_only_supported_directly_inside_a_module_or_as_a_top_level_declaration); - } - if (!node.name && !(node.flags & NodeFlags.Default)) { grammarErrorOnFirstToken(node, Diagnostics.A_class_declaration_without_the_default_modifier_must_have_a_name); } @@ -10433,45 +11017,46 @@ module ts { let symbol = getSymbolOfNode(node); let type = getDeclaredTypeOfSymbol(symbol); let staticType = getTypeOfSymbol(symbol); + let baseTypeNode = getClassExtendsHeritageClauseElement(node); if (baseTypeNode) { - if (!isSupportedExpressionWithTypeArguments(baseTypeNode)) { - error(baseTypeNode.expression, Diagnostics.Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_class_extends_clauses); - } - emitExtends = emitExtends || !isInAmbientContext(node); - checkExpressionWithTypeArguments(baseTypeNode); - } - let baseTypes = getBaseTypes(type); - if (baseTypes.length) { - if (produceDiagnostics) { + let baseTypes = getBaseTypes(type); + if (baseTypes.length && produceDiagnostics) { let baseType = baseTypes[0]; - checkTypeAssignableTo(type, baseType, node.name || node, Diagnostics.Class_0_incorrectly_extends_base_class_1); - let staticBaseType = getTypeOfSymbol(baseType.symbol); - checkTypeAssignableTo(staticType, getTypeWithoutConstructors(staticBaseType), node.name || node, - Diagnostics.Class_static_side_0_incorrectly_extends_base_class_static_side_1); - - if (baseType.symbol !== resolveEntityName(baseTypeNode.expression, SymbolFlags.Value)) { - error(baseTypeNode, Diagnostics.Type_name_0_in_extends_clause_does_not_reference_constructor_function_for_0, typeToString(baseType)); + let staticBaseType = getBaseConstructorTypeOfClass(type); + if (baseTypeNode.typeArguments) { + forEach(baseTypeNode.typeArguments, checkSourceElement); + for (let constructor of getConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments)) { + if (!checkTypeArgumentConstraints(constructor.typeParameters, baseTypeNode.typeArguments)) { + break; + } + } + } + checkTypeAssignableTo(type, baseType, node.name || node, Diagnostics.Class_0_incorrectly_extends_base_class_1); + checkTypeAssignableTo(staticType, getTypeWithoutSignatures(staticBaseType), node.name || node, + Diagnostics.Class_static_side_0_incorrectly_extends_base_class_static_side_1); + if (!(staticBaseType.symbol && staticBaseType.symbol.flags & SymbolFlags.Class)) { + // 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). + let constructors = getInstantiatedConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments); + if (forEach(constructors, sig => getReturnTypeOfSignature(sig) !== baseType)) { + error(baseTypeNode.expression, Diagnostics.Base_constructors_must_all_have_the_same_return_type); + } } - checkKindsOfPropertyMemberOverrides(type, baseType); } } - if (baseTypes.length || (baseTypeNode && compilerOptions.separateCompilation)) { - // Check that base type can be evaluated as expression - checkExpressionOrQualifiedName(baseTypeNode.expression); - } - let implementedTypeNodes = getClassImplementsHeritageClauseElements(node); if (implementedTypeNodes) { forEach(implementedTypeNodes, typeRefNode => { if (!isSupportedExpressionWithTypeArguments(typeRefNode)) { error(typeRefNode.expression, Diagnostics.A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments); } - - checkExpressionWithTypeArguments(typeRefNode); + checkTypeReferenceNode(typeRefNode); if (produceDiagnostics) { let t = getTypeFromTypeNode(typeRefNode); if (t !== unknownType) { @@ -10640,7 +11225,7 @@ module ts { function checkInterfaceDeclaration(node: InterfaceDeclaration) { // Grammar checking - checkGrammarDeclarationNameInStrictMode(node) || checkGrammarDecorators(node) || checkGrammarModifiers(node) || checkGrammarInterfaceDeclaration(node); + checkGrammarDecorators(node) || checkGrammarModifiers(node) || checkGrammarInterfaceDeclaration(node); checkTypeParameters(node.typeParameters); if (produceDiagnostics) { @@ -10671,8 +11256,7 @@ module ts { if (!isSupportedExpressionWithTypeArguments(heritageElement)) { error(heritageElement.expression, Diagnostics.An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments); } - - checkExpressionWithTypeArguments(heritageElement); + checkTypeReferenceNode(heritageElement); }); forEach(node.members, checkSourceElement); @@ -10865,7 +11449,7 @@ module ts { } // Grammar checking - checkGrammarDeclarationNameInStrictMode(node) || checkGrammarDecorators(node) || checkGrammarModifiers(node) || checkGrammarEnumDeclaration(node); + checkGrammarDecorators(node) || checkGrammarModifiers(node) || checkGrammarEnumDeclaration(node); checkTypeNameIsReserved(node.name, Diagnostics.Enum_name_cannot_be_0); checkCollisionWithCapturedThisVariable(node, node.name); @@ -10875,8 +11459,8 @@ module ts { computeEnumMemberValues(node); let enumIsConst = isConst(node); - if (compilerOptions.separateCompilation && enumIsConst && isInAmbientContext(node)) { - error(node.name, Diagnostics.Ambient_const_enums_are_not_allowed_when_the_separateCompilation_flag_is_provided); + if (compilerOptions.isolatedModules && enumIsConst && isInAmbientContext(node)) { + error(node.name, Diagnostics.Ambient_const_enums_are_not_allowed_when_the_isolatedModules_flag_is_provided); } // Spec 2014 - Section 9.3: @@ -10951,7 +11535,16 @@ module ts { function checkModuleDeclaration(node: ModuleDeclaration) { if (produceDiagnostics) { // Grammar checking - if (!checkGrammarDeclarationNameInStrictMode(node) && !checkGrammarDecorators(node) && !checkGrammarModifiers(node)) { + let isAmbientExternalModule = node.name.kind === SyntaxKind.StringLiteral; + let contextErrorMessage = isAmbientExternalModule + ? Diagnostics.An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file + : 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 (!isInAmbientContext(node) && node.name.kind === SyntaxKind.StringLiteral) { grammarErrorOnNode(node.name, Diagnostics.Only_ambient_modules_can_use_quoted_names); } @@ -10966,7 +11559,7 @@ module ts { if (symbol.flags & SymbolFlags.ValueModule && symbol.declarations.length > 1 && !isInAmbientContext(node) - && isInstantiatedModule(node, compilerOptions.preserveConstEnums || compilerOptions.separateCompilation)) { + && isInstantiatedModule(node, compilerOptions.preserveConstEnums || compilerOptions.isolatedModules)) { let firstNonAmbientClassOrFunc = getFirstNonAmbientClassOrFunctionDeclaration(symbol); if (firstNonAmbientClassOrFunc) { if (getSourceFileOfNode(node) !== getSourceFileOfNode(firstNonAmbientClassOrFunc)) { @@ -10987,7 +11580,7 @@ module ts { } // Checks for ambient external modules. - if (node.name.kind === SyntaxKind.StringLiteral) { + if (isAmbientExternalModule) { if (!isGlobalSourceFile(node.parent)) { error(node.name, Diagnostics.Ambient_modules_cannot_be_nested_in_other_modules); } @@ -11063,7 +11656,11 @@ module ts { } function checkImportDeclaration(node: ImportDeclaration) { - if (!checkGrammarImportDeclarationNameInStrictMode(node) && !checkGrammarDecorators(node) && !checkGrammarModifiers(node) && (node.flags & NodeFlags.Modifier)) { + if (checkGrammarModuleElementContext(node, 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) && (node.flags & NodeFlags.Modifier)) { grammarErrorOnFirstToken(node, Diagnostics.An_import_declaration_cannot_have_modifiers); } if (checkExternalImportOrExportDeclaration(node)) { @@ -11085,7 +11682,12 @@ module ts { } function checkImportEqualsDeclaration(node: ImportEqualsDeclaration) { - checkGrammarDeclarationNameInStrictMode(node) || checkGrammarDecorators(node) || checkGrammarModifiers(node); + if (checkGrammarModuleElementContext(node, 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 (isInternalModuleImportEqualsDeclaration(node) || checkExternalImportOrExportDeclaration(node)) { checkImportBinding(node); if (node.flags & NodeFlags.Export) { @@ -11116,9 +11718,15 @@ module ts { } function checkExportDeclaration(node: ExportDeclaration) { + if (checkGrammarModuleElementContext(node, 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) && (node.flags & NodeFlags.Modifier)) { grammarErrorOnFirstToken(node, Diagnostics.An_export_declaration_cannot_have_modifiers); } + if (!node.moduleSpecifier || checkExternalImportOrExportDeclaration(node)) { if (node.exportClause) { // export { x, y } @@ -11140,6 +11748,12 @@ module ts { } } + function checkGrammarModuleElementContext(node: Statement, errorMessage: DiagnosticMessage): boolean { + if (node.parent.kind !== SyntaxKind.SourceFile && node.parent.kind !== SyntaxKind.ModuleBlock && node.parent.kind !== SyntaxKind.ModuleDeclaration) { + return grammarErrorOnFirstToken(node, errorMessage); + } + } + function checkExportSpecifier(node: ExportSpecifier) { checkAliasSymbol(node); if (!(node.parent.parent).moduleSpecifier) { @@ -11148,6 +11762,11 @@ module ts { } function checkExportAssignment(node: ExportAssignment) { + if (checkGrammarModuleElementContext(node, 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; + } + let container = node.parent.kind === SyntaxKind.SourceFile ? node.parent : node.parent.parent; if (container.kind === SyntaxKind.ModuleDeclaration && (container).name.kind === SyntaxKind.Identifier) { error(node, Diagnostics.An_export_assignment_cannot_be_used_in_a_namespace); @@ -11163,7 +11782,8 @@ module ts { else { checkExpressionCached(node.expression); } - checkExternalModuleExports(container); + + checkExternalModuleExports(container); if (node.isExportEquals && !isInAmbientContext(node)) { if (languageVersion >= ScriptTarget.ES6) { @@ -11177,7 +11797,7 @@ module ts { } } - function getModuleStatements(node: Declaration): ModuleElement[] { + function getModuleStatements(node: Declaration): Statement[] { if (node.kind === SyntaxKind.SourceFile) { return (node).statements; } @@ -11209,6 +11829,12 @@ module ts { } } + function checkTypePredicate(node: TypePredicateNode) { + if(!isInLegalTypePredicatePosition(node)) { + error(node, Diagnostics.A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods); + } + } + function checkSourceElement(node: Node): void { if (!node) return; switch (node.kind) { @@ -11236,6 +11862,8 @@ module ts { return checkAccessorDeclaration(node); case SyntaxKind.TypeReference: return checkTypeReferenceNode(node); + case SyntaxKind.TypePredicate: + return checkTypePredicate(node); case SyntaxKind.TypeQuery: return checkTypeQuery(node); case SyntaxKind.TypeLiteral: @@ -11412,7 +12040,9 @@ module ts { function checkSourceFile(node: SourceFile) { let start = new Date().getTime(); + checkSourceFileWorker(node); + checkTime += new Date().getTime() - start; } @@ -11420,6 +12050,12 @@ module ts { function checkSourceFileWorker(node: SourceFile) { let links = getNodeLinks(node); if (!(links.flags & NodeCheckFlags.TypeChecked)) { + // Check whether the file has declared it is the default lib, + // and whether the user has specifically chosen to avoid checking it. + if (node.isDefaultLib && compilerOptions.skipDefaultLibCheck) { + return; + } + // Grammar checking checkGrammarSourceFile(node); @@ -11600,7 +12236,7 @@ module ts { } function isTypeDeclarationName(name: Node): boolean { - return name.kind == SyntaxKind.Identifier && + return name.kind === SyntaxKind.Identifier && isTypeDeclaration(name.parent) && (name.parent).name === name; } @@ -11635,93 +12271,6 @@ module ts { return node.parent && node.parent.kind === SyntaxKind.ExpressionWithTypeArguments; } - function isTypeNode(node: Node): boolean { - if (SyntaxKind.FirstTypeNode <= node.kind && node.kind <= SyntaxKind.LastTypeNode) { - return true; - } - - switch (node.kind) { - case SyntaxKind.AnyKeyword: - case SyntaxKind.NumberKeyword: - case SyntaxKind.StringKeyword: - case SyntaxKind.BooleanKeyword: - case SyntaxKind.SymbolKeyword: - return true; - case SyntaxKind.VoidKeyword: - return node.parent.kind !== SyntaxKind.VoidExpression; - case SyntaxKind.StringLiteral: - // Specialized signatures can have string literals as their parameters' type names - return node.parent.kind === SyntaxKind.Parameter; - case SyntaxKind.ExpressionWithTypeArguments: - return true; - - // Identifiers and qualified names may be type nodes, depending on their context. Climb - // above them to find the lowest container - case SyntaxKind.Identifier: - // If the identifier is the RHS of a qualified name, then it's a type iff its parent is. - if (node.parent.kind === SyntaxKind.QualifiedName && (node.parent).right === node) { - node = node.parent; - } - else if (node.parent.kind === SyntaxKind.PropertyAccessExpression && (node.parent).name === node) { - node = node.parent; - } - // fall through - case SyntaxKind.QualifiedName: - case SyntaxKind.PropertyAccessExpression: - // At this point, node is either a qualified name or an identifier - Debug.assert(node.kind === SyntaxKind.Identifier || node.kind === SyntaxKind.QualifiedName || node.kind === SyntaxKind.PropertyAccessExpression, - "'node' was expected to be a qualified name, identifier or property access in 'isTypeNode'."); - - let parent = node.parent; - if (parent.kind === SyntaxKind.TypeQuery) { - return false; - } - // Do not recursively call isTypeNode on the parent. In the example: - // - // let a: A.B.C; - // - // Calling isTypeNode would consider the qualified name A.B a type node. Only C or - // A.B.C is a type node. - if (SyntaxKind.FirstTypeNode <= parent.kind && parent.kind <= SyntaxKind.LastTypeNode) { - return true; - } - switch (parent.kind) { - case SyntaxKind.ExpressionWithTypeArguments: - return true; - case SyntaxKind.TypeParameter: - return node === (parent).constraint; - case SyntaxKind.PropertyDeclaration: - case SyntaxKind.PropertySignature: - case SyntaxKind.Parameter: - case SyntaxKind.VariableDeclaration: - return node === (parent).type; - case SyntaxKind.FunctionDeclaration: - case SyntaxKind.FunctionExpression: - case SyntaxKind.ArrowFunction: - case SyntaxKind.Constructor: - case SyntaxKind.MethodDeclaration: - case SyntaxKind.MethodSignature: - case SyntaxKind.GetAccessor: - case SyntaxKind.SetAccessor: - return node === (parent).type; - case SyntaxKind.CallSignature: - case SyntaxKind.ConstructSignature: - case SyntaxKind.IndexSignature: - return node === (parent).type; - case SyntaxKind.TypeAssertionExpression: - return node === (parent).type; - case SyntaxKind.CallExpression: - case SyntaxKind.NewExpression: - return (parent).typeArguments && indexOf((parent).typeArguments, node) >= 0; - case SyntaxKind.TaggedTemplateExpression: - // TODO (drosen): TaggedTemplateExpressions may eventually support type arguments. - return false; - } - } - - return false; - } - function getLeftSideOfImportEqualsOrExportAssignment(nodeOnRightSide: EntityName): ImportEqualsDeclaration | ExportAssignment { while (nodeOnRightSide.parent.kind === SyntaxKind.QualifiedName) { nodeOnRightSide = nodeOnRightSide.parent; @@ -11856,7 +12405,7 @@ module ts { // Intentional fall-through case SyntaxKind.NumericLiteral: // index access - if (node.parent.kind == SyntaxKind.ElementAccessExpression && (node.parent).argumentExpression === node) { + if (node.parent.kind === SyntaxKind.ElementAccessExpression && (node.parent).argumentExpression === node) { let objectType = checkExpression((node.parent).expression); if (objectType === unknownType) return undefined; let apparentType = getApparentType(objectType); @@ -11892,6 +12441,12 @@ module ts { return getTypeOfExpression(node); } + if (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. + return getBaseTypes(getDeclaredTypeOfSymbol(getSymbolOfNode(node.parent.parent)))[0]; + } + if (isTypeDeclaration(node)) { // In this case, we call getSymbolOfNode instead of getSymbolInfo because it is a declaration let symbol = getSymbolOfNode(node); @@ -11976,80 +12531,80 @@ module ts { // Emitter support - function isExternalModuleSymbol(symbol: Symbol): boolean { - return symbol.flags & SymbolFlags.ValueModule && symbol.declarations.length === 1 && symbol.declarations[0].kind === SyntaxKind.SourceFile; - } - - function getAliasNameSubstitution(symbol: Symbol, getGeneratedNameForNode: (node: Node) => string): string { - // If this is es6 or higher, just use the name of the export - // no need to qualify it. - if (languageVersion >= ScriptTarget.ES6) { - return undefined; - } - - let node = getDeclarationOfAliasSymbol(symbol); - if (node) { - if (node.kind === SyntaxKind.ImportClause) { - let defaultKeyword: string; - - if (languageVersion === ScriptTarget.ES3) { - defaultKeyword = "[\"default\"]"; - } else { - defaultKeyword = ".default"; - } - return getGeneratedNameForNode(node.parent) + defaultKeyword; - } - if (node.kind === SyntaxKind.ImportSpecifier) { - let moduleName = getGeneratedNameForNode(node.parent.parent.parent); - let propertyName = (node).propertyName || (node).name; - return moduleName + "." + unescapeIdentifier(propertyName.text); - } - } - } - - function getExportNameSubstitution(symbol: Symbol, location: Node, getGeneratedNameForNode: (Node: Node) => string): string { - if (isExternalModuleSymbol(symbol.parent)) { - // 1. If this is es6 or higher, just use the name of the export - // no need to qualify it. - // 2. export mechanism for System modules is different from CJS\AMD - // and it does not need qualifications for exports - if (languageVersion >= ScriptTarget.ES6 || compilerOptions.module === ModuleKind.System) { - return undefined; - } - return "exports." + unescapeIdentifier(symbol.name); - } - let node = location; - let containerSymbol = getParentOfSymbol(symbol); - while (node) { - if ((node.kind === SyntaxKind.ModuleDeclaration || node.kind === SyntaxKind.EnumDeclaration) && getSymbolOfNode(node) === containerSymbol) { - return getGeneratedNameForNode(node) + "." + unescapeIdentifier(symbol.name); - } - node = node.parent; - } - } - - function getExpressionNameSubstitution(node: Identifier, getGeneratedNameForNode: (Node: Node) => string): string { - let symbol = getNodeLinks(node).resolvedSymbol || (isDeclarationName(node) ? getSymbolOfNode(node.parent) : undefined); + // 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: Identifier): SourceFile | ModuleDeclaration | EnumDeclaration { + let symbol = getReferencedValueSymbol(node); if (symbol) { - // Whan an identifier resolves to a parented symbol, it references an exported entity from - // another declaration of the same internal module. - if (symbol.parent) { - return getExportNameSubstitution(symbol, node.parent, getGeneratedNameForNode); + if (symbol.flags & SymbolFlags.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. + let exportSymbol = getMergedSymbol(symbol.exportSymbol); + if (exportSymbol.flags & SymbolFlags.ExportHasLocal) { + return undefined; + } + symbol = exportSymbol; } - // 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. - let exportSymbol = getExportSymbolOfValueSymbolIfExported(symbol); - if (symbol !== exportSymbol && !(exportSymbol.flags & SymbolFlags.ExportHasLocal)) { - return getExportNameSubstitution(exportSymbol, node.parent, getGeneratedNameForNode); - } - // Named imports from ES6 import declarations are rewritten - if (symbol.flags & SymbolFlags.Alias) { - return getAliasNameSubstitution(symbol, getGeneratedNameForNode); + let parentSymbol = getParentOfSymbol(symbol); + if (parentSymbol) { + if (parentSymbol.flags & SymbolFlags.ValueModule && parentSymbol.valueDeclaration.kind === SyntaxKind.SourceFile) { + return parentSymbol.valueDeclaration; + } + for (let n = node.parent; n; n = n.parent) { + if ((n.kind === SyntaxKind.ModuleDeclaration || n.kind === SyntaxKind.EnumDeclaration) && getSymbolOfNode(n) === parentSymbol) { + return n; + } + } } } } + // 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: Identifier): Declaration { + let symbol = getReferencedValueSymbol(node); + return symbol && symbol.flags & SymbolFlags.Alias ? getDeclarationOfAliasSymbol(symbol) : undefined; + } + + function isStatementWithLocals(node: Node) { + switch (node.kind) { + case SyntaxKind.Block: + case SyntaxKind.CaseBlock: + case SyntaxKind.ForStatement: + case SyntaxKind.ForInStatement: + case SyntaxKind.ForOfStatement: + return true; + } + return false; + } + + function isNestedRedeclarationSymbol(symbol: Symbol): boolean { + if (symbol.flags & SymbolFlags.BlockScoped) { + let links = getSymbolLinks(symbol); + if (links.isNestedRedeclaration === undefined) { + let container = getEnclosingBlockScopeContainer(symbol.valueDeclaration); + links.isNestedRedeclaration = isStatementWithLocals(container) && + !!resolveName(container.parent, symbol.name, SymbolFlags.Value, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined); + } + return links.isNestedRedeclaration; + } + return false; + } + + // When resolved as an expression identifier, if the given node references a nested block scoped entity with + // a name that hides an existing name, return the declaration of that entity. Otherwise, return undefined. + function getReferencedNestedRedeclaration(node: Identifier): Declaration { + let symbol = getReferencedValueSymbol(node); + return symbol && isNestedRedeclarationSymbol(symbol) ? symbol.valueDeclaration : undefined; + } + + // Return true if the given node is a declaration of a nested block scoped entity with a name that hides an + // existing name. + function isNestedRedeclaration(node: Declaration): boolean { + return isNestedRedeclarationSymbol(getSymbolOfNode(node)); + } + function isValueAliasDeclaration(node: Node): boolean { switch (node.kind) { case SyntaxKind.ImportEqualsDeclaration: @@ -12079,7 +12634,7 @@ module ts { function isAliasResolvedToValue(symbol: Symbol): boolean { let target = resolveAlias(symbol); - if (target === unknownSymbol && compilerOptions.separateCompilation) { + if (target === unknownSymbol && compilerOptions.isolatedModules) { return true; } // const enums and modules that contain only const enums are not considered values from the emit perespective @@ -12151,10 +12706,13 @@ module ts { } /** Serializes an EntityName (with substitutions) to an appropriate JS constructor value. Used by the __metadata decorator. */ - function serializeEntityName(node: EntityName, getGeneratedNameForNode: (Node: Node) => string, fallbackPath?: string[]): string { + function serializeEntityName(node: EntityName, fallbackPath?: string[]): string { if (node.kind === SyntaxKind.Identifier) { - var substitution = getExpressionNameSubstitution(node, getGeneratedNameForNode); - var text = substitution || (node).text; + // TODO(ron.buckton): The getExpressionNameSubstitution function has been removed, but calling it + // here has no effect anyway as an identifier in a type name is not an expression. + // var substitution = getExpressionNameSubstitution(node, getGeneratedNameForNode); + // var text = substitution || (node).text; + var text = (node).text; if (fallbackPath) { fallbackPath.push(text); } @@ -12163,8 +12721,8 @@ module ts { } } else { - var left = serializeEntityName((node).left, getGeneratedNameForNode, fallbackPath); - var right = serializeEntityName((node).right, getGeneratedNameForNode, fallbackPath); + var left = serializeEntityName((node).left, fallbackPath); + var right = serializeEntityName((node).right, fallbackPath); if (!fallbackPath) { return left + "." + right; } @@ -12172,7 +12730,7 @@ module ts { } /** Serializes a TypeReferenceNode to an appropriate JS constructor value. Used by the __metadata decorator. */ - function serializeTypeReferenceNode(node: TypeReferenceNode, getGeneratedNameForNode: (Node: Node) => string): string | string[] { + function serializeTypeReferenceNode(node: TypeReferenceNode): string | string[] { // serialization of a TypeReferenceNode uses the following rules: // // * The serialized type of a TypeReference that is `void` is "void 0". @@ -12205,11 +12763,11 @@ module ts { } else if (type === unknownType) { var fallbackPath: string[] = []; - serializeEntityName(node.typeName, getGeneratedNameForNode, fallbackPath); + serializeEntityName(node.typeName, fallbackPath); return fallbackPath; } else if (type.symbol && type.symbol.valueDeclaration) { - return serializeEntityName(node.typeName, getGeneratedNameForNode); + return serializeEntityName(node.typeName); } else if (typeHasCallOrConstructSignatures(type)) { return "Function"; @@ -12219,7 +12777,7 @@ module ts { } /** Serializes a TypeNode to an appropriate JS constructor value. Used by the __metadata decorator. */ - function serializeTypeNode(node: TypeNode | LiteralExpression, getGeneratedNameForNode: (Node: Node) => string): string | string[] { + function serializeTypeNode(node: TypeNode | LiteralExpression): string | string[] { // serialization of a TypeNode uses the following rules: // // * The serialized type of `void` is "void 0" (undefined). @@ -12235,7 +12793,7 @@ module ts { case SyntaxKind.VoidKeyword: return "void 0"; case SyntaxKind.ParenthesizedType: - return serializeTypeNode((node).type, getGeneratedNameForNode); + return serializeTypeNode((node).type); case SyntaxKind.FunctionType: case SyntaxKind.ConstructorType: return "Function"; @@ -12250,7 +12808,7 @@ module ts { case SyntaxKind.NumberKeyword: return "Number"; case SyntaxKind.TypeReference: - return serializeTypeReferenceNode(node, getGeneratedNameForNode); + return serializeTypeReferenceNode(node); case SyntaxKind.TypeQuery: case SyntaxKind.TypeLiteral: case SyntaxKind.UnionType: @@ -12266,7 +12824,7 @@ module ts { } /** Serializes the type of a declaration to an appropriate JS constructor value. Used by the __metadata decorator for a class member. */ - function serializeTypeOfNode(node: Node, getGeneratedNameForNode: (Node: Node) => string): string | string[] { + function serializeTypeOfNode(node: Node): string | string[] { // serialization of the type of a declaration uses the following rules: // // * The serialized type of a ClassDeclaration is "Function" @@ -12279,10 +12837,10 @@ module ts { // For rules on serializing type annotations, see `serializeTypeNode`. switch (node.kind) { case SyntaxKind.ClassDeclaration: return "Function"; - case SyntaxKind.PropertyDeclaration: return serializeTypeNode((node).type, getGeneratedNameForNode); - case SyntaxKind.Parameter: return serializeTypeNode((node).type, getGeneratedNameForNode); - case SyntaxKind.GetAccessor: return serializeTypeNode((node).type, getGeneratedNameForNode); - case SyntaxKind.SetAccessor: return serializeTypeNode(getSetAccessorTypeAnnotationNode(node), getGeneratedNameForNode); + case SyntaxKind.PropertyDeclaration: return serializeTypeNode((node).type); + case SyntaxKind.Parameter: return serializeTypeNode((node).type); + case SyntaxKind.GetAccessor: return serializeTypeNode((node).type); + case SyntaxKind.SetAccessor: return serializeTypeNode(getSetAccessorTypeAnnotationNode(node)); } if (isFunctionLike(node)) { return "Function"; @@ -12291,7 +12849,7 @@ module ts { } /** Serializes the parameter types of a function or the constructor of a class. Used by the __metadata decorator for a method or set accessor. */ - function serializeParameterTypesOfNode(node: Node, getGeneratedNameForNode: (Node: Node) => string): (string | string[])[] { + function serializeParameterTypesOfNode(node: Node): (string | string[])[] { // serialization of parameter types uses the following rules: // // * If the declaration is a class, the parameters of the first constructor with a body are used. @@ -12324,10 +12882,10 @@ module ts { else { parameterType = undefined; } - result[i] = serializeTypeNode(parameterType, getGeneratedNameForNode); + result[i] = serializeTypeNode(parameterType); } else { - result[i] = serializeTypeOfNode(parameters[i], getGeneratedNameForNode); + result[i] = serializeTypeOfNode(parameters[i]); } } return result; @@ -12338,9 +12896,9 @@ module ts { } /** Serializes the return type of function. Used by the __metadata decorator for a method. */ - function serializeReturnTypeOfNode(node: Node, getGeneratedNameForNode: (Node: Node) => string): string | string[] { + function serializeReturnTypeOfNode(node: Node): string | string[] { if (node && isFunctionLike(node)) { - return serializeTypeNode((node).type, getGeneratedNameForNode); + return serializeTypeNode((node).type); } return "void 0"; } @@ -12369,17 +12927,15 @@ module ts { return hasProperty(globals, name); } - function resolvesToSomeValue(location: Node, name: string): boolean { - Debug.assert(!nodeIsSynthesized(location), "resolvesToSomeValue called with a synthesized location"); - return !!resolveName(location, name, SymbolFlags.Value, /*nodeNotFoundMessage*/ undefined, /*nameArg*/ undefined); + function getReferencedValueSymbol(reference: Identifier): Symbol { + return getNodeLinks(reference).resolvedSymbol || + resolveName(reference, reference.text, SymbolFlags.Value | SymbolFlags.ExportValue | SymbolFlags.Alias, + /*nodeNotFoundMessage*/ undefined, /*nameArg*/ undefined); } function getReferencedValueDeclaration(reference: Identifier): Declaration { Debug.assert(!nodeIsSynthesized(reference)); - let symbol = - getNodeLinks(reference).resolvedSymbol || - resolveName(reference, reference.text, SymbolFlags.Value | SymbolFlags.Alias, /*nodeNotFoundMessage*/ undefined, /*nameArg*/ undefined); - + let symbol = getReferencedValueSymbol(reference); return symbol && getExportSymbolOfValueSymbolIfExported(symbol).valueDeclaration; } @@ -12424,7 +12980,10 @@ module ts { function createResolver(): EmitResolver { return { - getExpressionNameSubstitution, + getReferencedExportContainer, + getReferencedImportDeclaration, + getReferencedNestedRedeclaration, + isNestedRedeclaration, isValueAliasDeclaration, hasGlobalName, isReferencedAliasDeclaration, @@ -12438,7 +12997,6 @@ module ts { isSymbolAccessible, isEntityNameVisible, getConstantValue, - resolvesToSomeValue, collectLinkedAliases, getBlockScopedVariableId, getReferencedValueDeclaration, @@ -12467,8 +13025,7 @@ module ts { getSymbolLinks(unknownSymbol).type = unknownType; globals[undefinedSymbol.name] = undefinedSymbol; // Initialize special types - globalArraySymbol = getGlobalTypeSymbol("Array"); - globalArrayType = getTypeOfGlobalSymbol(globalArraySymbol, /*arity*/ 1); + globalArrayType = getGlobalType("Array", /*arity*/ 1); globalObjectType = getGlobalType("Object"); globalFunctionType = getGlobalType("Function"); globalStringType = getGlobalType("String"); @@ -12483,7 +13040,9 @@ module ts { globalTemplateStringsArrayType = getGlobalType("TemplateStringsArray"); globalESSymbolType = getGlobalType("Symbol"); globalESSymbolConstructorSymbol = getGlobalValueSymbol("Symbol"); - globalIterableType = getGlobalType("Iterable", /*arity*/ 1); + globalIterableType = getGlobalType("Iterable", /*arity*/ 1); + globalIteratorType = getGlobalType("Iterator", /*arity*/ 1); + globalIterableIteratorType = getGlobalType("IterableIterator", /*arity*/ 1); } else { globalTemplateStringsArrayType = unknownType; @@ -12493,159 +13052,15 @@ module ts { // a global Symbol already, particularly if it is a class. globalESSymbolType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); globalESSymbolConstructorSymbol = undefined; + globalIterableType = emptyGenericType; + globalIteratorType = emptyGenericType; + globalIterableIteratorType = emptyGenericType; } anyArrayType = createArrayType(anyType); } // GRAMMAR CHECKING - function isReservedWordInStrictMode(node: Identifier): boolean { - // Check that originalKeywordKind is less than LastFutureReservedWord to see if an Identifier is a strict-mode reserved word - return (node.parserContextFlags & ParserContextFlags.StrictMode) && - (SyntaxKind.FirstFutureReservedWord <= node.originalKeywordKind && node.originalKeywordKind <= SyntaxKind.LastFutureReservedWord); - } - - function reportStrictModeGrammarErrorInClassDeclaration(identifier: Identifier, message: DiagnosticMessage, arg0?: any, arg1?: any, arg2?: any): boolean { - // We are checking if this name is inside class declaration or class expression (which are under class definitions inside ES6 spec.) - // if so, we would like to give more explicit invalid usage error. - if (getAncestor(identifier, SyntaxKind.ClassDeclaration) || getAncestor(identifier, SyntaxKind.ClassExpression)) { - return grammarErrorOnNode(identifier, message, arg0); - } - return false; - } - - function checkGrammarImportDeclarationNameInStrictMode(node: ImportDeclaration): boolean { - // Check if the import declaration used strict-mode reserved word in its names bindings - if (node.importClause) { - let impotClause = node.importClause; - if (impotClause.namedBindings) { - let nameBindings = impotClause.namedBindings; - if (nameBindings.kind === SyntaxKind.NamespaceImport) { - let name = (nameBindings).name; - if (isReservedWordInStrictMode(name)) { - let nameText = declarationNameToString(name); - return grammarErrorOnNode(name, Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode, nameText); - } - } - else if (nameBindings.kind === SyntaxKind.NamedImports) { - let reportError = false; - for (let element of (nameBindings).elements) { - let name = element.name; - if (isReservedWordInStrictMode(name)) { - let nameText = declarationNameToString(name); - reportError = reportError || grammarErrorOnNode(name, Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode, nameText); - } - } - return reportError; - } - } - } - return false; - } - - function checkGrammarDeclarationNameInStrictMode(node: Declaration): boolean { - let name = node.name; - if (name && name.kind === SyntaxKind.Identifier && isReservedWordInStrictMode(name)) { - let nameText = declarationNameToString(name); - switch (node.kind) { - case SyntaxKind.Parameter: - case SyntaxKind.VariableDeclaration: - case SyntaxKind.FunctionDeclaration: - case SyntaxKind.TypeParameter: - case SyntaxKind.BindingElement: - case SyntaxKind.InterfaceDeclaration: - case SyntaxKind.TypeAliasDeclaration: - case SyntaxKind.EnumDeclaration: - return checkGrammarIdentifierInStrictMode(name); - - case SyntaxKind.ClassDeclaration: - // Report an error if the class declaration uses strict-mode reserved word. - return grammarErrorOnNode(name, Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_strict_mode, nameText); - - case SyntaxKind.ModuleDeclaration: - // Report an error if the module declaration uses strict-mode reserved word. - // TODO(yuisu): fix this when having external module in strict mode - return grammarErrorOnNode(name, Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode, nameText); - - case SyntaxKind.ImportEqualsDeclaration: - // TODO(yuisu): fix this when having external module in strict mode - return grammarErrorOnNode(name, Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode, nameText); - } - } - return false; - } - - function checkGrammarTypeReferenceInStrictMode(typeName: Identifier | QualifiedName) { - // Check if the type reference is using strict mode keyword - // Example: - // class C { - // foo(x: public){} // Error. - // } - if (typeName.kind === SyntaxKind.Identifier) { - checkGrammarTypeNameInStrictMode(typeName); - } - // Report an error for each identifier in QualifiedName - // Example: - // foo (x: B.private.bar) // error at private - // foo (x: public.private.package) // error at public, private, and package - else if (typeName.kind === SyntaxKind.QualifiedName) { - // Walk from right to left and report a possible error at each Identifier in QualifiedName - // Example: - // x1: public.private.package // error at public and private - checkGrammarTypeNameInStrictMode((typeName).right); - checkGrammarTypeReferenceInStrictMode((typeName).left); - } - } - - // This function will report an error for every identifier in property access expression - // whether it violates strict mode reserved words. - // Example: - // public // error at public - // public.private.package // error at public - // B.private.B // no error - function checkGrammarExpressionWithTypeArgumentsInStrictMode(expression: Expression) { - // Example: - // class C extends public // error at public - if (expression && expression.kind === SyntaxKind.Identifier) { - return checkGrammarIdentifierInStrictMode(expression); - } - else if (expression && expression.kind === SyntaxKind.PropertyAccessExpression) { - // Walk from left to right in PropertyAccessExpression until we are at the left most expression - // in PropertyAccessExpression. According to grammar production of MemberExpression, - // the left component expression is a PrimaryExpression (i.e. Identifier) while the other - // component after dots can be IdentifierName. - checkGrammarExpressionWithTypeArgumentsInStrictMode((expression).expression); - } - - } - - // The function takes an identifier itself or an expression which has SyntaxKind.Identifier. - function checkGrammarIdentifierInStrictMode(node: Expression | Identifier, nameText?: string): boolean { - if (node && node.kind === SyntaxKind.Identifier && isReservedWordInStrictMode(node)) { - if (!nameText) { - nameText = declarationNameToString(node); - } - - // TODO (yuisu): Fix when module is a strict mode - let errorReport = reportStrictModeGrammarErrorInClassDeclaration(node, Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_strict_mode, nameText)|| - grammarErrorOnNode(node, Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode, nameText); - return errorReport; - } - return false; - } - - // The function takes an identifier when uses as a typeName in TypeReferenceNode - function checkGrammarTypeNameInStrictMode(node: Identifier): boolean { - if (node && node.kind === SyntaxKind.Identifier && isReservedWordInStrictMode(node)) { - let nameText = declarationNameToString(node); - - // TODO (yuisu): Fix when module is a strict mode - let errorReport = reportStrictModeGrammarErrorInClassDeclaration(node, Diagnostics.Type_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_strict_mode, nameText) || - grammarErrorOnNode(node, Diagnostics.Type_expected_0_is_a_reserved_word_in_strict_mode, nameText); - return errorReport; - } - return false; - } function checkGrammarDecorators(node: Node): boolean { if (!node.decorators) { @@ -12676,19 +13091,28 @@ module ts { case SyntaxKind.MethodDeclaration: case SyntaxKind.MethodSignature: case SyntaxKind.IndexSignature: - case SyntaxKind.ClassDeclaration: - case SyntaxKind.InterfaceDeclaration: case SyntaxKind.ModuleDeclaration: - case SyntaxKind.EnumDeclaration: - case SyntaxKind.VariableStatement: - case SyntaxKind.FunctionDeclaration: - case SyntaxKind.TypeAliasDeclaration: case SyntaxKind.ImportDeclaration: case SyntaxKind.ImportEqualsDeclaration: case SyntaxKind.ExportDeclaration: case SyntaxKind.ExportAssignment: case SyntaxKind.Parameter: break; + case SyntaxKind.ClassDeclaration: + case SyntaxKind.InterfaceDeclaration: + case SyntaxKind.VariableStatement: + case SyntaxKind.FunctionDeclaration: + case SyntaxKind.TypeAliasDeclaration: + if (node.modifiers && node.parent.kind !== SyntaxKind.ModuleBlock && node.parent.kind !== SyntaxKind.SourceFile) { + return grammarErrorOnFirstToken(node, Diagnostics.Modifiers_cannot_appear_here); + } + break; + case SyntaxKind.EnumDeclaration: + if (node.modifiers && (node.modifiers.length > 1 || node.modifiers[0].kind !== SyntaxKind.ConstKeyword) && + node.parent.kind !== SyntaxKind.ModuleBlock && node.parent.kind !== SyntaxKind.SourceFile) { + return grammarErrorOnFirstToken(node, Diagnostics.Modifiers_cannot_appear_here); + } + break; default: return false; } @@ -13040,15 +13464,22 @@ module ts { function checkGrammarForGenerator(node: FunctionLikeDeclaration) { if (node.asteriskToken) { - return grammarErrorOnNode(node.asteriskToken, Diagnostics.Generators_are_not_currently_supported); + Debug.assert( + node.kind === SyntaxKind.FunctionDeclaration || + node.kind === SyntaxKind.FunctionExpression || + node.kind === SyntaxKind.MethodDeclaration); + if (isInAmbientContext(node)) { + return grammarErrorOnNode(node.asteriskToken, Diagnostics.Generators_are_not_allowed_in_an_ambient_context); + } + if (!node.body) { + return grammarErrorOnNode(node.asteriskToken, Diagnostics.An_overload_signature_cannot_be_declared_as_a_generator); + } + if (languageVersion < ScriptTarget.ES6) { + return grammarErrorOnNode(node.asteriskToken, Diagnostics.Generators_are_only_available_when_targeting_ECMAScript_6_or_higher); + } } } - function checkGrammarFunctionName(name: Node) { - // It is a SyntaxError if the identifier eval or arguments appears within a FormalParameterList of a strict mode FunctionDeclaration or FunctionExpression (13.1)) - return checkGrammarEvalOrArgumentsInStrictMode(name, name); - } - function checkGrammarForInvalidQuestionMark(node: Declaration, questionToken: Node, message: DiagnosticMessage): boolean { if (questionToken) { return grammarErrorOnNode(questionToken, message); @@ -13061,7 +13492,6 @@ module ts { let GetAccessor = 2; let SetAccesor = 4; let GetOrSetAccessor = GetAccessor | SetAccesor; - let inStrictMode = (node.parserContextFlags & ParserContextFlags.StrictMode) !== 0; for (let prop of node.properties) { let name = prop.name; @@ -13108,9 +13538,7 @@ module ts { else { let existingKind = seen[(name).text]; if (currentKind === Property && existingKind === Property) { - if (inStrictMode) { - grammarErrorOnNode(name, Diagnostics.An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode); - } + continue; } else if ((currentKind & GetOrSetAccessor) && (existingKind & GetOrSetAccessor)) { if (existingKind !== GetOrSetAccessor && currentKind !== existingKind) { @@ -13333,9 +13761,6 @@ module ts { return grammarErrorAtPos(getSourceFileOfNode(node), node.initializer.pos - 1, 1, Diagnostics.A_rest_element_cannot_have_an_initializer); } } - // It is a SyntaxError if a VariableDeclaration or VariableDeclarationNoIn occurs within strict code - // and its Identifier is eval or arguments - return checkGrammarEvalOrArgumentsInStrictMode(node, node.name); } function checkGrammarVariableDeclaration(node: VariableDeclaration) { @@ -13367,8 +13792,7 @@ module ts { // 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)) || - checkGrammarEvalOrArgumentsInStrictMode(node, node.name); + return checkLetConstNames && checkGrammarNameInLetOrConstDeclarations(node.name); } function checkGrammarNameInLetOrConstDeclarations(name: Identifier | BindingPattern): boolean { @@ -13507,29 +13931,6 @@ module ts { } } - function checkGrammarEvalOrArgumentsInStrictMode(contextNode: Node, name: Node): boolean { - if (name && name.kind === SyntaxKind.Identifier) { - let identifier = name; - if (contextNode && (contextNode.parserContextFlags & ParserContextFlags.StrictMode) && isEvalOrArgumentsIdentifier(identifier)) { - let nameText = declarationNameToString(identifier); - - // We check first if the name is inside class declaration or class expression; if so give explicit message - // otherwise report generic error message. - // reportGrammarErrorInClassDeclaration only return true if grammar error is successfully reported and false otherwise - let reportErrorInClassDeclaration = reportStrictModeGrammarErrorInClassDeclaration(identifier, Diagnostics.Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode, nameText); - if (!reportErrorInClassDeclaration){ - return grammarErrorOnNode(identifier, Diagnostics.Invalid_use_of_0_in_strict_mode, nameText); - } - return reportErrorInClassDeclaration; - } - } - } - - function isEvalOrArgumentsIdentifier(node: Node): boolean { - return node.kind === SyntaxKind.Identifier && - ((node).text === "eval" || (node).text === "arguments"); - } - function checkGrammarConstructorTypeParameters(node: ConstructorDeclaration) { if (node.typeParameters) { return grammarErrorAtPos(getSourceFileOfNode(node), node.typeParameters.pos, node.typeParameters.end - node.typeParameters.pos, Diagnostics.Type_parameters_cannot_appear_on_a_constructor_declaration); @@ -13639,13 +14040,8 @@ module ts { function checkGrammarNumericLiteral(node: Identifier): boolean { // Grammar checking - if (node.flags & NodeFlags.OctalLiteral) { - if (node.parserContextFlags & ParserContextFlags.StrictMode) { - return grammarErrorOnNode(node, Diagnostics.Octal_literals_are_not_allowed_in_strict_mode); - } - else if (languageVersion >= ScriptTarget.ES5) { - return grammarErrorOnNode(node, Diagnostics.Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher); - } + if (node.flags & NodeFlags.OctalLiteral && languageVersion >= ScriptTarget.ES5) { + return grammarErrorOnNode(node, Diagnostics.Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher); } } @@ -13657,9 +14053,5 @@ module ts { return true; } } - - initializeTypeChecker(); - - return checker; } } diff --git a/src/compiler/commandLineParser.ts b/src/compiler/commandLineParser.ts index 7a589fe61cb..4e401c5c9b3 100644 --- a/src/compiler/commandLineParser.ts +++ b/src/compiler/commandLineParser.ts @@ -3,7 +3,7 @@ /// /// -module ts { +namespace ts { /* @internal */ export var optionDeclarations: CommandLineOption[] = [ { @@ -103,9 +103,14 @@ module ts { name: "noResolve", type: "boolean", }, + { + name: "skipDefaultLibCheck", + type: "boolean", + }, { name: "out", type: "string", + isFilePath: true, description: Diagnostics.Concatenate_and_emit_output_to_single_file, paramType: Diagnostics.FILE, }, @@ -142,7 +147,7 @@ module ts { paramType: Diagnostics.LOCATION, }, { - name: "separateCompilation", + name: "isolatedModules", type: "boolean", }, { @@ -188,10 +193,16 @@ module ts { type: "boolean", description: Diagnostics.Watch_input_files, }, + { + name: "experimentalDecorators", + type: "boolean", + description: Diagnostics.Enables_experimental_support_for_ES7_decorators + }, { name: "emitDecoratorMetadata", type: "boolean", - experimental: true + experimental: true, + description: Diagnostics.Enables_experimental_support_for_emitting_type_metadata_for_decorators } ]; @@ -343,7 +354,7 @@ module ts { return { options: getCompilerOptions(), - fileNames: getFiles(), + fileNames: getFileNames(), errors }; @@ -389,23 +400,24 @@ module ts { return options; } - function getFiles(): string[] { - var files: string[] = []; + function getFileNames(): string[] { + var fileNames: string[] = []; if (hasProperty(json, "files")) { if (json["files"] instanceof Array) { - var files = map(json["files"], s => combinePaths(basePath, s)); + fileNames = map(json["files"], s => combinePaths(basePath, s)); } } else { - var sysFiles = host.readDirectory(basePath, ".ts"); + var exclude = json["exclude"] instanceof Array ? map(json["exclude"], normalizeSlashes) : undefined; + var sysFiles = host.readDirectory(basePath, ".ts", exclude); for (var i = 0; i < sysFiles.length; i++) { var name = sysFiles[i]; if (!fileExtensionIs(name, ".d.ts") || !contains(sysFiles, name.substr(0, name.length - 5) + ".ts")) { - files.push(name); + fileNames.push(name); } } } - return files; + return fileNames; } } } diff --git a/src/compiler/core.ts b/src/compiler/core.ts index f5719033a2a..ced477eeeec 100644 --- a/src/compiler/core.ts +++ b/src/compiler/core.ts @@ -1,7 +1,7 @@ /// /* @internal */ -module ts { +namespace ts { // Ternary values are defined such that // x & y is False if either x or y is False. // x & y is Maybe if either x or y is Maybe, but neither x or y is False. @@ -15,6 +15,42 @@ module ts { True = -1 } + export function createFileMap(getCanonicalFileName: (fileName: string) => string): FileMap { + let files: Map = {}; + return { + get, + set, + contains, + remove, + forEachValue: forEachValueInMap + } + + function set(fileName: string, value: T) { + files[normalizeKey(fileName)] = value; + } + + function get(fileName: string) { + return files[normalizeKey(fileName)]; + } + + function contains(fileName: string) { + return hasProperty(files, normalizeKey(fileName)); + } + + function remove (fileName: string) { + let key = normalizeKey(fileName); + delete files[key]; + } + + function forEachValueInMap(f: (value: T) => void) { + forEachValue(files, f); + } + + function normalizeKey(key: string) { + return getCanonicalFileName(normalizeSlashes(key)); + } + } + export const enum Comparison { LessThan = -1, EqualTo = 0, @@ -129,6 +165,16 @@ module ts { } } + export function rangeEquals(array1: T[], array2: T[], pos: number, end: number) { + while (pos < end) { + if (array1[pos] !== array2[pos]) { + return false; + } + pos++; + } + return true; + } + /** * Returns the last element of an array if non-empty, undefined otherwise. */ @@ -526,7 +572,7 @@ module ts { export function getNormalizedPathComponents(path: string, currentDirectory: string) { path = normalizeSlashes(path); let rootLength = getRootLength(path); - if (rootLength == 0) { + if (rootLength === 0) { // If the path is not rooted it is relative to current directory path = combinePaths(normalizeSlashes(currentDirectory), path); rootLength = getRootLength(path); diff --git a/src/compiler/declarationEmitter.ts b/src/compiler/declarationEmitter.ts index 5c705f18190..2ba88f1ac29 100644 --- a/src/compiler/declarationEmitter.ts +++ b/src/compiler/declarationEmitter.ts @@ -1,7 +1,7 @@ /// /* @internal */ -module ts { +namespace ts { interface ModuleElementDeclarationEmitInfo { node: Node; outputPos: number; @@ -709,7 +709,12 @@ module ts { function writeModuleDeclaration(node: ModuleDeclaration) { emitJsDocComments(node); emitModuleElementDeclarationFlags(node); - write("module "); + if (node.flags & NodeFlags.Namespace) { + write("namespace "); + } + else { + write("module "); + } writeTextOfNode(currentSourceFile, node.name); while (node.body.kind !== SyntaxKind.ModuleBlock) { node = node.body; diff --git a/src/compiler/diagnosticInformationMap.generated.ts b/src/compiler/diagnosticInformationMap.generated.ts index a51d3b1a222..2b5e1daf760 100644 --- a/src/compiler/diagnosticInformationMap.generated.ts +++ b/src/compiler/diagnosticInformationMap.generated.ts @@ -1,7 +1,7 @@ // /// /* @internal */ -module ts { +namespace ts { export var Diagnostics = { Unterminated_string_literal: { code: 1002, category: DiagnosticCategory.Error, key: "Unterminated string literal." }, Identifier_expected: { code: 1003, category: DiagnosticCategory.Error, key: "Identifier expected." }, @@ -120,7 +120,7 @@ module ts { Unterminated_template_literal: { code: 1160, category: DiagnosticCategory.Error, key: "Unterminated template literal." }, Unterminated_regular_expression_literal: { code: 1161, category: DiagnosticCategory.Error, key: "Unterminated regular expression literal." }, An_object_member_cannot_be_declared_optional: { code: 1162, category: DiagnosticCategory.Error, key: "An object member cannot be declared optional." }, - yield_expression_must_be_contained_within_a_generator_declaration: { code: 1163, category: DiagnosticCategory.Error, key: "'yield' expression must be contained_within a generator declaration." }, + A_yield_expression_is_only_allowed_in_a_generator_body: { code: 1163, category: DiagnosticCategory.Error, key: "A 'yield' expression is only allowed in a generator body." }, Computed_property_names_are_not_allowed_in_enums: { code: 1164, category: DiagnosticCategory.Error, key: "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: DiagnosticCategory.Error, key: "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: DiagnosticCategory.Error, key: "A computed property name in a class property declaration must directly refer to a built-in symbol." }, @@ -165,22 +165,38 @@ module ts { Decorators_are_only_available_when_targeting_ECMAScript_5_and_higher: { code: 1205, category: DiagnosticCategory.Error, key: "Decorators are only available when targeting ECMAScript 5 and higher." }, Decorators_are_not_valid_here: { code: 1206, category: DiagnosticCategory.Error, key: "Decorators are not valid here." }, Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name: { code: 1207, category: DiagnosticCategory.Error, key: "Decorators cannot be applied to multiple get/set accessors of the same name." }, - Cannot_compile_namespaces_when_the_separateCompilation_flag_is_provided: { code: 1208, category: DiagnosticCategory.Error, key: "Cannot compile namespaces when the '--separateCompilation' flag is provided." }, - Ambient_const_enums_are_not_allowed_when_the_separateCompilation_flag_is_provided: { code: 1209, category: DiagnosticCategory.Error, key: "Ambient const enums are not allowed when the '--separateCompilation' flag is provided." }, + Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided: { code: 1208, category: DiagnosticCategory.Error, key: "Cannot compile namespaces when the '--isolatedModules' flag is provided." }, + Ambient_const_enums_are_not_allowed_when_the_isolatedModules_flag_is_provided: { code: 1209, category: DiagnosticCategory.Error, key: "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: DiagnosticCategory.Error, key: "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: DiagnosticCategory.Error, key: "A class declaration without the 'default' modifier must have a name" }, Identifier_expected_0_is_a_reserved_word_in_strict_mode: { code: 1212, category: DiagnosticCategory.Error, key: "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: DiagnosticCategory.Error, key: "Identifier expected. '{0}' is a reserved word in strict mode. Class definitions are automatically in strict mode." }, - Type_expected_0_is_a_reserved_word_in_strict_mode: { code: 1215, category: DiagnosticCategory.Error, key: "Type expected. '{0}' is a reserved word in strict mode" }, - Type_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_strict_mode: { code: 1216, category: DiagnosticCategory.Error, key: "Type 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: DiagnosticCategory.Error, key: "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: DiagnosticCategory.Error, key: "Invalid use of '{0}'. Modules are automatically in strict mode." }, Export_assignment_is_not_supported_when_module_flag_is_system: { code: 1218, category: DiagnosticCategory.Error, key: "Export assignment is not supported when '--module' flag is 'system'." }, - _0_tag_already_specified: { code: 1219, category: DiagnosticCategory.Error, key: "'{0}' tag already specified." }, - The_return_type_of_a_property_decorator_function_must_be_either_void_or_any: { code: 1220, category: DiagnosticCategory.Error, key: "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: 1221, category: DiagnosticCategory.Error, key: "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: 1222, category: DiagnosticCategory.Error, key: "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: 1223, category: DiagnosticCategory.Error, key: "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: 1224, category: DiagnosticCategory.Error, key: "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: 1225, category: DiagnosticCategory.Error, key: "Unable to resolve signature of method decorator when called as an expression." }, + Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Specify_experimentalDecorators_to_remove_this_warning: { code: 1219, category: DiagnosticCategory.Error, key: "Experimental support for decorators is a feature that is subject to change in a future release. Specify '--experimentalDecorators' to remove this warning." }, + Generators_are_only_available_when_targeting_ECMAScript_6_or_higher: { code: 1220, category: DiagnosticCategory.Error, key: "Generators are only available when targeting ECMAScript 6 or higher." }, + Generators_are_not_allowed_in_an_ambient_context: { code: 1221, category: DiagnosticCategory.Error, key: "Generators are not allowed in an ambient context." }, + An_overload_signature_cannot_be_declared_as_a_generator: { code: 1222, category: DiagnosticCategory.Error, key: "An overload signature cannot be declared as a generator." }, + _0_tag_already_specified: { code: 1223, category: DiagnosticCategory.Error, key: "'{0}' tag already specified." }, + Signature_0_must_have_a_type_predicate: { code: 1224, category: DiagnosticCategory.Error, key: "Signature '{0}' must have a type predicate." }, + Cannot_find_parameter_0: { code: 1225, category: DiagnosticCategory.Error, key: "Cannot find parameter '{0}'." }, + Type_predicate_0_is_not_assignable_to_1: { code: 1226, category: DiagnosticCategory.Error, key: "Type predicate '{0}' is not assignable to '{1}'." }, + Parameter_0_is_not_in_the_same_position_as_parameter_1: { code: 1227, category: DiagnosticCategory.Error, key: "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: DiagnosticCategory.Error, key: "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: DiagnosticCategory.Error, key: "A type predicate cannot reference a rest parameter." }, + A_type_predicate_cannot_reference_element_0_in_a_binding_pattern: { code: 1230, category: DiagnosticCategory.Error, key: "A type predicate cannot reference element '{0}' in a binding pattern." }, + An_export_assignment_can_only_be_used_in_a_module: { code: 1231, category: DiagnosticCategory.Error, key: "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: DiagnosticCategory.Error, key: "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: DiagnosticCategory.Error, key: "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: DiagnosticCategory.Error, key: "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: DiagnosticCategory.Error, key: "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: DiagnosticCategory.Error, key: "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: DiagnosticCategory.Error, key: "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: DiagnosticCategory.Error, key: "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: DiagnosticCategory.Error, key: "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: DiagnosticCategory.Error, key: "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: DiagnosticCategory.Error, key: "Unable to resolve signature of method decorator when called as an expression." }, Duplicate_identifier_0: { code: 2300, category: DiagnosticCategory.Error, key: "Duplicate identifier '{0}'." }, Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor: { code: 2301, category: DiagnosticCategory.Error, key: "Initializer of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor." }, Static_members_cannot_reference_class_type_parameters: { code: 2302, category: DiagnosticCategory.Error, key: "Static members cannot reference class type parameters." }, @@ -372,6 +388,13 @@ module ts { A_rest_element_cannot_contain_a_binding_pattern: { code: 2501, category: DiagnosticCategory.Error, key: "A rest element cannot contain a binding pattern." }, _0_is_referenced_directly_or_indirectly_in_its_own_type_annotation: { code: 2502, category: DiagnosticCategory.Error, key: "'{0}' is referenced directly or indirectly in its own type annotation." }, Cannot_find_namespace_0: { code: 2503, category: DiagnosticCategory.Error, key: "Cannot find namespace '{0}'." }, + No_best_common_type_exists_among_yield_expressions: { code: 2504, category: DiagnosticCategory.Error, key: "No best common type exists among yield expressions." }, + A_generator_cannot_have_a_void_type_annotation: { code: 2505, category: DiagnosticCategory.Error, key: "A generator cannot have a 'void' type annotation." }, + _0_is_referenced_directly_or_indirectly_in_its_own_base_expression: { code: 2506, category: DiagnosticCategory.Error, key: "'{0}' is referenced directly or indirectly in its own base expression." }, + Type_0_is_not_a_constructor_function_type: { code: 2507, category: DiagnosticCategory.Error, key: "Type '{0}' is not a constructor function type." }, + No_base_constructor_has_the_specified_number_of_type_arguments: { code: 2508, category: DiagnosticCategory.Error, key: "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: DiagnosticCategory.Error, key: "Base constructor return type '{0}' is not a class or interface type." }, + Base_constructors_must_all_have_the_same_return_type: { code: 2510, category: DiagnosticCategory.Error, key: "Base constructors must all have the same return type." }, Import_declaration_0_is_using_private_name_1: { code: 4000, category: DiagnosticCategory.Error, key: "Import declaration '{0}' is using private name '{1}'." }, Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: { code: 4002, category: DiagnosticCategory.Error, key: "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: DiagnosticCategory.Error, key: "Type parameter '{0}' of exported interface has or is using private name '{1}'." }, @@ -456,11 +479,11 @@ module ts { Option_noEmit_cannot_be_specified_with_option_out_or_outDir: { code: 5040, category: DiagnosticCategory.Error, key: "Option 'noEmit' cannot be specified with option 'out' or 'outDir'." }, Option_noEmit_cannot_be_specified_with_option_declaration: { code: 5041, category: DiagnosticCategory.Error, key: "Option 'noEmit' cannot be specified with option 'declaration'." }, Option_project_cannot_be_mixed_with_source_files_on_a_command_line: { code: 5042, category: DiagnosticCategory.Error, key: "Option 'project' cannot be mixed with source files on a command line." }, - Option_sourceMap_cannot_be_specified_with_option_separateCompilation: { code: 5043, category: DiagnosticCategory.Error, key: "Option 'sourceMap' cannot be specified with option 'separateCompilation'." }, - Option_declaration_cannot_be_specified_with_option_separateCompilation: { code: 5044, category: DiagnosticCategory.Error, key: "Option 'declaration' cannot be specified with option 'separateCompilation'." }, - Option_noEmitOnError_cannot_be_specified_with_option_separateCompilation: { code: 5045, category: DiagnosticCategory.Error, key: "Option 'noEmitOnError' cannot be specified with option 'separateCompilation'." }, - Option_out_cannot_be_specified_with_option_separateCompilation: { code: 5046, category: DiagnosticCategory.Error, key: "Option 'out' cannot be specified with option 'separateCompilation'." }, - Option_separateCompilation_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES6_or_higher: { code: 5047, category: DiagnosticCategory.Error, key: "Option 'separateCompilation' can only be used when either option'--module' is provided or option 'target' is 'ES6' or higher." }, + Option_sourceMap_cannot_be_specified_with_option_isolatedModules: { code: 5043, category: DiagnosticCategory.Error, key: "Option 'sourceMap' cannot be specified with option 'isolatedModules'." }, + Option_declaration_cannot_be_specified_with_option_isolatedModules: { code: 5044, category: DiagnosticCategory.Error, key: "Option 'declaration' cannot be specified with option 'isolatedModules'." }, + Option_noEmitOnError_cannot_be_specified_with_option_isolatedModules: { code: 5045, category: DiagnosticCategory.Error, key: "Option 'noEmitOnError' cannot be specified with option 'isolatedModules'." }, + Option_out_cannot_be_specified_with_option_isolatedModules: { code: 5046, category: DiagnosticCategory.Error, key: "Option 'out' cannot be specified with option 'isolatedModules'." }, + Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES6_or_higher: { code: 5047, category: DiagnosticCategory.Error, key: "Option 'isolatedModules' can only be used when either option'--module' is provided or option 'target' is 'ES6' or higher." }, Option_sourceMap_cannot_be_specified_with_option_inlineSourceMap: { code: 5048, category: DiagnosticCategory.Error, key: "Option 'sourceMap' cannot be specified with option 'inlineSourceMap'." }, Option_sourceRoot_cannot_be_specified_with_option_inlineSourceMap: { code: 5049, category: DiagnosticCategory.Error, key: "Option 'sourceRoot' cannot be specified with option 'inlineSourceMap'." }, Option_mapRoot_cannot_be_specified_with_option_inlineSourceMap: { code: 5050, category: DiagnosticCategory.Error, key: "Option 'mapRoot' cannot be specified with option 'inlineSourceMap'." }, @@ -514,6 +537,9 @@ module ts { Specifies_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix: { code: 6060, category: DiagnosticCategory.Message, key: "Specifies the end of line sequence to be used when emitting files: 'CRLF' (dos) or 'LF' (unix)." }, NEWLINE: { code: 6061, category: DiagnosticCategory.Message, key: "NEWLINE" }, Argument_for_newLine_option_must_be_CRLF_or_LF: { code: 6062, category: DiagnosticCategory.Error, key: "Argument for '--newLine' option must be 'CRLF' or 'LF'." }, + Option_experimentalDecorators_must_also_be_specified_when_option_emitDecoratorMetadata_is_specified: { code: 6064, category: DiagnosticCategory.Error, key: "Option 'experimentalDecorators' must also be specified when option 'emitDecoratorMetadata' is specified." }, + Enables_experimental_support_for_ES7_decorators: { code: 6065, category: DiagnosticCategory.Message, key: "Enables experimental support for ES7 decorators." }, + Enables_experimental_support_for_emitting_type_metadata_for_decorators: { code: 6066, category: DiagnosticCategory.Message, key: "Enables experimental support for emitting type metadata for decorators." }, Variable_0_implicitly_has_an_1_type: { code: 7005, category: DiagnosticCategory.Error, key: "Variable '{0}' implicitly has an '{1}' type." }, Parameter_0_implicitly_has_an_1_type: { code: 7006, category: DiagnosticCategory.Error, key: "Parameter '{0}' implicitly has an '{1}' type." }, Member_0_implicitly_has_an_1_type: { code: 7008, category: DiagnosticCategory.Error, key: "Member '{0}' implicitly has an '{1}' type." }, @@ -526,9 +552,10 @@ module ts { Object_literal_s_property_0_implicitly_has_an_1_type: { code: 7018, category: DiagnosticCategory.Error, key: "Object literal's property '{0}' implicitly has an '{1}' type." }, Rest_parameter_0_implicitly_has_an_any_type: { code: 7019, category: DiagnosticCategory.Error, key: "Rest parameter '{0}' implicitly has an 'any[]' type." }, Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type: { code: 7020, category: DiagnosticCategory.Error, key: "Call signature, which lacks return-type annotation, implicitly has an 'any' return type." }, - _0_implicitly_has_type_any_because_it_is_does_not_have_a_type_annotation_and_is_referenced_directly_or_indirectly_in_its_own_initializer: { code: 7022, category: DiagnosticCategory.Error, key: "'{0}' implicitly has type 'any' because it is does not have a type annotation and is referenced directly or indirectly in its own initializer." }, + _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: DiagnosticCategory.Error, key: "'{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: DiagnosticCategory.Error, key: "'{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: DiagnosticCategory.Error, key: "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: DiagnosticCategory.Error, key: "Generator implicitly has type '{0}' because it does not yield any values. Consider supplying a return type." }, You_cannot_rename_this_element: { code: 8000, category: DiagnosticCategory.Error, key: "You cannot rename this element." }, You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library: { code: 8001, category: DiagnosticCategory.Error, key: "You cannot rename elements that are defined in the standard TypeScript library." }, import_can_only_be_used_in_a_ts_file: { code: 8002, category: DiagnosticCategory.Error, key: "'import ... =' can only be used in a .ts file." }, @@ -546,10 +573,7 @@ module ts { enum_declarations_can_only_be_used_in_a_ts_file: { code: 8015, category: DiagnosticCategory.Error, key: "'enum declarations' can only be used in a .ts file." }, type_assertion_expressions_can_only_be_used_in_a_ts_file: { code: 8016, category: DiagnosticCategory.Error, key: "'type assertion expressions' can only be used in a .ts file." }, decorators_can_only_be_used_in_a_ts_file: { code: 8017, category: DiagnosticCategory.Error, key: "'decorators' can only be used in a .ts file." }, - yield_expressions_are_not_currently_supported: { code: 9000, category: DiagnosticCategory.Error, key: "'yield' expressions are not currently supported." }, - Generators_are_not_currently_supported: { code: 9001, category: DiagnosticCategory.Error, key: "Generators are not currently supported." }, Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_class_extends_clauses: { code: 9002, category: DiagnosticCategory.Error, key: "Only identifiers/qualified-names with optional type arguments are currently supported in a class 'extends' clauses." }, class_expressions_are_not_currently_supported: { code: 9003, category: DiagnosticCategory.Error, key: "'class' expressions are not currently supported." }, - class_declarations_are_only_supported_directly_inside_a_module_or_as_a_top_level_declaration: { code: 9004, category: DiagnosticCategory.Error, key: "'class' declarations are only supported directly inside a module or as a top level declaration." }, }; } \ No newline at end of file diff --git a/src/compiler/diagnosticMessages.json b/src/compiler/diagnosticMessages.json index d3c77d178ee..b3b042d1d9a 100644 --- a/src/compiler/diagnosticMessages.json +++ b/src/compiler/diagnosticMessages.json @@ -467,7 +467,7 @@ "category": "Error", "code": 1162 }, - "'yield' expression must be contained_within a generator declaration.": { + "A 'yield' expression is only allowed in a generator body.": { "category": "Error", "code": 1163 }, @@ -647,11 +647,11 @@ "category": "Error", "code": 1207 }, - "Cannot compile namespaces when the '--separateCompilation' flag is provided.": { + "Cannot compile namespaces when the '--isolatedModules' flag is provided.": { "category": "Error", "code": 1208 }, - "Ambient const enums are not allowed when the '--separateCompilation' flag is provided.": { + "Ambient const enums are not allowed when the '--isolatedModules' flag is provided.": { "category": "Error", "code": 1209 }, @@ -671,46 +671,112 @@ "category": "Error", "code": 1213 }, - "Type expected. '{0}' is a reserved word in strict mode": { + "Identifier expected. '{0}' is a reserved word in strict mode. Modules are automatically in strict mode.": { + "category": "Error", + "code": 1214 + }, + "Invalid use of '{0}'. Modules are automatically in strict mode.": { "category": "Error", "code": 1215 }, - "Type expected. '{0}' is a reserved word in strict mode. Class definitions are automatically in strict mode.": { - "category": "Error", - "code": 1216 - }, "Export assignment is not supported when '--module' flag is 'system'.": { "category": "Error", "code": 1218 }, - "'{0}' tag already specified.": { + "Experimental support for decorators is a feature that is subject to change in a future release. Specify '--experimentalDecorators' to remove this warning.": { "category": "Error", "code": 1219 - }, - "The return type of a property decorator function must be either 'void' or 'any'.": { + }, + "Generators are only available when targeting ECMAScript 6 or higher.": { "category": "Error", "code": 1220 }, - "The return type of a parameter decorator function must be either 'void' or 'any'.": { + "Generators are not allowed in an ambient context.": { "category": "Error", "code": 1221 }, - "Unable to resolve signature of class decorator when called as an expression.": { + "An overload signature cannot be declared as a generator.": { "category": "Error", "code": 1222 }, - "Unable to resolve signature of parameter decorator when called as an expression.": { + "'{0}' tag already specified.": { "category": "Error", "code": 1223 }, - "Unable to resolve signature of property decorator when called as an expression.": { + "Signature '{0}' must have a type predicate.": { "category": "Error", "code": 1224 }, - "Unable to resolve signature of method decorator when called as an expression.": { + "Cannot find parameter '{0}'.": { "category": "Error", "code": 1225 }, + "Type predicate '{0}' is not assignable to '{1}'.": { + "category": "Error", + "code": 1226 + }, + "Parameter '{0}' is not in the same position as parameter '{1}'.": { + "category": "Error", + "code": 1227 + }, + "A type predicate is only allowed in return type position for functions and methods.": { + "category": "Error", + "code": 1228 + }, + "A type predicate cannot reference a rest parameter.": { + "category": "Error", + "code": 1229 + }, + "A type predicate cannot reference element '{0}' in a binding pattern.": { + "category": "Error", + "code": 1230 + }, + "An export assignment can only be used in a module.": { + "category": "Error", + "code": 1231 + }, + "An import declaration can only be used in a namespace or module.": { + "category": "Error", + "code": 1232 + }, + "An export declaration can only be used in a module.": { + "category": "Error", + "code": 1233 + }, + "An ambient module declaration is only allowed at the top level in a file.": { + "category": "Error", + "code": 1234 + }, + "A namespace declaration is only allowed in a namespace or module.": { + "category": "Error", + "code": 1235 + }, + + + "The return type of a property decorator function must be either 'void' or 'any'.": { + "category": "Error", + "code": 1236 + }, + "The return type of a parameter decorator function must be either 'void' or 'any'.": { + "category": "Error", + "code": 1237 + }, + "Unable to resolve signature of class decorator when called as an expression.": { + "category": "Error", + "code": 1238 + }, + "Unable to resolve signature of parameter decorator when called as an expression.": { + "category": "Error", + "code": 1239 + }, + "Unable to resolve signature of property decorator when called as an expression.": { + "category": "Error", + "code": 1240 + }, + "Unable to resolve signature of method decorator when called as an expression.": { + "category": "Error", + "code": 1241 + }, "Duplicate identifier '{0}'.": { "category": "Error", @@ -1476,6 +1542,34 @@ "category": "Error", "code": 2503 }, + "No best common type exists among yield expressions.": { + "category": "Error", + "code": 2504 + }, + "A generator cannot have a 'void' type annotation.": { + "category": "Error", + "code": 2505 + }, + "'{0}' is referenced directly or indirectly in its own base expression.": { + "category": "Error", + "code": 2506 + }, + "Type '{0}' is not a constructor function type.": { + "category": "Error", + "code": 2507 + }, + "No base constructor has the specified number of type arguments.": { + "category": "Error", + "code": 2508 + }, + "Base constructor return type '{0}' is not a class or interface type.": { + "category": "Error", + "code": 2509 + }, + "Base constructors must all have the same return type.": { + "category": "Error", + "code": 2510 + }, "Import declaration '{0}' is using private name '{1}'.": { "category": "Error", @@ -1813,23 +1907,23 @@ "category": "Error", "code": 5042 }, - "Option 'sourceMap' cannot be specified with option 'separateCompilation'.": { + "Option 'sourceMap' cannot be specified with option 'isolatedModules'.": { "category": "Error", "code": 5043 }, - "Option 'declaration' cannot be specified with option 'separateCompilation'.": { + "Option 'declaration' cannot be specified with option 'isolatedModules'.": { "category": "Error", "code": 5044 }, - "Option 'noEmitOnError' cannot be specified with option 'separateCompilation'.": { + "Option 'noEmitOnError' cannot be specified with option 'isolatedModules'.": { "category": "Error", "code": 5045 }, - "Option 'out' cannot be specified with option 'separateCompilation'.": { + "Option 'out' cannot be specified with option 'isolatedModules'.": { "category": "Error", "code": 5046 }, - "Option 'separateCompilation' can only be used when either option'--module' is provided or option 'target' is 'ES6' or higher.": { + "Option 'isolatedModules' can only be used when either option'--module' is provided or option 'target' is 'ES6' or higher.": { "category": "Error", "code": 5047 }, @@ -2046,7 +2140,18 @@ "category": "Error", "code": 6062 }, - + "Option 'experimentalDecorators' must also be specified when option 'emitDecoratorMetadata' is specified.": { + "category": "Error", + "code": 6064 + }, + "Enables experimental support for ES7 decorators.": { + "category": "Message", + "code": 6065 + }, + "Enables experimental support for emitting type metadata for decorators.": { + "category": "Message", + "code": 6066 + }, "Variable '{0}' implicitly has an '{1}' type.": { "category": "Error", @@ -2096,7 +2201,7 @@ "category": "Error", "code": 7020 }, - "'{0}' implicitly has type 'any' because it is does not have a type annotation and is referenced directly or indirectly in its own initializer.": { + "'{0}' implicitly has type 'any' because it does not have a type annotation and is referenced directly or indirectly in its own initializer.": { "category": "Error", "code": 7022 }, @@ -2108,6 +2213,10 @@ "category": "Error", "code": 7024 }, + "Generator implicitly has type '{0}' because it does not yield any values. Consider supplying a return type.": { + "category": "Error", + "code": 7025 + }, "You cannot rename this element.": { "category": "Error", "code": 8000 @@ -2177,14 +2286,6 @@ "code": 8017 }, - "'yield' expressions are not currently supported.": { - "category": "Error", - "code": 9000 - }, - "Generators are not currently supported.": { - "category": "Error", - "code": 9001 - }, "Only identifiers/qualified-names with optional type arguments are currently supported in a class 'extends' clauses.": { "category": "Error", "code": 9002 @@ -2192,9 +2293,5 @@ "'class' expressions are not currently supported.": { "category": "Error", "code": 9003 - }, - "'class' declarations are only supported directly inside a module or as a top level declaration.": { - "category": "Error", - "code": 9004 } } diff --git a/src/compiler/emitter.ts b/src/compiler/emitter.ts index 32ebeaec08f..3fbe640254f 100644 --- a/src/compiler/emitter.ts +++ b/src/compiler/emitter.ts @@ -2,7 +2,7 @@ /// /* @internal */ -module ts { +namespace ts { export function isExternalModuleOrDeclarationFile(sourceFile: SourceFile) { return isExternalModule(sourceFile) || isDeclarationFile(sourceFile); } @@ -21,8 +21,7 @@ module ts { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); };`; // emit output for the __decorate helper function @@ -125,7 +124,6 @@ var __param = (this && this.__param) || function (paramIndex, decorator) { let generatedNameSet: Map = {}; let nodeToGeneratedName: string[] = []; - let blockScopedVariableToGeneratedName: string[]; let computedPropertyNamesToGeneratedNames: string[]; let extendsEmitted = false; @@ -249,81 +247,44 @@ var __param = (this && this.__param) || function (paramIndex, decorator) { } } - function assignGeneratedName(node: Node, name: string) { - nodeToGeneratedName[getNodeId(node)] = unescapeIdentifier(name); - } - - function generateNameForFunctionOrClassDeclaration(node: Declaration) { - if (!node.name) { - assignGeneratedName(node, makeUniqueName("default")); - } - } - function generateNameForModuleOrEnum(node: ModuleDeclaration | EnumDeclaration) { - if (node.name.kind === SyntaxKind.Identifier) { - let name = node.name.text; - // Use module/enum name itself if it is unique, otherwise make a unique variation - assignGeneratedName(node, isUniqueLocalName(name, node) ? name : makeUniqueName(name)); - } + let name = node.name.text; + // Use module/enum name itself if it is unique, otherwise make a unique variation + return isUniqueLocalName(name, node) ? name : makeUniqueName(name); } function generateNameForImportOrExportDeclaration(node: ImportDeclaration | ExportDeclaration) { let expr = getExternalModuleName(node); let baseName = expr.kind === SyntaxKind.StringLiteral ? escapeIdentifier(makeIdentifierFromModuleName((expr).text)) : "module"; - assignGeneratedName(node, makeUniqueName(baseName)); + return makeUniqueName(baseName); } - function generateNameForImportDeclaration(node: ImportDeclaration) { - if (node.importClause) { - generateNameForImportOrExportDeclaration(node); - } - } - - function generateNameForExportDeclaration(node: ExportDeclaration) { - if (node.moduleSpecifier) { - generateNameForImportOrExportDeclaration(node); - } - } - - function generateNameForExportAssignment(node: ExportAssignment) { - if (node.expression && node.expression.kind !== SyntaxKind.Identifier) { - assignGeneratedName(node, makeUniqueName("default")); - } + function generateNameForExportDefault() { + return makeUniqueName("default"); } function generateNameForNode(node: Node) { switch (node.kind) { + case SyntaxKind.Identifier: + return makeUniqueName((node).text); + case SyntaxKind.ModuleDeclaration: + case SyntaxKind.EnumDeclaration: + return generateNameForModuleOrEnum(node); + case SyntaxKind.ImportDeclaration: + case SyntaxKind.ExportDeclaration: + return generateNameForImportOrExportDeclaration(node); case SyntaxKind.FunctionDeclaration: case SyntaxKind.ClassDeclaration: case SyntaxKind.ClassExpression: - generateNameForFunctionOrClassDeclaration(node); - break; - case SyntaxKind.ModuleDeclaration: - generateNameForModuleOrEnum(node); - generateNameForNode((node).body); - break; - case SyntaxKind.EnumDeclaration: - generateNameForModuleOrEnum(node); - break; - case SyntaxKind.ImportDeclaration: - generateNameForImportDeclaration(node); - break; - case SyntaxKind.ExportDeclaration: - generateNameForExportDeclaration(node); - break; case SyntaxKind.ExportAssignment: - generateNameForExportAssignment(node); - break; + return generateNameForExportDefault(); } } function getGeneratedNameForNode(node: Node) { - let nodeId = getNodeId(node); - if (!nodeToGeneratedName[nodeId]) { - generateNameForNode(node); - } - return nodeToGeneratedName[nodeId]; + let id = getNodeId(node); + return nodeToGeneratedName[id] || (nodeToGeneratedName[id] = unescapeIdentifier(generateNameForNode(node))); } function initializeEmitterWithSourceMaps() { @@ -358,7 +319,7 @@ var __param = (this && this.__param) || function (paramIndex, decorator) { let prevEncodedEmittedColumn = lastEncodedSourceMapSpan.emittedColumn; // Line/Comma delimiters - if (lastEncodedSourceMapSpan.emittedLine == lastRecordedSourceMapSpan.emittedLine) { + if (lastEncodedSourceMapSpan.emittedLine === lastRecordedSourceMapSpan.emittedLine) { // Emit comma to separate the entry if (sourceMapData.sourceMapMappings) { sourceMapData.sourceMapMappings += ","; @@ -441,8 +402,8 @@ var __param = (this && this.__param) || function (paramIndex, decorator) { // If this location wasn't recorded or the location in source is going backwards, record the span if (!lastRecordedSourceMapSpan || - lastRecordedSourceMapSpan.emittedLine != emittedLine || - lastRecordedSourceMapSpan.emittedColumn != emittedColumn || + lastRecordedSourceMapSpan.emittedLine !== emittedLine || + lastRecordedSourceMapSpan.emittedColumn !== emittedColumn || (lastRecordedSourceMapSpan.sourceIndex === sourceMapSourceIndex && (lastRecordedSourceMapSpan.sourceLine > sourceLinePos.line || (lastRecordedSourceMapSpan.sourceLine === sourceLinePos.line && lastRecordedSourceMapSpan.sourceColumn > sourceLinePos.character)))) { @@ -687,19 +648,19 @@ var __param = (this && this.__param) || function (paramIndex, decorator) { sourceMapDir = getDirectoryPath(normalizePath(jsFilePath)); } - function emitNodeWithSourceMap(node: Node, allowGeneratedIdentifiers?: boolean) { + function emitNodeWithSourceMap(node: Node) { if (node) { if (nodeIsSynthesized(node)) { - return emitNodeWithoutSourceMap(node, /*allowGeneratedIdentifiers*/ false); + return emitNodeWithoutSourceMap(node); } - if (node.kind != SyntaxKind.SourceFile) { + if (node.kind !== SyntaxKind.SourceFile) { recordEmitNodeStartSpan(node); - emitNodeWithoutSourceMap(node, allowGeneratedIdentifiers); + emitNodeWithoutSourceMap(node); recordEmitNodeEndSpan(node); } else { recordNewSourceFileStart(node); - emitNodeWithoutSourceMap(node, /*allowGeneratedIdentifiers*/ false); + emitNodeWithoutSourceMap(node); } } } @@ -1201,80 +1162,129 @@ var __param = (this && this.__param) || function (paramIndex, decorator) { } } - function isNotExpressionIdentifier(node: Identifier) { + function isExpressionIdentifier(node: Node): boolean { let parent = node.parent; switch (parent.kind) { - case SyntaxKind.Parameter: - case SyntaxKind.VariableDeclaration: - case SyntaxKind.BindingElement: - case SyntaxKind.PropertyDeclaration: - case SyntaxKind.PropertySignature: - case SyntaxKind.PropertyAssignment: - case SyntaxKind.ShorthandPropertyAssignment: - case SyntaxKind.EnumMember: - case SyntaxKind.MethodDeclaration: - case SyntaxKind.MethodSignature: - case SyntaxKind.FunctionDeclaration: - case SyntaxKind.GetAccessor: - case SyntaxKind.SetAccessor: - case SyntaxKind.FunctionExpression: - case SyntaxKind.ClassDeclaration: - case SyntaxKind.InterfaceDeclaration: - case SyntaxKind.EnumDeclaration: - case SyntaxKind.ModuleDeclaration: - case SyntaxKind.ImportEqualsDeclaration: - case SyntaxKind.ImportClause: - case SyntaxKind.NamespaceImport: - return (parent).name === node; - case SyntaxKind.ImportSpecifier: - case SyntaxKind.ExportSpecifier: - return (parent).name === node || (parent).propertyName === node; - case SyntaxKind.BreakStatement: - case SyntaxKind.ContinueStatement: + case SyntaxKind.ArrayLiteralExpression: + case SyntaxKind.BinaryExpression: + case SyntaxKind.CallExpression: + case SyntaxKind.CaseClause: + case SyntaxKind.ComputedPropertyName: + case SyntaxKind.ConditionalExpression: + case SyntaxKind.Decorator: + case SyntaxKind.DeleteExpression: + case SyntaxKind.DoStatement: + case SyntaxKind.ElementAccessExpression: case SyntaxKind.ExportAssignment: - return false; - case SyntaxKind.LabeledStatement: - return (node.parent).label === node; + case SyntaxKind.ExpressionStatement: + case SyntaxKind.ExpressionWithTypeArguments: + case SyntaxKind.ForStatement: + case SyntaxKind.ForInStatement: + case SyntaxKind.ForOfStatement: + case SyntaxKind.IfStatement: + case SyntaxKind.NewExpression: + case SyntaxKind.ParenthesizedExpression: + case SyntaxKind.PostfixUnaryExpression: + case SyntaxKind.PrefixUnaryExpression: + case SyntaxKind.ReturnStatement: + case SyntaxKind.ShorthandPropertyAssignment: + case SyntaxKind.SpreadElementExpression: + case SyntaxKind.SwitchStatement: + case SyntaxKind.TaggedTemplateExpression: + case SyntaxKind.TemplateSpan: + case SyntaxKind.ThrowStatement: + case SyntaxKind.TypeAssertionExpression: + case SyntaxKind.TypeOfExpression: + case SyntaxKind.VoidExpression: + case SyntaxKind.WhileStatement: + case SyntaxKind.WithStatement: + case SyntaxKind.YieldExpression: + return true; + case SyntaxKind.BindingElement: + case SyntaxKind.EnumMember: + case SyntaxKind.Parameter: + case SyntaxKind.PropertyAssignment: + case SyntaxKind.PropertyDeclaration: + case SyntaxKind.VariableDeclaration: + return (parent).initializer === node; + case SyntaxKind.PropertyAccessExpression: + return (parent).expression === node; + case SyntaxKind.ArrowFunction: + case SyntaxKind.FunctionExpression: + return (parent).body === node; + case SyntaxKind.ImportEqualsDeclaration: + return (parent).moduleReference === node; + case SyntaxKind.QualifiedName: + return (parent).left === node; } + return false; } function emitExpressionIdentifier(node: Identifier) { - let substitution = resolver.getExpressionNameSubstitution(node, getGeneratedNameForNode); - if (substitution) { - write(substitution); + let container = resolver.getReferencedExportContainer(node); + if (container) { + if (container.kind === SyntaxKind.SourceFile) { + // Identifier references module export + if (languageVersion < ScriptTarget.ES6 && compilerOptions.module !== ModuleKind.System) { + write("exports."); + } + } + else { + // Identifier references namespace export + write(getGeneratedNameForNode(container)); + write("."); + } } - else { - writeTextOfNode(currentSourceFile, node); - } - } - - function getGeneratedNameForIdentifier(node: Identifier): string { - if (nodeIsSynthesized(node) || !blockScopedVariableToGeneratedName) { - return undefined; - } - - var variableId = resolver.getBlockScopedVariableId(node) - if (variableId === undefined) { - return undefined; - } - - return blockScopedVariableToGeneratedName[variableId]; - } - - function emitIdentifier(node: Identifier, allowGeneratedIdentifiers: boolean) { - if (allowGeneratedIdentifiers) { - let generatedName = getGeneratedNameForIdentifier(node); - if (generatedName) { - write(generatedName); + else if (languageVersion < ScriptTarget.ES6) { + let declaration = resolver.getReferencedImportDeclaration(node); + if (declaration) { + if (declaration.kind === SyntaxKind.ImportClause) { + // Identifier references default import + write(getGeneratedNameForNode(declaration.parent)); + write(languageVersion === ScriptTarget.ES3 ? '["default"]' : ".default"); + return; + } + else if (declaration.kind === SyntaxKind.ImportSpecifier) { + // Identifier references named import + write(getGeneratedNameForNode(declaration.parent.parent.parent)); + write("."); + writeTextOfNode(currentSourceFile, (declaration).propertyName || (declaration).name); + return; + } + } + declaration = resolver.getReferencedNestedRedeclaration(node); + if (declaration) { + write(getGeneratedNameForNode(declaration.name)); return; } } + writeTextOfNode(currentSourceFile, node); + } + + function isNameOfNestedRedeclaration(node: Identifier) { + if (languageVersion < ScriptTarget.ES6) { + let parent = node.parent; + switch (parent.kind) { + case SyntaxKind.BindingElement: + case SyntaxKind.ClassDeclaration: + case SyntaxKind.EnumDeclaration: + case SyntaxKind.VariableDeclaration: + return (parent).name === node && resolver.isNestedRedeclaration(parent); + } + } + return false; + } + + function emitIdentifier(node: Identifier) { if (!node.parent) { write(node.text); } - else if (!isNotExpressionIdentifier(node)) { + else if (isExpressionIdentifier(node)) { emitExpressionIdentifier(node); } + else if (isNameOfNestedRedeclaration(node)) { + write(getGeneratedNameForNode(node)); + } else { writeTextOfNode(currentSourceFile, node); } @@ -1320,7 +1330,7 @@ var __param = (this && this.__param) || function (paramIndex, decorator) { function emitBindingElement(node: BindingElement) { if (node.propertyName) { - emit(node.propertyName, /*allowGeneratedIdentifiers*/ false); + emit(node.propertyName); write(": "); } if (node.dotDotDotToken) { @@ -1646,6 +1656,12 @@ var __param = (this && this.__param) || function (paramIndex, decorator) { } function parenthesizeForAccess(expr: Expression): LeftHandSideExpression { + // When diagnosing whether the expression needs parentheses, the decision should be based + // on the innermost expression in a chain of nested type assertions. + while (expr.kind === SyntaxKind.TypeAssertionExpression) { + expr = (expr).expression; + } + // isLeftHandSideExpression is almost the correct criterion for when it is not necessary // to parenthesize the expression before a dot. The known exceptions are: // @@ -1654,7 +1670,10 @@ var __param = (this && this.__param) || function (paramIndex, decorator) { // NumberLiteral // 1.x -> not the same as (1).x // - if (isLeftHandSideExpression(expr) && expr.kind !== SyntaxKind.NewExpression && expr.kind !== SyntaxKind.NumericLiteral) { + if (isLeftHandSideExpression(expr) && + expr.kind !== SyntaxKind.NewExpression && + expr.kind !== SyntaxKind.NumericLiteral) { + return expr; } let node = createSynthesizedNode(SyntaxKind.ParenthesizedExpression); @@ -1673,7 +1692,7 @@ var __param = (this && this.__param) || function (paramIndex, decorator) { write("*"); } - emit(node.name, /*allowGeneratedIdentifiers*/ false); + emit(node.name); if (languageVersion < ScriptTarget.ES6) { write(": function "); } @@ -1681,45 +1700,39 @@ var __param = (this && this.__param) || function (paramIndex, decorator) { } function emitPropertyAssignment(node: PropertyDeclaration) { - emit(node.name, /*allowGeneratedIdentifiers*/ false); + emit(node.name); write(": "); emit(node.initializer); } + // Return true if identifier resolves to an exported member of a namespace + function isNamespaceExportReference(node: Identifier) { + let container = resolver.getReferencedExportContainer(node); + return container && container.kind !== SyntaxKind.SourceFile; + } + function emitShorthandPropertyAssignment(node: ShorthandPropertyAssignment) { - emit(node.name, /*allowGeneratedIdentifiers*/ false); - // If short-hand property has a prefix, then regardless of the target version, we will emit it as normal property assignment. For example: - // module m { - // export let y; - // } - // module m { - // export let obj = { y }; - // } - // The short-hand property in obj need to emit as such ... = { y : m.y } regardless of the TargetScript version - if (languageVersion < ScriptTarget.ES6) { + // The name property of a short-hand property assignment is considered an expression position, so here + // we manually emit the identifier to avoid rewriting. + writeTextOfNode(currentSourceFile, node.name); + // If emitting pre-ES6 code, or if the name requires rewriting when resolved as an expression identifier, + // we emit a normal property assignment. For example: + // module m { + // export let y; + // } + // module m { + // let obj = { y }; + // } + // Here we need to emit obj = { y : m.y } regardless of the output target. + if (languageVersion < ScriptTarget.ES6 || isNamespaceExportReference(node.name)) { // Emit identifier as an identifier write(": "); - var generatedName = getGeneratedNameForIdentifier(node.name); - if (generatedName) { - write(generatedName); - } - else { - // Even though this is stored as identifier treat it as an expression - // Short-hand, { x }, is equivalent of normal form { x: x } - emitExpressionIdentifier(node.name); - } - } - else if (resolver.getExpressionNameSubstitution(node.name, getGeneratedNameForNode)) { - // Emit identifier as an identifier - write(": "); - // Even though this is stored as identifier treat it as an expression - // Short-hand, { x }, is equivalent of normal form { x: x } - emitExpressionIdentifier(node.name); + emit(node.name); } } function tryEmitConstantValue(node: PropertyAccessExpression | ElementAccessExpression): boolean { - if (compilerOptions.separateCompilation) { + if (compilerOptions.isolatedModules) { // do not inline enum values in separate compilation mode return false; } @@ -1767,7 +1780,7 @@ var __param = (this && this.__param) || function (paramIndex, decorator) { let indentedBeforeDot = indentIfOnDifferentLines(node, node.expression, node.dotToken); write("."); let indentedAfterDot = indentIfOnDifferentLines(node, node.dotToken, node.name); - emit(node.name, /*allowGeneratedIdentifiers*/ false); + emit(node.name); decreaseIndentIf(indentedBeforeDot, indentedAfterDot); } @@ -1889,23 +1902,21 @@ var __param = (this && this.__param) || function (paramIndex, decorator) { function emitNewExpression(node: NewExpression) { write("new "); - // Spread operator logic can be supported in new expressions in ES5 using a combination + // Spread operator logic is supported in new expressions in ES5 using a combination // of Function.prototype.bind() and Function.prototype.apply(). // // Example: // - // var arguments = [1, 2, 3, 4, 5]; - // new Array(...arguments); + // var args = [1, 2, 3, 4, 5]; + // new Array(...args); // - // Could be transpiled into ES5: + // is compiled into the following ES5: // - // var arguments = [1, 2, 3, 4, 5]; - // new (Array.bind.apply(Array, [void 0].concat(arguments))); + // var args = [1, 2, 3, 4, 5]; + // new (Array.bind.apply(Array, [void 0].concat(args))); // - // `[void 0]` is the first argument which represents `thisArg` to the bind method above. - // And `thisArg` will be set to the return value of the constructor when instantiated - // with the new operator — regardless of any value we set `thisArg` to. Thus, we set it - // to an undefined, `void 0`. + // The 'thisArg' to 'bind' is ignored when invoking the result of 'bind' with 'new', + // Thus, we set it to undefined ('void 0'). if (languageVersion === ScriptTarget.ES5 && node.arguments && hasSpreadElement(node.arguments)) { @@ -1941,13 +1952,16 @@ var __param = (this && this.__param) || function (paramIndex, decorator) { } function emitParenExpression(node: ParenthesizedExpression) { - if (!node.parent || node.parent.kind !== SyntaxKind.ArrowFunction) { + // 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 (!nodeIsSynthesized(node) && node.parent.kind !== SyntaxKind.ArrowFunction) { if (node.expression.kind === SyntaxKind.TypeAssertionExpression) { let operand = (node.expression).expression; // Make sure we consider all nested cast expressions, e.g.: // (-A).x; - while (operand.kind == SyntaxKind.TypeAssertionExpression) { + while (operand.kind === SyntaxKind.TypeAssertionExpression) { operand = (operand).expression; } @@ -2769,8 +2783,6 @@ var __param = (this && this.__param) || function (paramIndex, decorator) { write(", "); } - renameNonTopLevelLetAndConst(name); - const isVariableDeclarationOrBindingElement = name.parent && (name.parent.kind === SyntaxKind.VariableDeclaration || name.parent.kind === SyntaxKind.BindingElement); @@ -2838,11 +2850,14 @@ var __param = (this && this.__param) || function (paramIndex, decorator) { } function createPropertyAccessForDestructuringProperty(object: Expression, propName: Identifier | LiteralExpression): Expression { - if (propName.kind !== SyntaxKind.Identifier) { - return createElementAccessExpression(object, propName); + // We create a synthetic copy of the identifier in order to avoid the rewriting that might + // otherwise occur when the identifier is emitted. + let syntheticName = createSynthesizedNode(propName.kind); + syntheticName.text = propName.text; + if (syntheticName.kind !== SyntaxKind.Identifier) { + return createElementAccessExpression(object, syntheticName); } - - return createPropertyAccessExpression(object, propName); + return createPropertyAccessExpression(object, syntheticName); } function createSliceCall(value: Expression, sliceIndex: number): CallExpression { @@ -2864,8 +2879,7 @@ var __param = (this && this.__param) || function (paramIndex, decorator) { } for (let p of properties) { if (p.kind === SyntaxKind.PropertyAssignment || p.kind === SyntaxKind.ShorthandPropertyAssignment) { - // TODO(andersh): Computed property support - let propName = ((p).name); + let propName = (p).name; emitDestructuringAssignment((p).initializer || propName, createPropertyAccessForDestructuringProperty(value, propName)); } } @@ -2979,8 +2993,6 @@ var __param = (this && this.__param) || function (paramIndex, decorator) { } } else { - renameNonTopLevelLetAndConst(node.name); - let initializer = node.initializer; if (!initializer && languageVersion < ScriptTarget.ES6) { @@ -3040,54 +3052,6 @@ var __param = (this && this.__param) || function (paramIndex, decorator) { return getCombinedNodeFlags(node.parent); } - function renameNonTopLevelLetAndConst(node: Node): void { - // do not rename if - // - language version is ES6+ - // - node is synthesized - // - node is not identifier (can happen when tree is malformed) - // - node is definitely not name of variable declaration. - // it still can be part of parameter declaration, this check will be done next - if (languageVersion >= ScriptTarget.ES6 || - nodeIsSynthesized(node) || - node.kind !== SyntaxKind.Identifier || - (node.parent.kind !== SyntaxKind.VariableDeclaration && node.parent.kind !== SyntaxKind.BindingElement)) { - return; - } - - let combinedFlags = getCombinedFlagsForIdentifier(node); - if (((combinedFlags & NodeFlags.BlockScoped) === 0) || combinedFlags & NodeFlags.Export) { - // do not rename exported or non-block scoped variables - return; - } - - // here it is known that node is a block scoped variable - let list = getAncestor(node, SyntaxKind.VariableDeclarationList); - if (list.parent.kind === SyntaxKind.VariableStatement) { - let isSourceFileLevelBinding = list.parent.parent.kind === SyntaxKind.SourceFile; - let isModuleLevelBinding = list.parent.parent.kind === SyntaxKind.ModuleBlock; - let isFunctionLevelBinding = - list.parent.parent.kind === SyntaxKind.Block && isFunctionLike(list.parent.parent.parent); - if (isSourceFileLevelBinding || isModuleLevelBinding || isFunctionLevelBinding) { - return; - } - } - - let blockScopeContainer = getEnclosingBlockScopeContainer(node); - let parent = blockScopeContainer.kind === SyntaxKind.SourceFile - ? blockScopeContainer - : blockScopeContainer.parent; - - if (resolver.resolvesToSomeValue(parent, (node).text)) { - let variableId = resolver.getBlockScopedVariableId(node); - if (!blockScopedVariableToGeneratedName) { - blockScopedVariableToGeneratedName = []; - } - - let generatedName = makeUniqueName((node).text); - blockScopedVariableToGeneratedName[variableId] = generatedName; - } - } - function isES6ExportedDeclaration(node: Node) { return !!(node.flags & NodeFlags.Export) && languageVersion >= ScriptTarget.ES6 && @@ -3205,7 +3169,7 @@ var __param = (this && this.__param) || function (paramIndex, decorator) { } function emitRestParameter(node: FunctionLikeDeclaration) { - if (languageVersion < ScriptTarget.ES6 && hasRestParameters(node)) { + if (languageVersion < ScriptTarget.ES6 && hasRestParameter(node)) { let restIndex = node.parameters.length - 1; let restParam = node.parameters[restIndex]; @@ -3251,7 +3215,7 @@ var __param = (this && this.__param) || function (paramIndex, decorator) { function emitAccessor(node: AccessorDeclaration) { write(node.kind === SyntaxKind.GetAccessor ? "get " : "set "); - emit(node.name, /*allowGeneratedIdentifiers*/ false); + emit(node.name); emitSignatureAndBody(node); } @@ -3333,7 +3297,7 @@ var __param = (this && this.__param) || function (paramIndex, decorator) { write("("); if (node) { let parameters = node.parameters; - let omitCount = languageVersion < ScriptTarget.ES6 && hasRestParameters(node) ? 1 : 0; + let omitCount = languageVersion < ScriptTarget.ES6 && hasRestParameter(node) ? 1 : 0; emitList(parameters, 0, parameters.length - omitCount, /*multiLine*/ false, /*trailingComma*/ false); } write(")"); @@ -4354,7 +4318,7 @@ var __param = (this && this.__param) || function (paramIndex, decorator) { let argumentsWritten = 0; if (compilerOptions.emitDecoratorMetadata) { if (shouldEmitTypeMetadata(node)) { - var serializedType = resolver.serializeTypeOfNode(node, getGeneratedNameForNode); + var serializedType = resolver.serializeTypeOfNode(node); if (serializedType) { if (writeComma) { write(", "); @@ -4367,7 +4331,7 @@ var __param = (this && this.__param) || function (paramIndex, decorator) { } } if (shouldEmitParamTypesMetadata(node)) { - var serializedTypes = resolver.serializeParameterTypesOfNode(node, getGeneratedNameForNode); + var serializedTypes = resolver.serializeParameterTypesOfNode(node); if (serializedTypes) { if (writeComma || argumentsWritten) { write(", "); @@ -4385,7 +4349,7 @@ var __param = (this && this.__param) || function (paramIndex, decorator) { } } if (shouldEmitReturnTypeMetadata(node)) { - var serializedType = resolver.serializeReturnTypeOfNode(node, getGeneratedNameForNode); + var serializedType = resolver.serializeReturnTypeOfNode(node); if (serializedType) { if (writeComma || argumentsWritten) { write(", "); @@ -4430,7 +4394,7 @@ var __param = (this && this.__param) || function (paramIndex, decorator) { function shouldEmitEnumDeclaration(node: EnumDeclaration) { let isConstEnum = isConst(node); - return !isConstEnum || compilerOptions.preserveConstEnums || compilerOptions.separateCompilation; + return !isConstEnum || compilerOptions.preserveConstEnums || compilerOptions.isolatedModules; } function emitEnumDeclaration(node: EnumDeclaration) { @@ -4491,7 +4455,7 @@ var __param = (this && this.__param) || function (paramIndex, decorator) { emitDeclarationName(node); write(`", `); emitDeclarationName(node); - write(")"); + write(");"); } emitExportMemberAssignments(node.name); } @@ -4535,7 +4499,7 @@ var __param = (this && this.__param) || function (paramIndex, decorator) { } function shouldEmitModuleDeclaration(node: ModuleDeclaration) { - return isInstantiatedModule(node, compilerOptions.preserveConstEnums || compilerOptions.separateCompilation); + return isInstantiatedModule(node, compilerOptions.preserveConstEnums || compilerOptions.isolatedModules); } function isModuleMergedWithES6Class(node: ModuleDeclaration) { @@ -4612,7 +4576,7 @@ var __param = (this && this.__param) || function (paramIndex, decorator) { emitDeclarationName(node); write(`", `); emitDeclarationName(node); - write(")"); + write(");"); } emitExportMemberAssignments(node.name); } @@ -4983,13 +4947,16 @@ var __param = (this && this.__param) || function (paramIndex, decorator) { } } - function getLocalNameForExternalImport(importNode: ImportDeclaration | ExportDeclaration | ImportEqualsDeclaration): string { - let namespaceDeclaration = getNamespaceDeclarationNode(importNode); - if (namespaceDeclaration && !isDefaultImport(importNode)) { + function getLocalNameForExternalImport(node: ImportDeclaration | ExportDeclaration | ImportEqualsDeclaration): string { + let namespaceDeclaration = getNamespaceDeclarationNode(node); + if (namespaceDeclaration && !isDefaultImport(node)) { return getSourceTextOfNodeFromSourceFile(currentSourceFile, namespaceDeclaration.name); } - else { - return getGeneratedNameForNode(importNode); + if (node.kind === SyntaxKind.ImportDeclaration && (node).importClause) { + return getGeneratedNameForNode(node); + } + if (node.kind === SyntaxKind.ExportDeclaration && (node).moduleSpecifier) { + return getGeneratedNameForNode(node); } } @@ -5377,10 +5344,10 @@ var __param = (this && this.__param) || function (paramIndex, decorator) { emitSetters(exportStarFunction); writeLine(); emitExecute(node, startIndex); - emitTempDeclarations(/*newLine*/ true) decreaseIndent(); writeLine(); write("}"); // return + emitTempDeclarations(/*newLine*/ true); } function emitSetters(exportStarFunction: string) { @@ -5527,7 +5494,11 @@ var __param = (this && this.__param) || function (paramIndex, decorator) { Debug.assert(!exportFunctionForFile); // make sure that name of 'exports' function does not conflict with existing identifiers exportFunctionForFile = makeUniqueName("exports"); - write("System.register(["); + write("System.register("); + if (node.moduleName) { + write(`"${node.moduleName}", `); + } + write("[") for (let i = 0; i < externalImports.length; ++i) { let text = getExternalModuleNameText(externalImports[i]); if (i !== 0) { @@ -5613,8 +5584,8 @@ var __param = (this && this.__param) || function (paramIndex, decorator) { writeLine(); write("define("); - if (node.amdModuleName) { - write("\"" + node.amdModuleName + "\", "); + if (node.moduleName) { + write("\"" + node.moduleName + "\", "); } emitAMDDependencies(node, /*includeNonAmdDependencies*/ true); write(") {"); @@ -5744,7 +5715,7 @@ var __param = (this && this.__param) || function (paramIndex, decorator) { } } - if (isExternalModule(node) || compilerOptions.separateCompilation) { + if (isExternalModule(node) || compilerOptions.isolatedModules) { if (languageVersion >= ScriptTarget.ES6) { emitES6Module(node, startIndex); } @@ -5774,7 +5745,7 @@ var __param = (this && this.__param) || function (paramIndex, decorator) { emitLeadingComments(node.endOfFileToken); } - function emitNodeWithoutSourceMap(node: Node, allowGeneratedIdentifiers?: boolean): void { + function emitNodeWithoutSourceMap(node: Node): void { if (!node) { return; } @@ -5788,7 +5759,7 @@ var __param = (this && this.__param) || function (paramIndex, decorator) { emitLeadingComments(node); } - emitJavaScriptWorker(node, allowGeneratedIdentifiers); + emitJavaScriptWorker(node); if (emitComments) { emitTrailingComments(node); @@ -5838,11 +5809,11 @@ var __param = (this && this.__param) || function (paramIndex, decorator) { return true; } - function emitJavaScriptWorker(node: Node, allowGeneratedIdentifiers: boolean = true) { + function emitJavaScriptWorker(node: Node) { // Check if the node can be emitted regardless of the ScriptTarget switch (node.kind) { case SyntaxKind.Identifier: - return emitIdentifier(node, allowGeneratedIdentifiers); + return emitIdentifier(node); case SyntaxKind.Parameter: return emitParameter(node); case SyntaxKind.MethodDeclaration: diff --git a/src/compiler/parser.ts b/src/compiler/parser.ts index 28fd8184d7e..fbb3dad5037 100644 --- a/src/compiler/parser.ts +++ b/src/compiler/parser.ts @@ -1,9 +1,7 @@ /// /// -module ts { - export var throwOnJSDocErrors = false; - +namespace ts { let nodeConstructors = new Array Node>(SyntaxKind.Count); /* @internal */ export let parseTime = 0; @@ -105,6 +103,9 @@ module ts { case SyntaxKind.TypeReference: return visitNode(cbNode, (node).typeName) || visitNodes(cbNodes, (node).typeArguments); + case SyntaxKind.TypePredicate: + return visitNode(cbNode, (node).parameterName) || + visitNode(cbNode, (node).type); case SyntaxKind.TypeQuery: return visitNode(cbNode, (node).exprName); case SyntaxKind.TypeLiteral: @@ -257,6 +258,7 @@ module ts { return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, (node).name) || + visitNodes(cbNodes, (node).typeParameters) || visitNode(cbNode, (node).type); case SyntaxKind.EnumDeclaration: return visitNodes(cbNodes, node.decorators) || @@ -401,7 +403,7 @@ module ts { module 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. - const scanner = createScanner(ScriptTarget.Latest, /*skipTrivia:*/ true); + const scanner = createScanner(ScriptTarget.Latest, /*skipTrivia*/ true); const disallowInAndDecoratorContext = ParserContextFlags.DisallowIn | ParserContextFlags.Decorator; let sourceFile: SourceFile; @@ -542,7 +544,7 @@ module ts { token = nextToken(); processReferenceComments(sourceFile); - sourceFile.statements = parseList(ParsingContext.SourceElements, /*checkForStrictMode*/ true, parseSourceElement); + sourceFile.statements = parseList(ParsingContext.SourceElements, parseStatement); Debug.assert(token === SyntaxKind.EndOfFileToken); sourceFile.endOfFileToken = parseTokenNode(); @@ -645,10 +647,6 @@ module ts { } } - function setStrictModeContext(val: boolean) { - setContextFlag(val, ParserContextFlags.StrictMode); - } - function setDisallowInContext(val: boolean) { setContextFlag(val, ParserContextFlags.DisallowIn); } @@ -742,10 +740,6 @@ module ts { return (contextFlags & ParserContextFlags.Yield) !== 0; } - function inStrictModeContext() { - return (contextFlags & ParserContextFlags.StrictMode) !== 0; - } - function inGeneratorParameterContext() { return (contextFlags & ParserContextFlags.GeneratorParameter) !== 0; } @@ -847,7 +841,7 @@ module ts { // was in immediately prior to invoking the callback. The result of invoking the callback // is returned from this function. function lookAhead(callback: () => T): T { - return speculationHelper(callback, /*isLookAhead:*/ true); + return speculationHelper(callback, /*isLookAhead*/ true); } // Invokes the provided callback. If the callback returns something falsy, then it restores @@ -855,7 +849,7 @@ module ts { // 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: () => T): T { - return speculationHelper(callback, /*isLookAhead:*/ false); + return speculationHelper(callback, /*isLookAhead*/ false); } // Ignore strict mode flag because we will report an error in type checker instead. @@ -1004,7 +998,7 @@ module ts { 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 { @@ -1023,7 +1017,7 @@ module ts { function parsePropertyNameWorker(allowComputedPropertyNames: boolean): DeclarationName { if (token === SyntaxKind.StringLiteral || token === SyntaxKind.NumericLiteral) { - return parseLiteralNode(/*internName:*/ true); + return parseLiteralNode(/*internName*/ true); } if (allowComputedPropertyNames && token === SyntaxKind.OpenBracketToken) { return parseComputedPropertyName(); @@ -1120,11 +1114,15 @@ module ts { switch (parsingContext) { case ParsingContext.SourceElements: - case ParsingContext.ModuleElements: - return isSourceElement(inErrorRecovery); case ParsingContext.BlockStatements: case ParsingContext.SwitchClauseStatements: - return isStartOfStatement(inErrorRecovery); + // 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 === SyntaxKind.SemicolonToken && inErrorRecovery) && isStartOfStatement(); case ParsingContext.SwitchClauses: return token === SyntaxKind.CaseKeyword || token === SyntaxKind.DefaultKeyword; case ParsingContext.TypeMembers: @@ -1234,7 +1232,6 @@ module ts { } switch (kind) { - case ParsingContext.ModuleElements: case ParsingContext.BlockStatements: case ParsingContext.SwitchClauses: case ParsingContext.TypeMembers: @@ -1318,31 +1315,17 @@ module ts { } // Parses a list of elements - function parseList(kind: ParsingContext, checkForStrictMode: boolean, parseElement: () => T): NodeArray { + function parseList(kind: ParsingContext, parseElement: () => T): NodeArray { let saveParsingContext = parsingContext; parsingContext |= 1 << kind; let result = >[]; result.pos = getNodePos(); - let savedStrictModeContext = inStrictModeContext(); while (!isListTerminator(kind)) { if (isListElement(kind, /* inErrorRecovery */ false)) { let element = parseListElement(kind, parseElement); result.push(element); - // test elements only if we are not already in strict mode - if (checkForStrictMode && !inStrictModeContext()) { - if (isPrologueDirective(element)) { - if (isUseStrictPrologueDirective(element)) { - setStrictModeContext(true); - checkForStrictMode = false; - } - } - else { - checkForStrictMode = false; - } - } - continue; } @@ -1351,22 +1334,11 @@ module ts { } } - setStrictModeContext(savedStrictModeContext); result.end = getNodeEnd(); parsingContext = saveParsingContext; return result; } - /// Should be called only on prologue directives (isPrologueDirective(node) should be true) - function isUseStrictPrologueDirective(node: Node): boolean { - Debug.assert(isPrologueDirective(node)); - let nodeText = getTextOfNodeFromSourceText(sourceText, (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 parseListElement(parsingContext: ParsingContext, parseElement: () => T): T { let node = currentNode(parsingContext); if (node) { @@ -1445,15 +1417,13 @@ module ts { function canReuseNode(node: Node, parsingContext: ParsingContext): boolean { switch (parsingContext) { - case ParsingContext.ModuleElements: - return isReusableModuleElement(node); - case ParsingContext.ClassMembers: return isReusableClassMember(node); case ParsingContext.SwitchClauses: return isReusableSwitchClause(node); + case ParsingContext.SourceElements: case ParsingContext.BlockStatements: case ParsingContext.SwitchClauseStatements: return isReusableStatement(node); @@ -1516,37 +1486,25 @@ module ts { return false; } - function isReusableModuleElement(node: Node) { - if (node) { - switch (node.kind) { - case SyntaxKind.ImportDeclaration: - case SyntaxKind.ImportEqualsDeclaration: - case SyntaxKind.ExportDeclaration: - case SyntaxKind.ExportAssignment: - case SyntaxKind.ClassDeclaration: - case SyntaxKind.InterfaceDeclaration: - case SyntaxKind.ModuleDeclaration: - case SyntaxKind.EnumDeclaration: - return true; - } - - return isReusableStatement(node); - } - - return false; - } - function isReusableClassMember(node: Node) { if (node) { switch (node.kind) { case SyntaxKind.Constructor: case SyntaxKind.IndexSignature: - case SyntaxKind.MethodDeclaration: case SyntaxKind.GetAccessor: case SyntaxKind.SetAccessor: case SyntaxKind.PropertyDeclaration: case SyntaxKind.SemicolonClassElement: return true; + case SyntaxKind.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. + let methodDeclaration = node; + let nameIsConstructor = methodDeclaration.name.kind === SyntaxKind.Identifier && + (methodDeclaration.name).originalKeywordKind === SyntaxKind.ConstructorKeyword; + + return !nameIsConstructor; } } @@ -1588,6 +1546,15 @@ module ts { case SyntaxKind.LabeledStatement: case SyntaxKind.DoStatement: case SyntaxKind.DebuggerStatement: + case SyntaxKind.ImportDeclaration: + case SyntaxKind.ImportEqualsDeclaration: + case SyntaxKind.ExportDeclaration: + case SyntaxKind.ExportAssignment: + case SyntaxKind.ModuleDeclaration: + case SyntaxKind.ClassDeclaration: + case SyntaxKind.InterfaceDeclaration: + case SyntaxKind.EnumDeclaration: + case SyntaxKind.TypeAliasDeclaration: return true; } } @@ -1661,8 +1628,7 @@ module ts { function parsingContextErrors(context: ParsingContext): DiagnosticMessage { switch (context) { case ParsingContext.SourceElements: return Diagnostics.Declaration_or_statement_expected; - case ParsingContext.ModuleElements: return Diagnostics.Declaration_or_statement_expected; - case ParsingContext.BlockStatements: return Diagnostics.Statement_expected; + case ParsingContext.BlockStatements: return Diagnostics.Declaration_or_statement_expected; case ParsingContext.SwitchClauses: return Diagnostics.case_or_default_expected; case ParsingContext.SwitchClauseStatements: return Diagnostics.Statement_expected; case ParsingContext.TypeMembers: return Diagnostics.Property_or_signature_expected; @@ -1779,33 +1745,33 @@ module ts { } function parseRightSideOfDot(allowIdentifierNames: boolean): Identifier { - // Technically a keyword is valid here as all keywords are identifier names. - // However, often we'll encounter this in error situations when the keyword + // 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. - // keyword identifierNameOrKeyword + // identifierOrKeyword identifierNameOrKeyword // // Note: the newlines are important here. For example, if that above code // were rewritten into: // - // name.keyword + // name.identifierOrKeyword // identifierNameOrKeyword // // Then we would consider it valid. That's because ASI would take effect and - // the code would be implicitly: "name.keyword; identifierNameOrKeyword". + // 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 keyword. - if (scanner.hasPrecedingLineBreak() && scanner.isReservedWord()) { + // line terminator after the identifier or keyword. + if (scanner.hasPrecedingLineBreak() && isIdentifierOrKeyword()) { let 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 woudl be quite confusing. - return createMissingNode(SyntaxKind.Identifier, /*reportAtCurrentToken:*/ true, Diagnostics.Identifier_expected); + // be an identifier and the error would be quite confusing. + return createMissingNode(SyntaxKind.Identifier, /*reportAtCurrentToken*/ true, Diagnostics.Identifier_expected); } } @@ -1843,7 +1809,7 @@ module ts { literal = parseLiteralNode(); } else { - literal = parseExpectedToken(SyntaxKind.TemplateTail, /*reportAtCurrentPosition:*/ false, Diagnostics._0_expected, tokenToString(SyntaxKind.CloseBraceToken)); + literal = parseExpectedToken(SyntaxKind.TemplateTail, /*reportAtCurrentPosition*/ false, Diagnostics._0_expected, tokenToString(SyntaxKind.CloseBraceToken)); } span.literal = literal; @@ -1885,9 +1851,17 @@ module ts { // TYPES - function parseTypeReference(): TypeReferenceNode { - let node = createNode(SyntaxKind.TypeReference); - node.typeName = parseEntityName(/*allowReservedWords*/ false, Diagnostics.Type_expected); + function parseTypeReferenceOrTypePredicate(): TypeReferenceNode | TypePredicateNode { + let typeName = parseEntityName(/*allowReservedWords*/ false, Diagnostics.Type_expected); + if (typeName.kind === SyntaxKind.Identifier && token === SyntaxKind.IsKeyword && !scanner.hasPrecedingLineBreak()) { + nextToken(); + let node = createNode(SyntaxKind.TypePredicate, typeName.pos); + node.parameterName = typeName; + node.type = parseType(); + return finishNode(node); + } + let node = createNode(SyntaxKind.TypeReference, typeName.pos); + node.typeName = typeName; if (!scanner.hasPrecedingLineBreak() && token === SyntaxKind.LessThanToken) { node.typeArguments = parseBracketedList(ParsingContext.TypeArguments, parseType, SyntaxKind.LessThanToken, SyntaxKind.GreaterThanToken); } @@ -1936,7 +1910,7 @@ module ts { function parseParameterType(): TypeNode { if (parseOptional(SyntaxKind.ColonToken)) { return token === SyntaxKind.StringLiteral - ? parseLiteralNode(/*internName:*/ true) + ? parseLiteralNode(/*internName*/ true) : parseType(); } @@ -2077,7 +2051,7 @@ module ts { if (kind === SyntaxKind.ConstructSignature) { parseExpected(SyntaxKind.NewKeyword); } - fillSignature(SyntaxKind.ColonToken, /*yieldAndGeneratorParameterContext:*/ false, /*requireCompleteParameterList:*/ false, node); + fillSignature(SyntaxKind.ColonToken, /*yieldAndGeneratorParameterContext*/ false, /*requireCompleteParameterList*/ false, node); parseTypeMemberSemicolon(); return finishNode(node); } @@ -2167,7 +2141,7 @@ module ts { // Method signatues don't exist in expression contexts. So they have neither // [Yield] nor [GeneratorParameter] - fillSignature(SyntaxKind.ColonToken, /*yieldAndGeneratorParameterContext:*/ false, /*requireCompleteParameterList:*/ false, method); + fillSignature(SyntaxKind.ColonToken, /*yieldAndGeneratorParameterContext*/ false, /*requireCompleteParameterList*/ false, method); parseTypeMemberSemicolon(); return finishNode(method); } @@ -2224,7 +2198,7 @@ module ts { case SyntaxKind.OpenBracketToken: // Indexer or computed property return isIndexSignature() - ? parseIndexSignatureDeclaration(scanner.getStartPos(), /*decorators*/ undefined, /*modifiers:*/ undefined) + ? parseIndexSignatureDeclaration(scanner.getStartPos(), /*decorators*/ undefined, /*modifiers*/ undefined) : parsePropertyOrMethodSignature(); case SyntaxKind.NewKeyword: if (lookAhead(isStartOfConstructSignature)) { @@ -2277,7 +2251,7 @@ module ts { function parseObjectTypeMembers(): NodeArray { let members: NodeArray; if (parseExpected(SyntaxKind.OpenBraceToken)) { - members = parseList(ParsingContext.TypeMembers, /*checkForStrictMode*/ false, parseTypeMember); + members = parseList(ParsingContext.TypeMembers, parseTypeMember); parseExpected(SyntaxKind.CloseBraceToken); } else { @@ -2306,7 +2280,7 @@ module ts { if (kind === SyntaxKind.ConstructorType) { parseExpected(SyntaxKind.NewKeyword); } - fillSignature(SyntaxKind.EqualsGreaterThanToken, /*yieldAndGeneratorParameterContext:*/ false, /*requireCompleteParameterList:*/ false, node); + fillSignature(SyntaxKind.EqualsGreaterThanToken, /*yieldAndGeneratorParameterContext*/ false, /*requireCompleteParameterList*/ false, node); return finishNode(node); } @@ -2324,7 +2298,7 @@ module ts { case SyntaxKind.SymbolKeyword: // If these are followed by a dot, then parse these out as a dotted type reference instead. let node = tryParse(parseKeywordAndNoDot); - return node || parseTypeReference(); + return node || parseTypeReferenceOrTypePredicate(); case SyntaxKind.VoidKeyword: return parseTokenNode(); case SyntaxKind.TypeOfKeyword: @@ -2336,7 +2310,7 @@ module ts { case SyntaxKind.OpenParenToken: return parseParenthesizedType(); default: - return parseTypeReference(); + return parseTypeReferenceOrTypePredicate(); } } @@ -2615,7 +2589,7 @@ module ts { // 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. - let expr = parseBinaryExpressionOrHigher(/*precedence:*/ 0); + let 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 @@ -2646,12 +2620,6 @@ module ts { return true; } - if (inStrictModeContext()) { - // If we're in strict mode, then 'yield' is a keyword, could only ever start - // a yield expression. - 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 @@ -2666,7 +2634,7 @@ module ts { // 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 accidently consume something legal. - return lookAhead(nextTokenIsIdentifierOnSameLine); + return lookAhead(nextTokenIsIdentifierOrKeywordOrNumberOnSameLine); } return false; @@ -2674,13 +2642,7 @@ module ts { function nextTokenIsIdentifierOnSameLine() { nextToken(); - return !scanner.hasPrecedingLineBreak() && isIdentifier() - } - - function nextTokenIsIdentifierOrStartOfDestructuringOnTheSameLine() { - nextToken(); - return !scanner.hasPrecedingLineBreak() && - (isIdentifier() || token === SyntaxKind.OpenBraceToken || token === SyntaxKind.OpenBracketToken); + return !scanner.hasPrecedingLineBreak() && isIdentifier(); } function parseYieldExpression(): YieldExpression { @@ -2737,7 +2699,7 @@ module ts { // it out, but don't allow any ambiguity, and return 'undefined' if this could be an // expression instead. let arrowFunction = triState === Tristate.True - ? parseParenthesizedArrowFunctionExpressionHead(/*allowAmbiguity:*/ true) + ? parseParenthesizedArrowFunctionExpressionHead(/*allowAmbiguity*/ true) : tryParse(parsePossibleParenthesizedArrowFunctionExpressionHead); if (!arrowFunction) { @@ -2748,7 +2710,7 @@ module ts { // 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(SyntaxKind.EqualsGreaterThanToken, /*reportAtCurrentPosition:*/false, Diagnostics._0_expected, "=>"); + arrowFunction.equalsGreaterThanToken = parseExpectedToken(SyntaxKind.EqualsGreaterThanToken, /*reportAtCurrentPosition*/false, Diagnostics._0_expected, "=>"); arrowFunction.body = (lastToken === SyntaxKind.EqualsGreaterThanToken || lastToken === SyntaxKind.OpenBraceToken) ? parseArrowFunctionExpressionBody() : parseIdentifier(); @@ -2846,7 +2808,7 @@ module ts { } function parsePossibleParenthesizedArrowFunctionExpressionHead(): ArrowFunction { - return parseParenthesizedArrowFunctionExpressionHead(/*allowAmbiguity:*/ false); + return parseParenthesizedArrowFunctionExpressionHead(/*allowAmbiguity*/ false); } function parseParenthesizedArrowFunctionExpressionHead(allowAmbiguity: boolean): ArrowFunction { @@ -2858,7 +2820,7 @@ module ts { // a => (b => c) // And think that "(b =>" was actually a parenthesized arrow function with a missing // close paren. - fillSignature(SyntaxKind.ColonToken, /*yieldAndGeneratorParameterContext:*/ false, /*requireCompleteParameterList:*/ !allowAmbiguity, node); + fillSignature(SyntaxKind.ColonToken, /*yieldAndGeneratorParameterContext*/ false, /*requireCompleteParameterList*/ !allowAmbiguity, node); // If we couldn't get parameters, we definitely could not parse out an arrow function. if (!node.parameters) { @@ -2883,14 +2845,14 @@ module ts { function parseArrowFunctionExpressionBody(): Block | Expression { if (token === SyntaxKind.OpenBraceToken) { - return parseFunctionBlock(/*allowYield:*/ false, /* ignoreMissingOpenBrace */ false); + return parseFunctionBlock(/*allowYield*/ false, /*ignoreMissingOpenBrace*/ false); } - if (isStartOfStatement(/*inErrorRecovery:*/ true) && - !isStartOfExpressionStatement() && + if (token !== SyntaxKind.SemicolonToken && token !== SyntaxKind.FunctionKeyword && - token !== SyntaxKind.ClassKeyword) { - + token !== SyntaxKind.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 @@ -2905,7 +2867,7 @@ module ts { // up preemptively closing the containing construct. // // Note: even when 'ignoreMissingOpenBrace' is passed as true, parseBody will still error. - return parseFunctionBlock(/*allowYield:*/ false, /* ignoreMissingOpenBrace */ true); + return parseFunctionBlock(/*allowYield*/ false, /*ignoreMissingOpenBrace*/ true); } return parseAssignmentExpressionOrHigher(); @@ -2924,7 +2886,7 @@ module ts { node.condition = leftOperand; node.questionToken = questionToken; node.whenTrue = doOutsideOfContext(disallowInAndDecoratorContext, parseAssignmentExpressionOrHigher); - node.colonToken = parseExpectedToken(SyntaxKind.ColonToken, /*reportAtCurrentPosition:*/ false, + node.colonToken = parseExpectedToken(SyntaxKind.ColonToken, /*reportAtCurrentPosition*/ false, Diagnostics._0_expected, tokenToString(SyntaxKind.ColonToken)); node.whenFalse = parseAssignmentExpressionOrHigher(); return finishNode(node); @@ -3188,8 +3150,8 @@ module ts { // If it wasn't then just try to parse out a '.' and report an error. let node = createNode(SyntaxKind.PropertyAccessExpression, expression.pos); node.expression = expression; - node.dotToken = parseExpectedToken(SyntaxKind.DotToken, /*reportAtCurrentPosition:*/ false, Diagnostics.super_must_be_followed_by_an_argument_list_or_member_access); - node.name = parseRightSideOfDot(/*allowIdentifierNames:*/ true); + node.dotToken = parseExpectedToken(SyntaxKind.DotToken, /*reportAtCurrentPosition*/ false, Diagnostics.super_must_be_followed_by_an_argument_list_or_member_access); + node.name = parseRightSideOfDot(/*allowIdentifierNames*/ true); return finishNode(node); } @@ -3209,7 +3171,7 @@ module ts { let propertyAccess = createNode(SyntaxKind.PropertyAccessExpression, expression.pos); propertyAccess.expression = expression; propertyAccess.dotToken = dotToken; - propertyAccess.name = parseRightSideOfDot(/*allowIdentifierNames:*/ true); + propertyAccess.name = parseRightSideOfDot(/*allowIdentifierNames*/ true); expression = finishNode(propertyAccess); continue; } @@ -3472,7 +3434,7 @@ module ts { node.flags |= NodeFlags.MultiLine; } - node.properties = parseDelimitedList(ParsingContext.ObjectLiteralMembers, parseObjectLiteralElement, /*considerSemicolonAsDelimeter:*/ true); + node.properties = parseDelimitedList(ParsingContext.ObjectLiteralMembers, parseObjectLiteralElement, /*considerSemicolonAsDelimeter*/ true); parseExpected(SyntaxKind.CloseBraceToken); return finishNode(node); } @@ -3490,8 +3452,8 @@ module ts { parseExpected(SyntaxKind.FunctionKeyword); node.asteriskToken = parseOptionalToken(SyntaxKind.AsteriskToken); node.name = node.asteriskToken ? doInYieldContext(parseOptionalIdentifier) : parseOptionalIdentifier(); - fillSignature(SyntaxKind.ColonToken, /*yieldAndGeneratorParameterContext:*/ !!node.asteriskToken, /*requireCompleteParameterList:*/ false, node); - node.body = parseFunctionBlock(/*allowYield:*/ !!node.asteriskToken, /* ignoreMissingOpenBrace */ false); + fillSignature(SyntaxKind.ColonToken, /*yieldAndGeneratorParameterContext*/ !!node.asteriskToken, /*requireCompleteParameterList*/ false, node); + node.body = parseFunctionBlock(/*allowYield*/ !!node.asteriskToken, /* ignoreMissingOpenBrace */ false); if (saveDecoratorContext) { setDecoratorContext(true); } @@ -3515,10 +3477,10 @@ module ts { } // STATEMENTS - function parseBlock(ignoreMissingOpenBrace: boolean, checkForStrictMode: boolean, diagnosticMessage?: DiagnosticMessage): Block { + function parseBlock(ignoreMissingOpenBrace: boolean, diagnosticMessage?: DiagnosticMessage): Block { let node = createNode(SyntaxKind.Block); if (parseExpected(SyntaxKind.OpenBraceToken, diagnosticMessage) || ignoreMissingOpenBrace) { - node.statements = parseList(ParsingContext.BlockStatements, checkForStrictMode, parseStatement); + node.statements = parseList(ParsingContext.BlockStatements, parseStatement); parseExpected(SyntaxKind.CloseBraceToken); } else { @@ -3538,7 +3500,7 @@ module ts { setDecoratorContext(false); } - let block = parseBlock(ignoreMissingOpenBrace, /*checkForStrictMode*/ true, diagnosticMessage); + let block = parseBlock(ignoreMissingOpenBrace, diagnosticMessage); if (saveDecoratorContext) { setDecoratorContext(true); @@ -3601,7 +3563,7 @@ module ts { let initializer: VariableDeclarationList | Expression = undefined; if (token !== SyntaxKind.SemicolonToken) { if (token === SyntaxKind.VarKeyword || token === SyntaxKind.LetKeyword || token === SyntaxKind.ConstKeyword) { - initializer = parseVariableDeclarationList(/*inForStatementInitializer:*/ true); + initializer = parseVariableDeclarationList(/*inForStatementInitializer*/ true); } else { initializer = disallowInAnd(parseExpression); @@ -3680,7 +3642,7 @@ module ts { parseExpected(SyntaxKind.CaseKeyword); node.expression = allowInAnd(parseExpression); parseExpected(SyntaxKind.ColonToken); - node.statements = parseList(ParsingContext.SwitchClauseStatements, /*checkForStrictMode*/ false, parseStatement); + node.statements = parseList(ParsingContext.SwitchClauseStatements, parseStatement); return finishNode(node); } @@ -3688,7 +3650,7 @@ module ts { let node = createNode(SyntaxKind.DefaultClause); parseExpected(SyntaxKind.DefaultKeyword); parseExpected(SyntaxKind.ColonToken); - node.statements = parseList(ParsingContext.SwitchClauseStatements, /*checkForStrictMode*/ false, parseStatement); + node.statements = parseList(ParsingContext.SwitchClauseStatements, parseStatement); return finishNode(node); } @@ -3704,7 +3666,7 @@ module ts { parseExpected(SyntaxKind.CloseParenToken); let caseBlock = createNode(SyntaxKind.CaseBlock, scanner.getStartPos()); parseExpected(SyntaxKind.OpenBraceToken); - caseBlock.clauses = parseList(ParsingContext.SwitchClauses, /*checkForStrictMode*/ false, parseCaseOrDefaultClause); + caseBlock.clauses = parseList(ParsingContext.SwitchClauses, parseCaseOrDefaultClause); parseExpected(SyntaxKind.CloseBraceToken); node.caseBlock = finishNode(caseBlock); return finishNode(node); @@ -3731,14 +3693,14 @@ module ts { let node = createNode(SyntaxKind.TryStatement); parseExpected(SyntaxKind.TryKeyword); - node.tryBlock = parseBlock(/*ignoreMissingOpenBrace:*/ false, /*checkForStrictMode*/ false); + node.tryBlock = parseBlock(/*ignoreMissingOpenBrace*/ false); node.catchClause = token === SyntaxKind.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 === SyntaxKind.FinallyKeyword) { parseExpected(SyntaxKind.FinallyKeyword); - node.finallyBlock = parseBlock(/*ignoreMissingOpenBrace:*/ false, /*checkForStrictMode*/ false); + node.finallyBlock = parseBlock(/*ignoreMissingOpenBrace*/ false); } return finishNode(node); @@ -3752,7 +3714,7 @@ module ts { } parseExpected(SyntaxKind.CloseParenToken); - result.block = parseBlock(/*ignoreMissingOpenBrace:*/ false, /*checkForStrictMode:*/ false); + result.block = parseBlock(/*ignoreMissingOpenBrace*/ false); return finishNode(result); } @@ -3784,34 +3746,103 @@ module ts { } } - function isStartOfStatement(inErrorRecovery: boolean): boolean { - // Functions, variable statements and classes are allowed as a statement. But as per - // the grammar, they also allow modifiers. So we have to check for those statements - // that might be following modifiers.This ensures that things work properly when - // incrementally parsing as the parser will produce the same FunctionDeclaraiton, - // VariableStatement or ClassDeclaration, if it has the same text regardless of whether - // it is inside a block or not. - if (isModifier(token)) { - let result = lookAhead(parseVariableStatementOrFunctionDeclarationOrClassDeclarationWithDecoratorsOrModifiers); - if (result) { - return true; + function isIdentifierOrKeyword() { + return token >= SyntaxKind.Identifier; + } + + function nextTokenIsIdentifierOrKeywordOnSameLine() { + nextToken(); + return isIdentifierOrKeyword() && !scanner.hasPrecedingLineBreak(); + } + + function nextTokenIsIdentifierOrKeywordOrNumberOnSameLine() { + nextToken(); + return (isIdentifierOrKeyword() || token === SyntaxKind.NumericLiteral) && !scanner.hasPrecedingLineBreak(); + } + + function isDeclaration(): boolean { + while (true) { + switch (token) { + case SyntaxKind.VarKeyword: + case SyntaxKind.LetKeyword: + case SyntaxKind.ConstKeyword: + case SyntaxKind.FunctionKeyword: + case SyntaxKind.ClassKeyword: + case SyntaxKind.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 SyntaxKind.InterfaceKeyword: + case SyntaxKind.TypeKeyword: + return nextTokenIsIdentifierOnSameLine(); + case SyntaxKind.ModuleKeyword: + case SyntaxKind.NamespaceKeyword: + return nextTokenIsIdentifierOrStringLiteralOnSameLine(); + case SyntaxKind.DeclareKeyword: + nextToken(); + // ASI takes effect for this modifier. + if (scanner.hasPrecedingLineBreak()) { + return false; + } + continue; + + case SyntaxKind.ImportKeyword: + nextToken(); + return token === SyntaxKind.StringLiteral || token === SyntaxKind.AsteriskToken || + token === SyntaxKind.OpenBraceToken || isIdentifierOrKeyword(); + case SyntaxKind.ExportKeyword: + nextToken(); + if (token === SyntaxKind.EqualsToken || token === SyntaxKind.AsteriskToken || + token === SyntaxKind.OpenBraceToken || token === SyntaxKind.DefaultKeyword) { + return true; + } + continue; + case SyntaxKind.PublicKeyword: + case SyntaxKind.PrivateKeyword: + case SyntaxKind.ProtectedKeyword: + case SyntaxKind.StaticKeyword: + nextToken(); + continue; + default: + return false; } } + } + function isStartOfDeclaration(): boolean { + return lookAhead(isDeclaration); + } + + function isStartOfStatement(): boolean { switch (token) { + case SyntaxKind.AtToken: case SyntaxKind.SemicolonToken: - // 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 !inErrorRecovery; case SyntaxKind.OpenBraceToken: case SyntaxKind.VarKeyword: case SyntaxKind.LetKeyword: case SyntaxKind.FunctionKeyword: case SyntaxKind.ClassKeyword: + case SyntaxKind.EnumKeyword: case SyntaxKind.IfKeyword: case SyntaxKind.DoKeyword: case SyntaxKind.WhileKeyword: @@ -3829,61 +3860,61 @@ module ts { case SyntaxKind.CatchKeyword: case SyntaxKind.FinallyKeyword: return true; + case SyntaxKind.ConstKeyword: - // const keyword can precede enum keyword when defining constant enums - // 'const enum' do not start statement. - // In ES 6 'enum' is a future reserved keyword, so it should not be used as identifier - let isConstEnum = lookAhead(nextTokenIsEnumKeyword); - return !isConstEnum; + case SyntaxKind.ExportKeyword: + case SyntaxKind.ImportKeyword: + return isStartOfDeclaration(); + + case SyntaxKind.DeclareKeyword: case SyntaxKind.InterfaceKeyword: case SyntaxKind.ModuleKeyword: case SyntaxKind.NamespaceKeyword: - case SyntaxKind.EnumKeyword: case SyntaxKind.TypeKeyword: - // When followed by an identifier, these do not start a statement but might - // instead be following declarations - if (isDeclarationStart()) { - return false; - } + // When these don't start a declaration, they're an identifier in an expression statement + return true; case SyntaxKind.PublicKeyword: case SyntaxKind.PrivateKeyword: case SyntaxKind.ProtectedKeyword: case SyntaxKind.StaticKeyword: - // When followed by an identifier or keyword, these do not start a statement but - // might instead be following type members - if (lookAhead(nextTokenIsIdentifierOrKeywordOnSameLine)) { - return false; - } + // 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 nextTokenIsEnumKeyword() { + function nextTokenIsIdentifierOrStartOfDestructuring() { nextToken(); - return token === SyntaxKind.EnumKeyword + return isIdentifier() || token === SyntaxKind.OpenBraceToken || token === SyntaxKind.OpenBracketToken; } - function nextTokenIsIdentifierOrKeywordOnSameLine() { - nextToken(); - return isIdentifierOrKeyword() && !scanner.hasPrecedingLineBreak(); + function isLetDeclaration() { + // In ES6 'let' always starts a lexical declaration if followed by an identifier or { + // or [. + return lookAhead(nextTokenIsIdentifierOrStartOfDestructuring); } function parseStatement(): Statement { switch (token) { - case SyntaxKind.OpenBraceToken: - return parseBlock(/*ignoreMissingOpenBrace:*/ false, /*checkForStrictMode:*/ false); - case SyntaxKind.VarKeyword: - case SyntaxKind.ConstKeyword: - // const here should always be parsed as const declaration because of check in 'isStatement' - return parseVariableStatement(scanner.getStartPos(), /*decorators*/ undefined, /*modifiers:*/ undefined); - case SyntaxKind.FunctionKeyword: - return parseFunctionDeclaration(scanner.getStartPos(), /*decorators*/ undefined, /*modifiers:*/ undefined); - case SyntaxKind.ClassKeyword: - return parseClassDeclaration(scanner.getStartPos(), /*decorators*/ undefined, /*modifiers:*/ undefined); case SyntaxKind.SemicolonToken: return parseEmptyStatement(); + case SyntaxKind.OpenBraceToken: + return parseBlock(/*ignoreMissingOpenBrace*/ false); + case SyntaxKind.VarKeyword: + return parseVariableStatement(scanner.getStartPos(), /*decorators*/ undefined, /*modifiers*/ undefined); + case SyntaxKind.LetKeyword: + if (isLetDeclaration()) { + return parseVariableStatement(scanner.getStartPos(), /*decorators*/ undefined, /*modifiers*/ undefined); + } + break; + case SyntaxKind.FunctionKeyword: + return parseFunctionDeclaration(scanner.getStartPos(), /*decorators*/ undefined, /*modifiers*/ undefined); + case SyntaxKind.ClassKeyword: + return parseClassDeclaration(scanner.getStartPos(), /*decorators*/ undefined, /*modifiers*/ undefined); case SyntaxKind.IfKeyword: return parseIfStatement(); case SyntaxKind.DoKeyword: @@ -3905,67 +3936,81 @@ module ts { case SyntaxKind.ThrowKeyword: return parseThrowStatement(); case SyntaxKind.TryKeyword: - // Include the next two for error recovery. + // Include 'catch' and 'finally' for error recovery. case SyntaxKind.CatchKeyword: case SyntaxKind.FinallyKeyword: return parseTryStatement(); case SyntaxKind.DebuggerKeyword: return parseDebuggerStatement(); - case SyntaxKind.LetKeyword: - // If let follows identifier on the same line, it is declaration parse it as variable statement - if (isLetDeclaration()) { - return parseVariableStatement(scanner.getStartPos(), /*decorators*/ undefined, /*modifiers:*/ undefined); - } - // Else parse it like identifier - fall through - default: - // Functions and variable statements are allowed as a statement. But as per - // the grammar, they also allow modifiers. So we have to check for those - // statements that might be following modifiers. This ensures that things - // work properly when incrementally parsing as the parser will produce the - // same FunctionDeclaraiton or VariableStatement if it has the same text - // regardless of whether it is inside a block or not. - // Even though variable statements and function declarations cannot have decorators, - // we parse them here to provide better error recovery. - if (isModifier(token) || token === SyntaxKind.AtToken) { - let result = tryParse(parseVariableStatementOrFunctionDeclarationOrClassDeclarationWithDecoratorsOrModifiers); - if (result) { - return result; - } - } + case SyntaxKind.AtToken: + return parseDeclaration(); - return parseExpressionOrLabeledStatement(); + case SyntaxKind.InterfaceKeyword: + case SyntaxKind.TypeKeyword: + case SyntaxKind.ModuleKeyword: + case SyntaxKind.NamespaceKeyword: + case SyntaxKind.DeclareKeyword: + case SyntaxKind.ConstKeyword: + case SyntaxKind.EnumKeyword: + case SyntaxKind.ExportKeyword: + case SyntaxKind.ImportKeyword: + case SyntaxKind.PrivateKeyword: + case SyntaxKind.ProtectedKeyword: + case SyntaxKind.PublicKeyword: + case SyntaxKind.StaticKeyword: + if (isStartOfDeclaration()) { + return parseDeclaration(); + } + break; } + return parseExpressionOrLabeledStatement(); } - function parseVariableStatementOrFunctionDeclarationOrClassDeclarationWithDecoratorsOrModifiers(): FunctionDeclaration | VariableStatement | ClassDeclaration { - let start = scanner.getStartPos(); + function parseDeclaration(): Statement { + let fullStart = getNodePos(); let decorators = parseDecorators(); let modifiers = parseModifiers(); switch (token) { - case SyntaxKind.ConstKeyword: - let nextTokenIsEnum = lookAhead(nextTokenIsEnumKeyword) - if (nextTokenIsEnum) { - return undefined; - } - return parseVariableStatement(start, decorators, modifiers); - - case SyntaxKind.LetKeyword: - if (!isLetDeclaration()) { - return undefined; - } - return parseVariableStatement(start, decorators, modifiers); - case SyntaxKind.VarKeyword: - return parseVariableStatement(start, decorators, modifiers); - + case SyntaxKind.LetKeyword: + case SyntaxKind.ConstKeyword: + return parseVariableStatement(fullStart, decorators, modifiers); case SyntaxKind.FunctionKeyword: - return parseFunctionDeclaration(start, decorators, modifiers); - + return parseFunctionDeclaration(fullStart, decorators, modifiers); case SyntaxKind.ClassKeyword: - return parseClassDeclaration(start, decorators, modifiers); + return parseClassDeclaration(fullStart, decorators, modifiers); + case SyntaxKind.InterfaceKeyword: + return parseInterfaceDeclaration(fullStart, decorators, modifiers); + case SyntaxKind.TypeKeyword: + return parseTypeAliasDeclaration(fullStart, decorators, modifiers); + case SyntaxKind.EnumKeyword: + return parseEnumDeclaration(fullStart, decorators, modifiers); + case SyntaxKind.ModuleKeyword: + case SyntaxKind.NamespaceKeyword: + return parseModuleDeclaration(fullStart, decorators, modifiers); + case SyntaxKind.ImportKeyword: + return parseImportDeclarationOrImportEqualsDeclaration(fullStart, decorators, modifiers); + case SyntaxKind.ExportKeyword: + nextToken(); + return token === SyntaxKind.DefaultKeyword || token === SyntaxKind.EqualsToken ? + parseExportAssignment(fullStart, decorators, modifiers) : + 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. + let node = createMissingNode(SyntaxKind.MissingDeclaration, /*reportAtCurrentPosition*/ true, Diagnostics.Declaration_expected); + node.pos = fullStart; + node.decorators = decorators; + setModifiers(node, modifiers); + return finishNode(node); + } } + } - return undefined; + function nextTokenIsIdentifierOrStringLiteralOnSameLine() { + nextToken(); + return !scanner.hasPrecedingLineBreak() && (isIdentifier() || token === SyntaxKind.StringLiteral); } function parseFunctionBlockOrSemicolon(isGenerator: boolean, diagnosticMessage?: DiagnosticMessage): Block { @@ -3974,7 +4019,7 @@ module ts { return; } - return parseFunctionBlock(isGenerator, /*ignoreMissingOpenBrace:*/ false, diagnosticMessage); + return parseFunctionBlock(isGenerator, /*ignoreMissingOpenBrace*/ false, diagnosticMessage); } // DECLARATIONS @@ -4097,7 +4142,7 @@ module ts { let node = createNode(SyntaxKind.VariableStatement, fullStart); node.decorators = decorators; setModifiers(node, modifiers); - node.declarationList = parseVariableDeclarationList(/*inForStatementInitializer:*/ false); + node.declarationList = parseVariableDeclarationList(/*inForStatementInitializer*/ false); parseSemicolon(); return finishNode(node); } @@ -4109,7 +4154,7 @@ module ts { parseExpected(SyntaxKind.FunctionKeyword); node.asteriskToken = parseOptionalToken(SyntaxKind.AsteriskToken); node.name = node.flags & NodeFlags.Default ? parseOptionalIdentifier() : parseIdentifier(); - fillSignature(SyntaxKind.ColonToken, /*yieldAndGeneratorParameterContext:*/ !!node.asteriskToken, /*requireCompleteParameterList:*/ false, node); + fillSignature(SyntaxKind.ColonToken, /*yieldAndGeneratorParameterContext*/ !!node.asteriskToken, /*requireCompleteParameterList*/ false, node); node.body = parseFunctionBlockOrSemicolon(!!node.asteriskToken, Diagnostics.or_expected); return finishNode(node); } @@ -4119,8 +4164,8 @@ module ts { node.decorators = decorators; setModifiers(node, modifiers); parseExpected(SyntaxKind.ConstructorKeyword); - fillSignature(SyntaxKind.ColonToken, /*yieldAndGeneratorParameterContext:*/ false, /*requireCompleteParameterList:*/ false, node); - node.body = parseFunctionBlockOrSemicolon(/*isGenerator:*/ false, Diagnostics.or_expected); + fillSignature(SyntaxKind.ColonToken, /*yieldAndGeneratorParameterContext*/ false, /*requireCompleteParameterList*/ false, node); + node.body = parseFunctionBlockOrSemicolon(/*isGenerator*/ false, Diagnostics.or_expected); return finishNode(node); } @@ -4131,7 +4176,7 @@ module ts { method.asteriskToken = asteriskToken; method.name = name; method.questionToken = questionToken; - fillSignature(SyntaxKind.ColonToken, /*yieldAndGeneratorParameterContext:*/ !!asteriskToken, /*requireCompleteParameterList:*/ false, method); + fillSignature(SyntaxKind.ColonToken, /*yieldAndGeneratorParameterContext*/ !!asteriskToken, /*requireCompleteParameterList*/ false, method); method.body = parseFunctionBlockOrSemicolon(!!asteriskToken, diagnosticMessage); return finishNode(method); } @@ -4143,7 +4188,20 @@ module ts { property.name = name; property.questionToken = questionToken; property.type = parseTypeAnnotation(); - property.initializer = allowInAnd(parseNonParameterInitializer); + + // 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 Initialiser_opt[In]; + // AccessibilityModifier_opt static_opt PropertyName TypeAnnotation_opt Initialiser_opt[In, ?Yield]; + // + // The checker may still error in the static case to explicitly disallow the yield expression. + property.initializer = modifiers && modifiers.flags & NodeFlags.Static + ? allowInAnd(parseNonParameterInitializer) + : doOutsideOfContext(ParserContextFlags.Yield | ParserContextFlags.DisallowIn, parseNonParameterInitializer); + parseSemicolon(); return finishNode(property); } @@ -4172,8 +4230,8 @@ module ts { node.decorators = decorators; setModifiers(node, modifiers); node.name = parsePropertyName(); - fillSignature(SyntaxKind.ColonToken, /*yieldAndGeneratorParameterContext:*/ false, /*requireCompleteParameterList:*/ false, node); - node.body = parseFunctionBlockOrSemicolon(/*isGenerator:*/ false); + fillSignature(SyntaxKind.ColonToken, /*yieldAndGeneratorParameterContext*/ false, /*requireCompleteParameterList*/ false, node); + node.body = parseFunctionBlockOrSemicolon(/*isGenerator*/ false); return finishNode(node); } @@ -4340,7 +4398,7 @@ module ts { return parsePropertyOrMethodDeclaration(fullStart, decorators, modifiers); } - if (decorators) { + if (decorators || modifiers) { // treat this as a property declaration with a missing name. let name = createMissingNode(SyntaxKind.Identifier, /*reportAtCurrentPosition*/ true, Diagnostics.Declaration_expected); return parsePropertyDeclaration(fullStart, decorators, modifiers, name, /*questionToken*/ undefined); @@ -4352,9 +4410,9 @@ module ts { function parseClassExpression(): ClassExpression { return parseClassDeclarationOrExpression( - /*fullStart:*/ scanner.getStartPos(), - /*decorators:*/ undefined, - /*modifiers:*/ undefined, + /*fullStart*/ scanner.getStartPos(), + /*decorators*/ undefined, + /*modifiers*/ undefined, SyntaxKind.ClassExpression); } @@ -4363,17 +4421,13 @@ module ts { } function parseClassDeclarationOrExpression(fullStart: number, decorators: NodeArray, modifiers: ModifiersArray, kind: SyntaxKind): ClassLikeDeclaration { - // In ES6 specification, All parts of a ClassDeclaration or a ClassExpression are strict mode code - let savedStrictModeContext = inStrictModeContext(); - setStrictModeContext(true); - var node = createNode(kind, fullStart); node.decorators = decorators; setModifiers(node, modifiers); parseExpected(SyntaxKind.ClassKeyword); node.name = parseOptionalIdentifier(); node.typeParameters = parseTypeParameters(); - node.heritageClauses = parseHeritageClauses(/*isClassHeritageClause:*/ true); + node.heritageClauses = parseHeritageClauses(/*isClassHeritageClause*/ true); if (parseExpected(SyntaxKind.OpenBraceToken)) { // ClassTail[Yield,GeneratorParameter] : See 14.5 @@ -4389,9 +4443,7 @@ module ts { node.members = createMissingList(); } - var finishedNode = finishNode(node); - setStrictModeContext(savedStrictModeContext); - return finishedNode; + return finishNode(node); } function parseHeritageClauses(isClassHeritageClause: boolean): NodeArray { @@ -4409,7 +4461,7 @@ module ts { } function parseHeritageClausesWorker() { - return parseList(ParsingContext.HeritageClauses, /*checkForStrictMode:*/ false, parseHeritageClause); + return parseList(ParsingContext.HeritageClauses, parseHeritageClause); } function parseHeritageClause() { @@ -4439,7 +4491,7 @@ module ts { } function parseClassMembers() { - return parseList(ParsingContext.ClassMembers, /*checkForStrictMode*/ false, parseClassElement); + return parseList(ParsingContext.ClassMembers, parseClassElement); } function parseInterfaceDeclaration(fullStart: number, decorators: NodeArray, modifiers: ModifiersArray): InterfaceDeclaration { @@ -4449,7 +4501,7 @@ module ts { parseExpected(SyntaxKind.InterfaceKeyword); node.name = parseIdentifier(); node.typeParameters = parseTypeParameters(); - node.heritageClauses = parseHeritageClauses(/*isClassHeritageClause:*/ false); + node.heritageClauses = parseHeritageClauses(/*isClassHeritageClause*/ false); node.members = parseObjectTypeMembers(); return finishNode(node); } @@ -4460,6 +4512,7 @@ module ts { setModifiers(node, modifiers); parseExpected(SyntaxKind.TypeKeyword); node.name = parseIdentifier(); + node.typeParameters = parseTypeParameters(); parseExpected(SyntaxKind.EqualsToken); node.type = parseType(); parseSemicolon(); @@ -4496,7 +4549,7 @@ module ts { function parseModuleBlock(): ModuleBlock { let node = createNode(SyntaxKind.ModuleBlock, scanner.getStartPos()); if (parseExpected(SyntaxKind.OpenBraceToken)) { - node.statements = parseList(ParsingContext.ModuleElements, /*checkForStrictMode*/false, parseModuleElement); + node.statements = parseList(ParsingContext.BlockStatements, parseStatement); parseExpected(SyntaxKind.CloseBraceToken); } else { @@ -4512,7 +4565,7 @@ module ts { node.flags |= flags; node.name = parseIdentifier(); node.body = parseOptional(SyntaxKind.DotToken) - ? parseModuleOrNamespaceDeclaration(getNodePos(), /*decorators*/ undefined, /*modifiers:*/undefined, NodeFlags.Export) + ? parseModuleOrNamespaceDeclaration(getNodePos(), /*decorators*/ undefined, /*modifiers*/ undefined, NodeFlags.Export) : parseModuleBlock(); return finishNode(node); } @@ -4521,7 +4574,7 @@ module ts { let node = createNode(SyntaxKind.ModuleDeclaration, fullStart); node.decorators = decorators; setModifiers(node, modifiers); - node.name = parseLiteralNode(/*internName:*/ true); + node.name = parseLiteralNode(/*internName*/ true); node.body = parseModuleBlock(); return finishNode(node); } @@ -4748,151 +4801,6 @@ module ts { return finishNode(node); } - function isLetDeclaration() { - // It is let declaration if in strict mode or next token is identifier\open bracket\open curly on same line. - // otherwise it needs to be treated like identifier - return inStrictModeContext() || lookAhead(nextTokenIsIdentifierOrStartOfDestructuringOnTheSameLine); - } - - function isDeclarationStart(followsModifier?: boolean): boolean { - switch (token) { - case SyntaxKind.VarKeyword: - case SyntaxKind.ConstKeyword: - case SyntaxKind.FunctionKeyword: - return true; - case SyntaxKind.LetKeyword: - return isLetDeclaration(); - case SyntaxKind.ClassKeyword: - case SyntaxKind.InterfaceKeyword: - case SyntaxKind.EnumKeyword: - case SyntaxKind.TypeKeyword: - // Not true keywords so ensure an identifier follows - return lookAhead(nextTokenIsIdentifierOrKeyword); - case SyntaxKind.ImportKeyword: - // Not true keywords so ensure an identifier follows or is string literal or asterisk or open brace - return lookAhead(nextTokenCanFollowImportKeyword); - case SyntaxKind.ModuleKeyword: - case SyntaxKind.NamespaceKeyword: - // Not a true keyword so ensure an identifier or string literal follows - return lookAhead(nextTokenIsIdentifierOrKeywordOrStringLiteral); - case SyntaxKind.ExportKeyword: - // Check for export assignment or modifier on source element - return lookAhead(nextTokenCanFollowExportKeyword); - case SyntaxKind.DeclareKeyword: - case SyntaxKind.PublicKeyword: - case SyntaxKind.PrivateKeyword: - case SyntaxKind.ProtectedKeyword: - case SyntaxKind.StaticKeyword: - // Check for modifier on source element - return lookAhead(nextTokenIsDeclarationStart); - case SyntaxKind.AtToken: - // a lookahead here is too costly, and decorators are only valid on a declaration. - // We will assume we are parsing a declaration here and report an error later - return !followsModifier; - } - } - - function isIdentifierOrKeyword() { - return token >= SyntaxKind.Identifier; - } - - function nextTokenIsIdentifierOrKeyword() { - nextToken(); - return isIdentifierOrKeyword(); - } - - function nextTokenIsIdentifierOrKeywordOrStringLiteral() { - nextToken(); - return isIdentifierOrKeyword() || token === SyntaxKind.StringLiteral; - } - - function nextTokenCanFollowImportKeyword() { - nextToken(); - return isIdentifierOrKeyword() || token === SyntaxKind.StringLiteral || - token === SyntaxKind.AsteriskToken || token === SyntaxKind.OpenBraceToken; - } - - function nextTokenCanFollowExportKeyword() { - nextToken(); - return token === SyntaxKind.EqualsToken || token === SyntaxKind.AsteriskToken || - token === SyntaxKind.OpenBraceToken || token === SyntaxKind.DefaultKeyword || isDeclarationStart(/*followsModifier*/ true); - } - - function nextTokenIsDeclarationStart() { - nextToken(); - return isDeclarationStart(/*followsModifier*/ true); - } - - function nextTokenIsAsKeyword() { - return nextToken() === SyntaxKind.AsKeyword; - } - - function parseDeclaration(): ModuleElement { - let fullStart = getNodePos(); - let decorators = parseDecorators(); - let modifiers = parseModifiers(); - if (token === SyntaxKind.ExportKeyword) { - nextToken(); - if (token === SyntaxKind.DefaultKeyword || token === SyntaxKind.EqualsToken) { - return parseExportAssignment(fullStart, decorators, modifiers); - } - if (token === SyntaxKind.AsteriskToken || token === SyntaxKind.OpenBraceToken) { - return parseExportDeclaration(fullStart, decorators, modifiers); - } - } - - switch (token) { - case SyntaxKind.VarKeyword: - case SyntaxKind.LetKeyword: - case SyntaxKind.ConstKeyword: - return parseVariableStatement(fullStart, decorators, modifiers); - case SyntaxKind.FunctionKeyword: - return parseFunctionDeclaration(fullStart, decorators, modifiers); - case SyntaxKind.ClassKeyword: - return parseClassDeclaration(fullStart, decorators, modifiers); - case SyntaxKind.InterfaceKeyword: - return parseInterfaceDeclaration(fullStart, decorators, modifiers); - case SyntaxKind.TypeKeyword: - return parseTypeAliasDeclaration(fullStart, decorators, modifiers); - case SyntaxKind.EnumKeyword: - return parseEnumDeclaration(fullStart, decorators, modifiers); - case SyntaxKind.ModuleKeyword: - case SyntaxKind.NamespaceKeyword: - return parseModuleDeclaration(fullStart, decorators, modifiers); - case SyntaxKind.ImportKeyword: - return parseImportDeclarationOrImportEqualsDeclaration(fullStart, decorators, modifiers); - default: - if (decorators) { - // We reached this point because we encountered an AtToken and assumed a declaration would - // follow. For recovery and error reporting purposes, return an incomplete declaration. - let node = createMissingNode(SyntaxKind.MissingDeclaration, /*reportAtCurrentPosition*/ true, Diagnostics.Declaration_expected); - node.pos = fullStart; - node.decorators = decorators; - setModifiers(node, modifiers); - return finishNode(node); - } - Debug.fail("Mismatch between isDeclarationStart and parseDeclaration"); - } - } - - function isSourceElement(inErrorRecovery: boolean): boolean { - return isDeclarationStart() || isStartOfStatement(inErrorRecovery); - } - - function parseSourceElement() { - return parseSourceElementOrModuleElement(); - } - - function parseModuleElement() { - return parseSourceElementOrModuleElement(); - } - - function parseSourceElementOrModuleElement(): ModuleElement { - return isDeclarationStart() - ? parseDeclaration() - : parseStatement(); - } - function processReferenceComments(sourceFile: SourceFile): void { let triviaScanner = createScanner(sourceFile.languageVersion, /*skipTrivia*/false, sourceText); let referencedFiles: FileReference[] = []; @@ -4953,7 +4861,7 @@ module ts { sourceFile.referencedFiles = referencedFiles; sourceFile.amdDependencies = amdDependencies; - sourceFile.amdModuleName = amdModuleName; + sourceFile.moduleName = amdModuleName; } function setExternalModuleIndicator(sourceFile: SourceFile) { @@ -4969,7 +4877,6 @@ module ts { const enum ParsingContext { SourceElements, // Elements in source file - ModuleElements, // Elements in module declaration BlockStatements, // Statements in block SwitchClauses, // Clauses in switch statement SwitchClauseStatements, // Statements in switch clause @@ -5049,13 +4956,6 @@ module ts { return finishNode(result); } - function setError(message: DiagnosticMessage) { - parseErrorAtCurrentToken(message); - if (throwOnJSDocErrors) { - throw new Error(message.key); - } - } - function parseJSDocTopLevelType(): JSDocType { var type = parseJSDocType(); if (token === SyntaxKind.BarToken) { @@ -5899,7 +5799,7 @@ module ts { 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); + moveElementEntirelyPastChangeRange(child, /*isArray*/ false, delta, oldText, newText, aggressiveChecks); return; } @@ -5928,7 +5828,7 @@ module ts { 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); + moveElementEntirelyPastChangeRange(array, /*isArray*/ true, delta, oldText, newText, aggressiveChecks); return; } diff --git a/src/compiler/program.ts b/src/compiler/program.ts index 38634f1dea6..2af9ad9987d 100644 --- a/src/compiler/program.ts +++ b/src/compiler/program.ts @@ -1,17 +1,14 @@ /// /// -module ts { +namespace ts { /* @internal */ export let programTime = 0; /* @internal */ export let emitTime = 0; /* @internal */ export let ioReadTime = 0; /* @internal */ export let ioWriteTime = 0; /** The version of the TypeScript compiler release */ - export const version = "1.5.2"; - - const carriageReturnLineFeed = "\r\n"; - const lineFeed = "\n"; + export const version = "1.5.3"; export function findConfigFile(searchPath: string): string { var fileName = "tsconfig.json"; @@ -94,10 +91,7 @@ module ts { } } - let newLine = - options.newLine === NewLineKind.CarriageReturnLineFeed ? carriageReturnLineFeed : - options.newLine === NewLineKind.LineFeed ? lineFeed : - sys.newLine; + const newLine = getNewLineCharacter(options); return { getSourceFile, @@ -111,7 +105,10 @@ module ts { } export function getPreEmitDiagnostics(program: Program, sourceFile?: SourceFile): Diagnostic[] { - let diagnostics = program.getSyntacticDiagnostics(sourceFile).concat(program.getGlobalDiagnostics()).concat(program.getSemanticDiagnostics(sourceFile)); + let diagnostics = program.getOptionsDiagnostics().concat( + program.getSyntacticDiagnostics(sourceFile), + program.getGlobalDiagnostics(), + program.getSemanticDiagnostics(sourceFile)); if (program.getCompilerOptions().declaration) { diagnostics.concat(program.getDeclarationDiagnostics(sourceFile)); @@ -149,20 +146,31 @@ module ts { export function createProgram(rootNames: string[], options: CompilerOptions, host?: CompilerHost): Program { let program: Program; let files: SourceFile[] = []; - let filesByName: Map = {}; let diagnostics = createDiagnosticCollection(); - let seenNoDefaultLib = options.noLib; + let commonSourceDirectory: string; let diagnosticsProducingTypeChecker: TypeChecker; let noDiagnosticsTypeChecker: TypeChecker; + let classifiableNames: Map; + + let skipDefaultLib = options.noLib; let start = new Date().getTime(); host = host || createCompilerHost(options); - forEach(rootNames, name => processRootFile(name, false)); - if (!seenNoDefaultLib) { - processRootFile(host.getDefaultLibFileName(options), true); + + let filesByName = createFileMap(fileName => host.getCanonicalFileName(fileName)); + + forEach(rootNames, name => processRootFile(name, /*isDefaultLib:*/ false)); + + // Do not process the default library if: + // - The '--noLib' flag is used. + // - A 'no-default-lib' reference comment is encountered in + // processing the root files. + if (!skipDefaultLib) { + processRootFile(host.getDefaultLibFileName(options), /*isDefaultLib:*/ true); } + verifyCompilerOptions(); programTime += new Date().getTime() - start; @@ -172,10 +180,12 @@ module ts { getSourceFiles: () => files, getCompilerOptions: () => options, getSyntacticDiagnostics, + getOptionsDiagnostics, getGlobalDiagnostics, getSemanticDiagnostics, getDeclarationDiagnostics, getTypeChecker, + getClassifiableNames, getDiagnosticsProducingTypeChecker, getCommonSourceDirectory: () => commonSourceDirectory, emit, @@ -187,6 +197,20 @@ module ts { }; return program; + function getClassifiableNames() { + if (!classifiableNames) { + // Initialize a checker so that all our files are bound. + getTypeChecker(); + classifiableNames = {}; + + for (let sourceFile of files) { + copyMap(sourceFile.classifiableNames, classifiableNames); + } + } + + return classifiableNames; + } + function getEmitHost(writeFileCallback?: WriteFileCallback): EmitHost { return { getCanonicalFileName: fileName => host.getCanonicalFileName(fileName), @@ -238,8 +262,7 @@ module ts { } function getSourceFile(fileName: string) { - fileName = host.getCanonicalFileName(normalizeSlashes(fileName)); - return hasProperty(filesByName, fileName) ? filesByName[fileName] : undefined; + return filesByName.get(fileName); } function getDiagnosticsHelper(sourceFile: SourceFile, getDiagnostics: (sourceFile: SourceFile) => Diagnostic[]): Diagnostic[] { @@ -291,13 +314,15 @@ module ts { } } - function getGlobalDiagnostics(): Diagnostic[] { - let typeChecker = getDiagnosticsProducingTypeChecker(); - + function getOptionsDiagnostics(): Diagnostic[] { let allDiagnostics: Diagnostic[] = []; - addRange(allDiagnostics, typeChecker.getGlobalDiagnostics()); addRange(allDiagnostics, diagnostics.getGlobalDiagnostics()); + return sortAndDeduplicateDiagnostics(allDiagnostics); + } + function getGlobalDiagnostics(): Diagnostic[] { + let allDiagnostics: Diagnostic[] = []; + addRange(allDiagnostics, getDiagnosticsProducingTypeChecker().getGlobalDiagnostics()); return sortAndDeduplicateDiagnostics(allDiagnostics); } @@ -334,14 +359,17 @@ module ts { } } else { - if (options.allowNonTsExtensions && !findSourceFile(fileName, isDefaultLib, refFile, refPos, refEnd)) { - diagnostic = Diagnostics.File_0_not_found; - diagnosticArgument = [fileName]; - } - else if (!forEach(supportedExtensions, extension => findSourceFile(fileName + extension, isDefaultLib, refFile, refPos, refEnd))) { - diagnostic = Diagnostics.File_0_not_found; - fileName += ".ts"; - diagnosticArgument = [fileName]; + var nonTsFile: SourceFile = options.allowNonTsExtensions && findSourceFile(fileName, isDefaultLib, refFile, refPos, refEnd); + if (!nonTsFile) { + if (options.allowNonTsExtensions) { + diagnostic = Diagnostics.File_0_not_found; + diagnosticArgument = [fileName]; + } + else if (!forEach(supportedExtensions, extension => findSourceFile(fileName + extension, isDefaultLib, refFile, refPos, refEnd))) { + diagnostic = Diagnostics.File_0_not_found; + fileName += ".ts"; + diagnosticArgument = [fileName]; + } } } @@ -358,19 +386,19 @@ module ts { // Get source file from normalized fileName function findSourceFile(fileName: string, isDefaultLib: boolean, refFile?: SourceFile, refStart?: number, refLength?: number): SourceFile { let canonicalName = host.getCanonicalFileName(normalizeSlashes(fileName)); - if (hasProperty(filesByName, canonicalName)) { + if (filesByName.contains(canonicalName)) { // We've already looked for this file, use cached result return getSourceFileFromCache(fileName, canonicalName, /*useAbsolutePath*/ false); } else { let normalizedAbsolutePath = getNormalizedAbsolutePath(fileName, host.getCurrentDirectory()); let canonicalAbsolutePath = host.getCanonicalFileName(normalizedAbsolutePath); - if (hasProperty(filesByName, canonicalAbsolutePath)) { + if (filesByName.contains(canonicalAbsolutePath)) { return getSourceFileFromCache(normalizedAbsolutePath, canonicalAbsolutePath, /*useAbsolutePath*/ true); } // We haven't looked for this file, do so now and cache result - let file = filesByName[canonicalName] = host.getSourceFile(fileName, options.target, hostErrorMessage => { + let file = host.getSourceFile(fileName, options.target, hostErrorMessage => { if (refFile) { diagnostics.add(createFileDiagnostic(refFile, refStart, refLength, Diagnostics.Cannot_read_file_0_Colon_1, fileName, hostErrorMessage)); @@ -379,11 +407,12 @@ module ts { diagnostics.add(createCompilerDiagnostic(Diagnostics.Cannot_read_file_0_Colon_1, fileName, hostErrorMessage)); } }); + filesByName.set(canonicalName, file); if (file) { - seenNoDefaultLib = seenNoDefaultLib || file.hasNoDefaultLib; + skipDefaultLib = skipDefaultLib || file.hasNoDefaultLib; // Set the source file for normalized absolute path - filesByName[canonicalAbsolutePath] = file; + filesByName.set(canonicalAbsolutePath, file); if (!options.noResolve) { let basePath = getDirectoryPath(fileName); @@ -391,6 +420,7 @@ module ts { processImportedModules(file, basePath); } if (isDefaultLib) { + file.isDefaultLib = true; files.unshift(file); } else { @@ -402,7 +432,7 @@ module ts { } function getSourceFileFromCache(fileName: string, canonicalName: string, useAbsolutePath: boolean): SourceFile { - let file = filesByName[canonicalName]; + let file = filesByName.get(canonicalName); if (file && host.useCaseSensitiveFileNames()) { let sourceFileName = useAbsolutePath ? getNormalizedAbsolutePath(file.fileName, host.getCurrentDirectory()) : file.fileName; if (canonicalName !== sourceFileName) { @@ -534,21 +564,21 @@ module ts { } function verifyCompilerOptions() { - if (options.separateCompilation) { + if (options.isolatedModules) { if (options.sourceMap) { - diagnostics.add(createCompilerDiagnostic(Diagnostics.Option_sourceMap_cannot_be_specified_with_option_separateCompilation)); + diagnostics.add(createCompilerDiagnostic(Diagnostics.Option_sourceMap_cannot_be_specified_with_option_isolatedModules)); } if (options.declaration) { - diagnostics.add(createCompilerDiagnostic(Diagnostics.Option_declaration_cannot_be_specified_with_option_separateCompilation)); + diagnostics.add(createCompilerDiagnostic(Diagnostics.Option_declaration_cannot_be_specified_with_option_isolatedModules)); } if (options.noEmitOnError) { - diagnostics.add(createCompilerDiagnostic(Diagnostics.Option_noEmitOnError_cannot_be_specified_with_option_separateCompilation)); + diagnostics.add(createCompilerDiagnostic(Diagnostics.Option_noEmitOnError_cannot_be_specified_with_option_isolatedModules)); } if (options.out) { - diagnostics.add(createCompilerDiagnostic(Diagnostics.Option_out_cannot_be_specified_with_option_separateCompilation)); + diagnostics.add(createCompilerDiagnostic(Diagnostics.Option_out_cannot_be_specified_with_option_isolatedModules)); } } @@ -585,15 +615,15 @@ module ts { let languageVersion = options.target || ScriptTarget.ES3; let firstExternalModuleSourceFile = forEach(files, f => isExternalModule(f) ? f : undefined); - if (options.separateCompilation) { + if (options.isolatedModules) { if (!options.module && languageVersion < ScriptTarget.ES6) { - diagnostics.add(createCompilerDiagnostic(Diagnostics.Option_separateCompilation_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES6_or_higher)); + diagnostics.add(createCompilerDiagnostic(Diagnostics.Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES6_or_higher)); } let firstNonExternalModuleSourceFile = forEach(files, f => !isExternalModule(f) && !isDeclarationFile(f) ? f : undefined); if (firstNonExternalModuleSourceFile) { let span = getErrorSpanForNode(firstNonExternalModuleSourceFile, firstNonExternalModuleSourceFile); - diagnostics.add(createFileDiagnostic(firstNonExternalModuleSourceFile, span.start, span.length, Diagnostics.Cannot_compile_namespaces_when_the_separateCompilation_flag_is_provided)); + diagnostics.add(createFileDiagnostic(firstNonExternalModuleSourceFile, span.start, span.length, Diagnostics.Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided)); } } else if (firstExternalModuleSourceFile && languageVersion < ScriptTarget.ES6 && !options.module) { @@ -640,6 +670,11 @@ module ts { diagnostics.add(createCompilerDiagnostic(Diagnostics.Option_noEmit_cannot_be_specified_with_option_declaration)); } } + + if (options.emitDecoratorMetadata && + !options.experimentalDecorators) { + diagnostics.add(createCompilerDiagnostic(Diagnostics.Option_experimentalDecorators_must_also_be_specified_when_option_emitDecoratorMetadata_is_specified)); + } } } -} \ No newline at end of file +} diff --git a/src/compiler/scanner.ts b/src/compiler/scanner.ts index 89ac837ab24..bcc31c39002 100644 --- a/src/compiler/scanner.ts +++ b/src/compiler/scanner.ts @@ -1,7 +1,7 @@ /// /// -module ts { +namespace ts { export interface ErrorCallback { (message: DiagnosticMessage, length: number): void; } @@ -72,6 +72,7 @@ module ts { "in": SyntaxKind.InKeyword, "instanceof": SyntaxKind.InstanceOfKeyword, "interface": SyntaxKind.InterfaceKeyword, + "is": SyntaxKind.IsKeyword, "let": SyntaxKind.LetKeyword, "module": SyntaxKind.ModuleKeyword, "namespace": SyntaxKind.NamespaceKeyword, @@ -375,8 +376,31 @@ module ts { return ch >= CharacterCodes._0 && ch <= CharacterCodes._7; } + export function couldStartTrivia(text: string, pos: number): boolean { + // Keep in sync with skipTrivia + let ch = text.charCodeAt(pos); + switch (ch) { + case CharacterCodes.carriageReturn: + case CharacterCodes.lineFeed: + case CharacterCodes.tab: + case CharacterCodes.verticalTab: + case CharacterCodes.formFeed: + case CharacterCodes.space: + case CharacterCodes.slash: + // starts of normal trivia + case CharacterCodes.lessThan: + case CharacterCodes.equals: + case CharacterCodes.greaterThan: + // Starts of conflict marker trivia + return true; + default: + return ch > CharacterCodes.maxAsciiCharacter; + } + } + /* @internal */ export function skipTrivia(text: string, pos: number, stopAfterLineBreak?: boolean): number { + // Keep in sync with couldStartTrivia while (true) { let ch = text.charCodeAt(pos); switch (ch) { @@ -933,7 +957,7 @@ module ts { error(Diagnostics.Unexpected_end_of_text); isInvalidExtendedEscape = true; } - else if (text.charCodeAt(pos) == CharacterCodes.closeBrace) { + else if (text.charCodeAt(pos) === CharacterCodes.closeBrace) { // Only swallow the following character up if it's a '}'. pos++; } diff --git a/src/compiler/sys.ts b/src/compiler/sys.ts index f9daf52c5f2..a47d6959ba8 100644 --- a/src/compiler/sys.ts +++ b/src/compiler/sys.ts @@ -1,6 +1,6 @@ /// -module ts { +namespace ts { export interface System { args: string[]; newLine: string; @@ -15,7 +15,7 @@ module ts { createDirectory(path: string): void; getExecutingFilePath(): string; getCurrentDirectory(): string; - readDirectory(path: string, extension?: string): string[]; + readDirectory(path: string, extension?: string, exclude?: string[]): string[]; getMemoryUsage?(): number; exit(exitCode?: number): void; } @@ -109,7 +109,11 @@ module ts { } } - function getNames(collection: any): string[] { + function getCanonicalPath(path: string): string { + return path.toLowerCase(); + } + + function getNames(collection: any): string[]{ var result: string[] = []; for (var e = new Enumerator(collection); !e.atEnd(); e.moveNext()) { result.push(e.item().Name); @@ -117,21 +121,26 @@ module ts { return result.sort(); } - function readDirectory(path: string, extension?: string): string[] { + function readDirectory(path: string, extension?: string, exclude?: string[]): string[] { var result: string[] = []; + exclude = map(exclude, s => getCanonicalPath(combinePaths(path, s))); visitDirectory(path); return result; function visitDirectory(path: string) { var folder = fso.GetFolder(path || "."); var files = getNames(folder.files); - for (let name of files) { - if (!extension || fileExtensionIs(name, extension)) { - result.push(combinePaths(path, name)); + for (let current of files) { + let name = combinePaths(path, current); + if ((!extension || fileExtensionIs(name, extension)) && !contains(exclude, getCanonicalPath(name))) { + result.push(name); } } var subfolders = getNames(folder.subfolders); for (let current of subfolders) { - visitDirectory(combinePaths(path, current)); + let name = combinePaths(path, current); + if (!contains(exclude, getCanonicalPath(name))) { + visitDirectory(name); + } } } } @@ -222,8 +231,13 @@ module ts { _fs.writeFileSync(fileName, data, "utf8"); } - function readDirectory(path: string, extension?: string): string[] { + function getCanonicalPath(path: string): string { + return useCaseSensitiveFileNames ? path.toLowerCase() : path; + } + + function readDirectory(path: string, extension?: string, exclude?: string[]): string[] { var result: string[] = []; + exclude = map(exclude, s => getCanonicalPath(combinePaths(path, s))); visitDirectory(path); return result; function visitDirectory(path: string) { @@ -231,14 +245,16 @@ module ts { var directories: string[] = []; for (let current of files) { var name = combinePaths(path, current); - var stat = _fs.lstatSync(name); - if (stat.isFile()) { - if (!extension || fileExtensionIs(name, extension)) { - result.push(name); + if (!contains(exclude, getCanonicalPath(name))) { + var stat = _fs.statSync(name); + if (stat.isFile()) { + if (!extension || fileExtensionIs(name, extension)) { + result.push(name); + } + } + else if (stat.isDirectory()) { + directories.push(name); } - } - else if (stat.isDirectory()) { - directories.push(name); } } for (let current of directories) { diff --git a/src/compiler/tsc.ts b/src/compiler/tsc.ts index 15cc665e351..2903c3a31f4 100644 --- a/src/compiler/tsc.ts +++ b/src/compiler/tsc.ts @@ -1,7 +1,7 @@ /// /// -module ts { +namespace ts { export interface SourceFile { fileWatcher: FileWatcher; } diff --git a/src/compiler/types.ts b/src/compiler/types.ts index 8cdcffabc1b..d858e430ab6 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -1,8 +1,16 @@ -module ts { +namespace ts { export interface Map { [index: string]: T; } + export interface FileMap { + get(fileName: string): T; + set(fileName: string, value: T): void; + contains(fileName: string): boolean; + remove(fileName: string): void; + forEachValue(f: (v: T) => void): void; + } + export interface TextRange { pos: number; end: number; @@ -137,6 +145,7 @@ module ts { ConstructorKeyword, DeclareKeyword, GetKeyword, + IsKeyword, ModuleKeyword, NamespaceKeyword, RequireKeyword, @@ -169,6 +178,7 @@ module ts { ConstructSignature, IndexSignature, // Type + TypePredicate, TypeReference, FunctionType, ConstructorType, @@ -352,10 +362,6 @@ module ts { export const enum ParserContextFlags { None = 0, - // Set if this node was parsed in strict mode. Used for grammar error checks, as well as - // checking if the node can be reused in incremental settings. - StrictMode = 1 << 0, - // If this node was parsed in a context where 'in-expressions' are not allowed. DisallowIn = 1 << 1, @@ -378,7 +384,7 @@ module ts { JavaScriptFile = 1 << 6, // Context flags set directly by the parser. - ParserGeneratedFlags = StrictMode | DisallowIn | Yield | GeneratorParameter | Decorator | ThisNodeHasError, + ParserGeneratedFlags = DisallowIn | Yield | GeneratorParameter | Decorator | ThisNodeHasError, // Context flags computed by aggregating child flags upwards. @@ -606,6 +612,11 @@ module ts { typeArguments?: NodeArray; } + export interface TypePredicateNode extends TypeNode { + parameterName: Identifier; + type: TypeNode; + } + export interface TypeQueryNode extends TypeNode { exprName: EntityName; } @@ -693,7 +704,7 @@ module ts { export interface YieldExpression extends Expression { asteriskToken?: Node; - expression: Expression; + expression?: Expression; } export interface BinaryExpression extends Expression { @@ -793,7 +804,7 @@ module ts { expression: UnaryExpression; } - export interface Statement extends Node, ModuleElement { + export interface Statement extends Node { _statementBrand: any; } @@ -896,10 +907,6 @@ module ts { block: Block; } - export interface ModuleElement extends Node { - _moduleElementBrand: any; - } - export interface ClassLikeDeclaration extends Declaration { name?: Identifier; typeParameters?: NodeArray; @@ -917,7 +924,7 @@ module ts { _classElementBrand: any; } - export interface InterfaceDeclaration extends Declaration, ModuleElement { + export interface InterfaceDeclaration extends Declaration, Statement { name: Identifier; typeParameters?: NodeArray; heritageClauses?: NodeArray; @@ -929,8 +936,9 @@ module ts { types?: NodeArray; } - export interface TypeAliasDeclaration extends Declaration, ModuleElement { + export interface TypeAliasDeclaration extends Declaration, Statement { name: Identifier; + typeParameters?: NodeArray; type: TypeNode; } @@ -941,21 +949,21 @@ module ts { initializer?: Expression; } - export interface EnumDeclaration extends Declaration, ModuleElement { + export interface EnumDeclaration extends Declaration, Statement { name: Identifier; members: NodeArray; } - export interface ModuleDeclaration extends Declaration, ModuleElement { + export interface ModuleDeclaration extends Declaration, Statement { name: Identifier | LiteralExpression; body: ModuleBlock | ModuleDeclaration; } - export interface ModuleBlock extends Node, ModuleElement { - statements: NodeArray + export interface ModuleBlock extends Node, Statement { + statements: NodeArray } - export interface ImportEqualsDeclaration extends Declaration, ModuleElement { + export interface ImportEqualsDeclaration extends Declaration, Statement { name: Identifier; // 'EntityName' for an internal module reference, 'ExternalModuleReference' for an external @@ -971,7 +979,7 @@ module ts { // import "mod" => importClause = undefined, moduleSpecifier = "mod" // In rest of the cases, module specifier is string literal corresponding to module // ImportClause information is shown at its declaration below. - export interface ImportDeclaration extends ModuleElement { + export interface ImportDeclaration extends Statement { importClause?: ImportClause; moduleSpecifier: Expression; } @@ -991,7 +999,7 @@ module ts { name: Identifier; } - export interface ExportDeclaration extends Declaration, ModuleElement { + export interface ExportDeclaration extends Declaration, Statement { exportClause?: NamedExports; moduleSpecifier?: Expression; } @@ -1011,7 +1019,7 @@ module ts { export type ImportSpecifier = ImportOrExportSpecifier; export type ExportSpecifier = ImportOrExportSpecifier; - export interface ExportAssignment extends Declaration, ModuleElement { + export interface ExportAssignment extends Declaration, Statement { isExportEquals?: boolean; expression: Expression; } @@ -1127,23 +1135,32 @@ module ts { // Source files are declarations when they are external modules. export interface SourceFile extends Declaration { - statements: NodeArray; + statements: NodeArray; endOfFileToken: Node; fileName: string; text: string; amdDependencies: {path: string; name: string}[]; - amdModuleName: string; + moduleName: string; referencedFiles: FileReference[]; + /** + * lib.d.ts should have a reference comment like + * + * /// + * + * If any other file has this comment, it signals not to include lib.d.ts + * because this containing file is intended to act as a default library. + */ hasNoDefaultLib: boolean; languageVersion: ScriptTarget; // The first node that causes this file to be an external module /* @internal */ externalModuleIndicator: Node; - + + /* @internal */ isDefaultLib: boolean; /* @internal */ identifiers: Map; /* @internal */ nodeCount: number; /* @internal */ identifierCount: number; @@ -1159,6 +1176,8 @@ module ts { // Stores a line map for the file. // This field should never be used directly to obtain line map, use getLineMap function instead. /* @internal */ lineMap: number[]; + + /* @internal */ classifiableNames?: Map; } export interface ScriptReferenceHost { @@ -1168,7 +1187,7 @@ module ts { } export interface ParseConfigHost { - readDirectory(rootDir: string, extension: string): string[]; + readDirectory(rootDir: string, extension: string, exclude: string[]): string[]; } export interface WriteFileCallback { @@ -1193,8 +1212,9 @@ module ts { */ emit(targetSourceFile?: SourceFile, writeFile?: WriteFileCallback): EmitResult; - getSyntacticDiagnostics(sourceFile?: SourceFile): Diagnostic[]; + getOptionsDiagnostics(): Diagnostic[]; getGlobalDiagnostics(): Diagnostic[]; + getSyntacticDiagnostics(sourceFile?: SourceFile): Diagnostic[]; getSemanticDiagnostics(sourceFile?: SourceFile): Diagnostic[]; getDeclarationDiagnostics(sourceFile?: SourceFile): Diagnostic[]; @@ -1209,6 +1229,8 @@ module ts { // language service). /* @internal */ getDiagnosticsProducingTypeChecker(): TypeChecker; + /* @internal */ getClassifiableNames(): Map; + /* @internal */ getNodeCount(): number; /* @internal */ getIdentifierCount(): number; /* @internal */ getSymbolCount(): number; @@ -1376,6 +1398,12 @@ module ts { NotAccessible, CannotBeNamed } + + export interface TypePredicate { + parameterName: string; + parameterIndex: number; + type: Type; + } /* @internal */ export type AnyImportSyntax = ImportDeclaration | ImportEqualsDeclaration; @@ -1396,7 +1424,10 @@ module ts { /* @internal */ export interface EmitResolver { hasGlobalName(name: string): boolean; - getExpressionNameSubstitution(node: Identifier, getGeneratedNameForNode: (node: Node) => string): string; + getReferencedExportContainer(node: Identifier): SourceFile | ModuleDeclaration | EnumDeclaration; + getReferencedImportDeclaration(node: Identifier): Declaration; + getReferencedNestedRedeclaration(node: Identifier): Declaration; + isNestedRedeclaration(node: Declaration): boolean; isValueAliasDeclaration(node: Node): boolean; isReferencedAliasDeclaration(node: Node, checkChildren?: boolean): boolean; isTopLevelValueImportEqualsWithEntityName(node: ImportEqualsDeclaration): boolean; @@ -1411,15 +1442,15 @@ module ts { isEntityNameVisible(entityName: EntityName | Expression, enclosingDeclaration: Node): SymbolVisibilityResult; // Returns the constant value this property access resolves to, or 'undefined' for a non-constant getConstantValue(node: EnumMember | PropertyAccessExpression | ElementAccessExpression): number; - resolvesToSomeValue(location: Node, name: string): boolean; getBlockScopedVariableId(node: Identifier): number; getReferencedValueDeclaration(reference: Identifier): Declaration; - serializeTypeOfNode(node: Node, getGeneratedNameForNode: (Node: Node) => string): string | string[]; - serializeParameterTypesOfNode(node: Node, getGeneratedNameForNode: (Node: Node) => string): (string | string[])[]; - serializeReturnTypeOfNode(node: Node, getGeneratedNameForNode: (Node: Node) => string): string | string[]; + serializeTypeOfNode(node: Node): string | string[]; + serializeParameterTypesOfNode(node: Node): (string | string[])[]; + serializeReturnTypeOfNode(node: Node): string | string[]; } export const enum SymbolFlags { + None = 0, FunctionScopedVariable = 0x00000001, // Variable (var) or parameter BlockScopedVariable = 0x00000002, // A block-scoped variable (let or const) Property = 0x00000004, // Property or enum member @@ -1489,26 +1520,32 @@ module ts { ExportHasLocal = Function | Class | Enum | ValueModule, - HasLocals = Function | Module | Method | Constructor | Accessor | Signature, HasExports = Class | Enum | Module, HasMembers = Class | Interface | TypeLiteral | ObjectLiteral, - IsContainer = HasLocals | HasExports | HasMembers, + BlockScoped = BlockScopedVariable | Class | Enum, + PropertyOrAccessor = Property | Accessor, Export = ExportNamespace | ExportType | ExportValue, + + /* @internal */ + // The set of things we consider semantically classifiable. Used to speed up the LS during + // classification. + Classifiable = Class | Enum | TypeAlias | Interface | TypeParameter | Module, } export interface Symbol { flags: SymbolFlags; // Symbol flags name: string; // Name of symbol - /* @internal */ id?: number; // Unique id (used to look up SymbolLinks) - /* @internal */ mergeId?: number; // Merge id (used to look up merged symbol) declarations?: Declaration[]; // Declarations associated with this symbol - /* @internal */ parent?: Symbol; // Parent symbol + valueDeclaration?: Declaration; // First value declaration of the symbol + members?: SymbolTable; // Class, interface or literal instance members exports?: SymbolTable; // Module exports + /* @internal */ id?: number; // Unique id (used to look up SymbolLinks) + /* @internal */ mergeId?: number; // Merge id (used to look up merged symbol) + /* @internal */ parent?: Symbol; // Parent symbol /* @internal */ exportSymbol?: Symbol; // Exported symbol associated with this symbol - valueDeclaration?: Declaration; // First value declaration of the symbol /* @internal */ constEnumOnlyModule?: boolean; // True if module contains only const enums or other modules with only const enums } @@ -1516,12 +1553,15 @@ module ts { export interface SymbolLinks { target?: Symbol; // Resolved (non-alias) target of an alias type?: Type; // Type of value symbol - declaredType?: Type; // Type of class, interface, enum, or type parameter + declaredType?: Type; // Type of class, interface, enum, type alias, or type parameter + typeParameters?: TypeParameter[]; // Type parameters of type alias (undefined if non-generic) + instantiations?: Map; // Instantiations of generic type alias (undefined if non-generic) mapper?: TypeMapper; // Type mapper for instantiation alias referenced?: boolean; // True if alias symbol has been referenced as a value unionType?: UnionType; // Containing union type for union property resolvedExports?: SymbolTable; // Resolved exports of module exportsChecked?: boolean; // True if exports of external module have been checked + isNestedRedeclaration?: boolean; // True if symbol is block scoped redeclaration } /* @internal */ @@ -1582,14 +1622,15 @@ module ts { Tuple = 0x00002000, // Tuple Union = 0x00004000, // Union Anonymous = 0x00008000, // Anonymous - /* @internal */ - FromSignature = 0x00010000, // Created for signature assignment check - ObjectLiteral = 0x00020000, // Originates in an object literal - /* @internal */ - ContainsUndefinedOrNull = 0x00040000, // Type is or contains Undefined or Null type - /* @internal */ - ContainsObjectLiteral = 0x00080000, // Type is or contains object literal type - ESSymbol = 0x00100000, // Type of symbol primitive introduced in ES6 + Instantiated = 0x00010000, // Instantiated anonymous type + /* @internal */ + FromSignature = 0x00020000, // Created for signature assignment check + ObjectLiteral = 0x00040000, // Originates in an object literal + /* @internal */ + ContainsUndefinedOrNull = 0x00080000, // Type is or contains Undefined or Null type + /* @internal */ + ContainsObjectLiteral = 0x00100000, // Type is or contains object literal type + ESSymbol = 0x00200000, // Type of symbol primitive introduced in ES6 /* @internal */ Intrinsic = Any | String | Number | Boolean | ESSymbol | Void | Undefined | Null, @@ -1626,10 +1667,10 @@ module ts { // Class and interface types (TypeFlags.Class and TypeFlags.Interface) export interface InterfaceType extends ObjectType { typeParameters: TypeParameter[]; // Type parameters (undefined if non-generic) - } - - export interface InterfaceTypeWithBaseTypes extends InterfaceType { - baseTypes: ObjectType[]; + outerTypeParameters: TypeParameter[]; // Outer type parameters (undefined if none) + localTypeParameters: TypeParameter[]; // Local type parameters (undefined if none) + resolvedBaseConstructorType?: Type; // Resolved base constructor type of class + resolvedBaseTypes: ObjectType[]; // Resolved base types } export interface InterfaceTypeWithDeclaredMembers extends InterfaceType { @@ -1672,8 +1713,15 @@ module ts { properties: Symbol[]; // Properties callSignatures: Signature[]; // Call signatures of type constructSignatures: Signature[]; // Construct signatures of type - stringIndexType: Type; // String index type - numberIndexType: Type; // Numeric index type + stringIndexType?: Type; // String index type + numberIndexType?: Type; // Numeric index type + } + + // Just a place to cache element types of iterables and iterators + /* @internal */ + export interface IterableOrIteratorType extends ObjectType, UnionType { + iterableElementType?: Type; + iteratorElementType?: Type; } // Type parameters (TypeFlags.TypeParameter) @@ -1694,6 +1742,7 @@ module ts { declaration: SignatureDeclaration; // Originating declaration typeParameters: TypeParameter[]; // Type parameters (undefined if non-generic) parameters: Symbol[]; // Parameters + typePredicate?: TypePredicate; // Type predicate /* @internal */ resolvedReturnType: Type; // Resolved return type /* @internal */ @@ -1722,7 +1771,6 @@ module ts { /* @internal */ export interface TypeMapper { (t: TypeParameter): Type; - mappings?: Map; // Type mapping cache } /* @internal */ @@ -1810,9 +1858,14 @@ module ts { target?: ScriptTarget; version?: boolean; watch?: boolean; - separateCompilation?: boolean; + isolatedModules?: boolean; + experimentalDecorators?: boolean; emitDecoratorMetadata?: boolean; /* @internal */ stripInternal?: boolean; + + // Skip checking lib.d.ts to help speed up tests. + /* @internal */ skipDefaultLibCheck?: boolean; + [option: string]: string | number | boolean; } diff --git a/src/compiler/utilities.ts b/src/compiler/utilities.ts index bff1b99901f..d65ec79fddb 100644 --- a/src/compiler/utilities.ts +++ b/src/compiler/utilities.ts @@ -1,7 +1,7 @@ /// /* @internal */ -module ts { +namespace ts { export interface ReferencePathMatchResult { fileReference?: FileReference diagnosticMessage?: DiagnosticMessage @@ -42,7 +42,7 @@ module ts { // Pool writers to avoid needing to allocate them for every symbol we write. let stringWriters: StringSymbolWriter[] = []; export function getSingleLineStringWriter(): StringSymbolWriter { - if (stringWriters.length == 0) { + if (stringWriters.length === 0) { let str = ""; let writeText: (text: string) => void = text => str += text; @@ -408,6 +408,93 @@ module ts { export let fullTripleSlashReferencePathRegEx = /^(\/\/\/\s*/ + export function isTypeNode(node: Node): boolean { + if (SyntaxKind.FirstTypeNode <= node.kind && node.kind <= SyntaxKind.LastTypeNode) { + return true; + } + + switch (node.kind) { + case SyntaxKind.AnyKeyword: + case SyntaxKind.NumberKeyword: + case SyntaxKind.StringKeyword: + case SyntaxKind.BooleanKeyword: + case SyntaxKind.SymbolKeyword: + return true; + case SyntaxKind.VoidKeyword: + return node.parent.kind !== SyntaxKind.VoidExpression; + case SyntaxKind.StringLiteral: + // Specialized signatures can have string literals as their parameters' type names + return node.parent.kind === SyntaxKind.Parameter; + case SyntaxKind.ExpressionWithTypeArguments: + return !isExpressionWithTypeArgumentsInClassExtendsClause(node); + + // Identifiers and qualified names may be type nodes, depending on their context. Climb + // above them to find the lowest container + case SyntaxKind.Identifier: + // If the identifier is the RHS of a qualified name, then it's a type iff its parent is. + if (node.parent.kind === SyntaxKind.QualifiedName && (node.parent).right === node) { + node = node.parent; + } + else if (node.parent.kind === SyntaxKind.PropertyAccessExpression && (node.parent).name === node) { + node = node.parent; + } + // fall through + case SyntaxKind.QualifiedName: + case SyntaxKind.PropertyAccessExpression: + // At this point, node is either a qualified name or an identifier + Debug.assert(node.kind === SyntaxKind.Identifier || node.kind === SyntaxKind.QualifiedName || node.kind === SyntaxKind.PropertyAccessExpression, + "'node' was expected to be a qualified name, identifier or property access in 'isTypeNode'."); + + let parent = node.parent; + if (parent.kind === SyntaxKind.TypeQuery) { + return false; + } + // Do not recursively call isTypeNode on the parent. In the example: + // + // let a: A.B.C; + // + // Calling isTypeNode would consider the qualified name A.B a type node. Only C or + // A.B.C is a type node. + if (SyntaxKind.FirstTypeNode <= parent.kind && parent.kind <= SyntaxKind.LastTypeNode) { + return true; + } + switch (parent.kind) { + case SyntaxKind.ExpressionWithTypeArguments: + return !isExpressionWithTypeArgumentsInClassExtendsClause(parent); + case SyntaxKind.TypeParameter: + return node === (parent).constraint; + case SyntaxKind.PropertyDeclaration: + case SyntaxKind.PropertySignature: + case SyntaxKind.Parameter: + case SyntaxKind.VariableDeclaration: + return node === (parent).type; + case SyntaxKind.FunctionDeclaration: + case SyntaxKind.FunctionExpression: + case SyntaxKind.ArrowFunction: + case SyntaxKind.Constructor: + case SyntaxKind.MethodDeclaration: + case SyntaxKind.MethodSignature: + case SyntaxKind.GetAccessor: + case SyntaxKind.SetAccessor: + return node === (parent).type; + case SyntaxKind.CallSignature: + case SyntaxKind.ConstructSignature: + case SyntaxKind.IndexSignature: + return node === (parent).type; + case SyntaxKind.TypeAssertionExpression: + return node === (parent).type; + case SyntaxKind.CallExpression: + case SyntaxKind.NewExpression: + return (parent).typeArguments && indexOf((parent).typeArguments, node) >= 0; + case SyntaxKind.TaggedTemplateExpression: + // TODO (drosen): TaggedTemplateExpressions may eventually support type arguments. + return false; + } + } + + return false; + } + // 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. export function forEachReturnStatement(body: Block, visitor: (stmt: ReturnStatement) => T): T { @@ -438,6 +525,46 @@ module ts { } } + export function forEachYieldExpression(body: Block, visitor: (expr: YieldExpression) => void): void { + + return traverse(body); + + function traverse(node: Node): void { + switch (node.kind) { + case SyntaxKind.YieldExpression: + visitor(node); + let operand = (node).expression; + if (operand) { + traverse(operand); + } + case SyntaxKind.EnumDeclaration: + case SyntaxKind.InterfaceDeclaration: + case SyntaxKind.ModuleDeclaration: + case SyntaxKind.TypeAliasDeclaration: + case SyntaxKind.ClassDeclaration: + // These are not allowed inside a generator now, but eventually they may be allowed + // as local types. Regardless, any yield statements contained within them should be + // skipped in this traversal. + return; + default: + if (isFunctionLike(node)) { + let name = (node).name; + if (name && name.kind === SyntaxKind.ComputedPropertyName) { + // Note that we will not include methods/accessors of a class because they would require + // first descending into the class. This is by design. + traverse((name).expression); + return; + } + } + else if (!isTypeNode(node)) { + // This is the general case, which should include mostly expressions and statements. + // Also includes NodeArrays. + forEachChild(node, traverse); + } + } + } + } + export function isVariableLike(node: Node): boolean { if (node) { switch (node.kind) { @@ -739,12 +866,12 @@ module ts { case SyntaxKind.TemplateExpression: case SyntaxKind.NoSubstitutionTemplateLiteral: case SyntaxKind.OmittedExpression: + case SyntaxKind.YieldExpression: return true; case SyntaxKind.QualifiedName: while (node.parent.kind === SyntaxKind.QualifiedName) { node = node.parent; } - return node.parent.kind === SyntaxKind.TypeQuery; case SyntaxKind.Identifier: if (node.parent.kind === SyntaxKind.TypeQuery) { @@ -792,6 +919,8 @@ module ts { return node === (parent).expression; case SyntaxKind.Decorator: return true; + case SyntaxKind.ExpressionWithTypeArguments: + return (parent).expression === node && isExpressionWithTypeArgumentsInClassExtendsClause(parent); default: if (isExpression(parent)) { return true; @@ -835,10 +964,6 @@ module ts { } } - export function hasDotDotDotToken(node: Node) { - return node && node.kind === SyntaxKind.Parameter && (node).dotDotDotToken !== undefined; - } - export function hasQuestionToken(node: Node) { if (node) { switch (node.kind) { @@ -858,10 +983,6 @@ module ts { return false; } - export function hasRestParameters(s: SignatureDeclaration): boolean { - return s.parameters.length > 0 && lastOrUndefined(s.parameters).dotDotDotToken !== undefined; - } - export function isJSDocConstructSignature(node: Node) { return node.kind === SyntaxKind.JSDocFunctionType && (node).parameters.length > 0 && @@ -1057,6 +1178,41 @@ module ts { return false; } + // Return true if the given identifier is classified as an IdentifierName + export function isIdentifierName(node: Identifier): boolean { + let parent = node.parent; + switch (parent.kind) { + case SyntaxKind.PropertyDeclaration: + case SyntaxKind.PropertySignature: + case SyntaxKind.MethodDeclaration: + case SyntaxKind.MethodSignature: + case SyntaxKind.GetAccessor: + case SyntaxKind.SetAccessor: + case SyntaxKind.EnumMember: + case SyntaxKind.PropertyAssignment: + case SyntaxKind.PropertyAccessExpression: + // Name in member declaration or property name in property access + return (parent).name === node; + case SyntaxKind.QualifiedName: + // Name on right hand side of dot in a type query + if ((parent).right === node) { + while (parent.kind === SyntaxKind.QualifiedName) { + parent = parent.parent; + } + return parent.kind === SyntaxKind.TypeQuery; + } + return false; + case SyntaxKind.BindingElement: + case SyntaxKind.ImportSpecifier: + // Property name in binding element or import specifier + return (parent).propertyName === node; + case SyntaxKind.ExportSpecifier: + // Any name in an export specifier + return true; + } + return false; + } + // An alias symbol is created by one of the following declarations: // import = ... // import from ... @@ -1525,7 +1681,7 @@ module ts { if ((isExternalModule(sourceFile) || !compilerOptions.out)) { // 1. in-browser single file compilation scenario // 2. non .js file - return compilerOptions.separateCompilation || !fileExtensionIs(sourceFile.fileName, ".js"); + return compilerOptions.isolatedModules || !fileExtensionIs(sourceFile.fileName, ".js"); } return false; } @@ -1758,6 +1914,12 @@ module ts { return token >= SyntaxKind.FirstAssignment && token <= SyntaxKind.LastAssignment; } + export function isExpressionWithTypeArgumentsInClassExtendsClause(node: Node): boolean { + return node.kind === SyntaxKind.ExpressionWithTypeArguments && + (node.parent).token === SyntaxKind.ExtendsKeyword && + node.parent.parent.kind === SyntaxKind.ClassDeclaration; + } + // Returns false if this heritage clause element's expression contains something unsupported // (i.e. not a name or dotted name). export function isSupportedExpressionWithTypeArguments(node: ExpressionWithTypeArguments): boolean { @@ -1865,9 +2027,24 @@ module ts { return result; } + + const carriageReturnLineFeed = "\r\n"; + const lineFeed = "\n"; + export function getNewLineCharacter(options: CompilerOptions): string { + if (options.newLine === NewLineKind.CarriageReturnLineFeed) { + return carriageReturnLineFeed; + } + else if (options.newLine === NewLineKind.LineFeed) { + return lineFeed; + } + else if (sys) { + return sys.newLine + } + return carriageReturnLineFeed; + } } -module ts { +namespace ts { export function getDefaultLibFileName(options: CompilerOptions): string { return options.target === ScriptTarget.ES6 ? "lib.es6.d.ts" : "lib.d.ts"; } @@ -1913,6 +2090,12 @@ module ts { return start <= textSpanEnd(span) && end >= span.start; } + export function decodedTextSpanIntersectsWith(start1: number, length1: number, start2: number, length2: number) { + let end1 = start1 + length1; + let end2 = start2 + length2; + return start2 <= end1 && end2 >= start1; + } + export function textSpanIntersectsWithPosition(span: TextSpan, position: number) { return position <= textSpanEnd(span) && position >= span.start; } diff --git a/src/harness/compilerRunner.ts b/src/harness/compilerRunner.ts index b6997e705b9..21e88b9e41a 100644 --- a/src/harness/compilerRunner.ts +++ b/src/harness/compilerRunner.ts @@ -1,7 +1,6 @@ /// /// /// -/// const enum CompilerTestType { Conformance, @@ -18,7 +17,7 @@ class CompilerBaselineRunner extends RunnerBase { public options: string; - constructor(public testType?: CompilerTestType) { + constructor(public testType: CompilerTestType) { super(); this.errors = true; this.emit = true; @@ -171,7 +170,6 @@ class CompilerBaselineRunner extends RunnerBase { } }); - it('Correct JS output for ' + fileName, () => { if (!ts.fileExtensionIs(lastUnit.name, '.d.ts') && this.emit) { if (result.files.length === 0 && result.errors.length === 0) { @@ -195,8 +193,6 @@ class CompilerBaselineRunner extends RunnerBase { jsCode += '//// [' + Harness.Path.getFileName(result.files[i].fileName) + ']\r\n'; jsCode += getByteOrderMarkText(result.files[i]); jsCode += result.files[i].code; - // Re-enable this if we want to do another comparison of old vs new compiler baselines - // jsCode += SyntacticCleaner.clean(result.files[i].code); } if (result.declFilesCode.length > 0) { diff --git a/src/harness/exec.ts b/src/harness/exec.ts deleted file mode 100644 index 6ed538b1d40..00000000000 --- a/src/harness/exec.ts +++ /dev/null @@ -1,74 +0,0 @@ -// -// 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 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -// Allows for executing a program with command-line arguments and reading the result -interface IExec { - exec: (fileName: string, cmdLineArgs: string[], handleResult: (ExecResult: ExecResult) => void) => void; -} - -class ExecResult { - public stdout = ""; - public stderr = ""; - public exitCode: number; -} - -class WindowsScriptHostExec implements IExec { - public exec(fileName: string, cmdLineArgs: string[], handleResult: (ExecResult: ExecResult) => void) : void { - var result = new ExecResult(); - var shell = new ActiveXObject('WScript.Shell'); - try { - var process = shell.Exec(fileName + ' ' + cmdLineArgs.join(' ')); - } catch(e) { - result.stderr = e.message; - result.exitCode = 1; - handleResult(result); - return; - } - // Wait for it to finish running - while (process.Status != 0) { /* todo: sleep? */ } - - - result.exitCode = process.ExitCode; - if(!process.StdOut.AtEndOfStream) result.stdout = process.StdOut.ReadAll(); - if(!process.StdErr.AtEndOfStream) result.stderr = process.StdErr.ReadAll(); - - handleResult(result); - } -} - -class NodeExec implements IExec { - public exec(fileName: string, cmdLineArgs: string[], handleResult: (ExecResult: ExecResult) => void) : void { - var nodeExec = require('child_process').exec; - - var result = new ExecResult(); - result.exitCode = null; - var cmdLine = fileName + ' ' + cmdLineArgs.join(' '); - var process = nodeExec(cmdLine, function(error: any, stdout: string, stderr: string) { - result.stdout = stdout; - result.stderr = stderr; - result.exitCode = error ? error.code : 0; - handleResult(result); - }); - } -} - -var Exec: IExec = function() : IExec { - var global = Function("return this;").call(null); - if(typeof global.ActiveXObject !== "undefined") { - return new WindowsScriptHostExec(); - } else { - return new NodeExec(); - } -}(); \ No newline at end of file diff --git a/src/harness/fourslash.ts b/src/harness/fourslash.ts index 110e59c46e1..5915698462c 100644 --- a/src/harness/fourslash.ts +++ b/src/harness/fourslash.ts @@ -343,7 +343,8 @@ module FourSlash { if (!resolvedResult.isLibFile) { this.languageServiceAdapterHost.addScript(Harness.Compiler.defaultLibFileName, Harness.Compiler.defaultLibSourceFile.text); } - } else { + } + else { // resolveReference file-option is not specified then do not resolve any files and include all inputFiles ts.forEachKey(this.inputFiles, fileName => { if (!Harness.isLibraryFile(fileName)) { @@ -830,6 +831,7 @@ module FourSlash { if (expectedText !== undefined) { assert.notEqual(actualQuickInfoText, expectedText, this.messageAtLastKnownMarker("quick info text")); } + // TODO: should be '==='? if (expectedDocumentation != undefined) { assert.notEqual(actualQuickInfoDocumentation, expectedDocumentation, this.messageAtLastKnownMarker("quick info doc comment")); } @@ -837,6 +839,7 @@ module FourSlash { if (expectedText !== undefined) { assert.equal(actualQuickInfoText, expectedText, this.messageAtLastKnownMarker("quick info text")); } + // TODO: should be '==='? if (expectedDocumentation != undefined) { assert.equal(actualQuickInfoDocumentation, expectedDocumentation, assertionMessage("quick info doc")); } @@ -1818,6 +1821,21 @@ module FourSlash { } } + private verifyProjectInfo(expected: string[]) { + if (this.testType === FourSlashTestType.Server) { + let actual = (this.languageService).getProjectInfo( + this.activeFile.fileName, + /* needFileNameList */ true + ); + assert.equal( + expected.join(","), + actual.fileNameList.map( file => { + return file.replace(this.basePath + "/", "") + }).join(",") + ); + } + } + public verifySemanticClassifications(expected: { classificationType: string; text: string }[]) { var actual = this.languageService.getSemanticClassifications(this.activeFile.fileName, ts.createTextSpan(0, this.activeFile.content.length)); @@ -1921,7 +1939,7 @@ module FourSlash { } } - if (expected != actual) { + if (expected !== actual) { this.raiseError('verifyNavigationItemsCount failed - found: ' + actual + ' navigation items, expected: ' + expected + '.'); } } @@ -1968,7 +1986,7 @@ module FourSlash { var items = this.languageService.getNavigationBarItems(this.activeFile.fileName); var actual = this.getNavigationBarItemsCount(items); - if (expected != actual) { + if (expected !== actual) { this.raiseError('verifyGetScriptLexicalStructureListCount failed - found: ' + actual + ' navigation items, expected: ' + expected + '.'); } } @@ -2386,6 +2404,7 @@ module FourSlash { globalOptions[match[1]] = match[2]; } } + // TODO: should be '==='? } else if (line == '' || lineLength === 0) { // Previously blank lines between fourslash content caused it to be considered as 2 files, // Remove this behavior since it just causes errors now diff --git a/src/harness/harness.ts b/src/harness/harness.ts index 90afab029eb..6a559488150 100644 --- a/src/harness/harness.ts +++ b/src/harness/harness.ts @@ -99,7 +99,7 @@ module Utils { } try { - var content = ts.sys.readFile(Harness.userSpecifiedroot + path); + var content = ts.sys.readFile(Harness.userSpecifiedRoot + path); } catch (err) { return undefined; @@ -732,7 +732,8 @@ module Harness { } // Settings - export var userSpecifiedroot = ""; + export let userSpecifiedRoot = ""; + export let lightMode = false; /** Functionality for compiling TypeScript code */ export module Compiler { @@ -808,12 +809,20 @@ module Harness { } } - export function createSourceFileAndAssertInvariants(fileName: string, sourceText: string, languageVersion: ts.ScriptTarget, assertInvariants = true) { + export function createSourceFileAndAssertInvariants( + fileName: string, + sourceText: string, + languageVersion: ts.ScriptTarget) { + // We'll only assert invariants outside of light mode. + const shouldAssertInvariants = !Harness.lightMode; + // Only set the parent nodes if we're asserting invariants. We don't need them otherwise. - var result = ts.createSourceFile(fileName, sourceText, languageVersion, /*setParentNodes:*/ assertInvariants); - if (assertInvariants) { + var result = ts.createSourceFile(fileName, sourceText, languageVersion, /*setParentNodes:*/ shouldAssertInvariants); + + if (shouldAssertInvariants) { Utils.assertInvariants(result, /*parent:*/ undefined); } + return result; } @@ -832,13 +841,14 @@ module Harness { return ts.sys.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase(); } - export function createCompilerHost(inputFiles: { unitName: string; content: string; }[], - writeFile: (fn: string, contents: string, writeByteOrderMark: boolean) => void, - scriptTarget: ts.ScriptTarget, - useCaseSensitiveFileNames: boolean, - // the currentDirectory is needed for rwcRunner to passed in specified current directory to compiler host - currentDirectory?: string, - newLineKind?: ts.NewLineKind): ts.CompilerHost { + export function createCompilerHost( + inputFiles: { unitName: string; content: string; }[], + writeFile: (fn: string, contents: string, writeByteOrderMark: boolean) => void, + scriptTarget: ts.ScriptTarget, + useCaseSensitiveFileNames: boolean, + // the currentDirectory is needed for rwcRunner to passed in specified current directory to compiler host + currentDirectory?: string, + newLineKind?: ts.NewLineKind): ts.CompilerHost { // Local get canonical file name function, that depends on passed in parameter for useCaseSensitiveFileNames function getCanonicalFileName(fileName: string): string { @@ -899,7 +909,7 @@ module Harness { private compileOptions: ts.CompilerOptions; private settings: Harness.TestCaseParser.CompilerSetting[] = []; - private lastErrors: HarnessDiagnostic[]; + private lastErrors: ts.Diagnostic[]; public reset() { this.inputFiles = []; @@ -932,17 +942,19 @@ module Harness { } public emitAll(ioHost?: IEmitterIOHost) { - this.compileFiles(this.inputFiles, [],(result) => { - result.files.forEach(file => { - ioHost.writeFile(file.fileName, file.code, false); - }); - result.declFilesCode.forEach(file => { - ioHost.writeFile(file.fileName, file.code, false); - }); - result.sourceMaps.forEach(file => { - ioHost.writeFile(file.fileName, file.code, false); - }); - },() => { }, this.compileOptions); + this.compileFiles(this.inputFiles, + /*otherFiles*/ [], + /*onComplete*/ result => { + result.files.forEach(writeFile); + result.declFilesCode.forEach(writeFile); + result.sourceMaps.forEach(writeFile); + }, + /*settingsCallback*/ () => { }, + this.compileOptions); + + function writeFile(file: GeneratedFile) { + ioHost.writeFile(file.fileName, file.code, false); + } } public compileFiles(inputFiles: { unitName: string; content: string }[], @@ -951,8 +963,7 @@ module Harness { settingsCallback?: (settings: ts.CompilerOptions) => void, options?: ts.CompilerOptions, // Current directory is needed for rwcRunner to be able to use currentDirectory defined in json file - currentDirectory?: string, - assertInvariants = true) { + currentDirectory?: string) { options = options || { noResolve: false }; options.target = options.target || ts.ScriptTarget.ES3; @@ -964,14 +975,39 @@ module Harness { settingsCallback(null); } - var newLine = '\r\n'; + let newLine = '\r\n'; + options.skipDefaultLibCheck = true; // Files from built\local that are requested by test "@includeBuiltFiles" to be in the context. // Treat them as library files, so include them in build, but not in baselines. var includeBuiltFiles: { unitName: string; content: string }[] = []; var useCaseSensitiveFileNames = ts.sys.useCaseSensitiveFileNames; - this.settings.forEach(setting => { + this.settings.forEach(setCompilerOptionForSetting); + + var fileOutputs: GeneratedFile[] = []; + + var programFiles = inputFiles.concat(includeBuiltFiles).map(file => file.unitName); + + var compilerHost = createCompilerHost( + inputFiles.concat(includeBuiltFiles).concat(otherFiles), + (fn, contents, writeByteOrderMark) => fileOutputs.push({ fileName: fn, code: contents, writeByteOrderMark: writeByteOrderMark }), + options.target, useCaseSensitiveFileNames, currentDirectory, options.newLine); + var program = ts.createProgram(programFiles, options, compilerHost); + + var emitResult = program.emit(); + + var errors = ts.getPreEmitDiagnostics(program).concat(emitResult.diagnostics); + this.lastErrors = errors; + + var result = new CompilerResult(fileOutputs, errors, program, ts.sys.getCurrentDirectory(), emitResult.sourceMaps); + onComplete(result, program); + + // reset what newline means in case the last test changed it + ts.sys.newLine = newLine; + return options; + + function setCompilerOptionForSetting(setting: Harness.TestCaseParser.CompilerSetting) { switch (setting.flag.toLowerCase()) { // "fileName", "comments", "declaration", "module", "nolib", "sourcemap", "target", "out", "outdir", "noimplicitany", "noresolve" case "module": @@ -1011,6 +1047,10 @@ module Harness { options.target = setting.value; } break; + + case 'experimentaldecorators': + options.experimentalDecorators = setting.value === 'true'; + break; case 'emitdecoratormetadata': options.emitDecoratorMetadata = setting.value === 'true'; @@ -1046,6 +1086,10 @@ module Harness { options.outDir = setting.value; break; + case 'skipdefaultlibcheck': + options.skipDefaultLibCheck = setting.value === "true"; + break; + case 'sourceroot': options.sourceRoot = setting.value; break; @@ -1074,10 +1118,6 @@ module Harness { } break; - case 'normalizenewline': - newLine = setting.value; - break; - case 'comments': options.removeComments = setting.value === 'false'; break; @@ -1105,8 +1145,8 @@ module Harness { options.preserveConstEnums = setting.value === 'true'; break; - case 'separatecompilation': - options.separateCompilation = setting.value === 'true'; + case 'isolatedmodules': + options.isolatedModules = setting.value === 'true'; break; case 'suppressimplicitanyindexerrors': @@ -1121,7 +1161,7 @@ module Harness { case 'inlinesourcemap': options.inlineSourceMap = setting.value === 'true'; break; - + case 'inlinesources': options.inlineSources = setting.value === 'true'; break; @@ -1129,30 +1169,7 @@ module Harness { default: throw new Error('Unsupported compiler setting ' + setting.flag); } - }); - - var fileOutputs: GeneratedFile[] = []; - - var programFiles = inputFiles.concat(includeBuiltFiles).map(file => file.unitName); - var program = ts.createProgram(programFiles, options, createCompilerHost(inputFiles.concat(includeBuiltFiles).concat(otherFiles), - (fn, contents, writeByteOrderMark) => fileOutputs.push({ fileName: fn, code: contents, writeByteOrderMark: writeByteOrderMark }), - options.target, useCaseSensitiveFileNames, currentDirectory, options.newLine)); - - var emitResult = program.emit(); - - var errors: HarnessDiagnostic[] = []; - ts.getPreEmitDiagnostics(program).concat(emitResult.diagnostics).forEach(err => { - // TODO: new compiler formats errors after this point to add . and newlines so we'll just do it manually for now - errors.push(getMinimalDiagnostic(err)); - }); - this.lastErrors = errors; - - var result = new CompilerResult(fileOutputs, errors, program, ts.sys.getCurrentDirectory(), emitResult.sourceMaps); - onComplete(result, program); - - // reset what newline means in case the last test changed it - ts.sys.newLine = newLine; - return options; + } } public compileDeclarationFiles(inputFiles: { unitName: string; content: string; }[], @@ -1231,70 +1248,50 @@ module Harness { return normalized; } - export function getMinimalDiagnostic(err: ts.Diagnostic): HarnessDiagnostic { - var errorLineInfo = err.file ? err.file.getLineAndCharacterOfPosition(err.start) : { line: -1, character: -1 }; - return { - fileName: err.file && err.file.fileName, - start: err.start, - end: err.start + err.length, - line: errorLineInfo.line + 1, - character: errorLineInfo.character + 1, - message: ts.flattenDiagnosticMessageText(err.messageText, ts.sys.newLine), - category: ts.DiagnosticCategory[err.category].toLowerCase(), - code: err.code - }; - } - - export function minimalDiagnosticsToString(diagnostics: HarnessDiagnostic[]) { + export function minimalDiagnosticsToString(diagnostics: ts.Diagnostic[]) { // This is basically copied from tsc.ts's reportError to replicate what tsc does var errorOutput = ""; - ts.forEach(diagnostics, diagnotic => { - if (diagnotic.fileName) { - errorOutput += diagnotic.fileName + "(" + diagnotic.line + "," + diagnotic.character + "): "; + ts.forEach(diagnostics, diagnostic => { + if (diagnostic.file) { + var lineAndCharacter = diagnostic.file.getLineAndCharacterOfPosition(diagnostic.start); + errorOutput += diagnostic.file.fileName + "(" + (lineAndCharacter.line + 1) + "," + (lineAndCharacter.character + 1) + "): "; } - errorOutput += diagnotic.category + " TS" + diagnotic.code + ": " + diagnotic.message + ts.sys.newLine; + errorOutput += ts.DiagnosticCategory[diagnostic.category].toLowerCase() + " TS" + diagnostic.code + ": " + ts.flattenDiagnosticMessageText(diagnostic.messageText, ts.sys.newLine) + ts.sys.newLine; }); return errorOutput; } - function compareDiagnostics(d1: HarnessDiagnostic, d2: HarnessDiagnostic) { - return ts.compareValues(d1.fileName, d2.fileName) || - ts.compareValues(d1.start, d2.start) || - ts.compareValues(d1.end, d2.end) || - ts.compareValues(d1.code, d2.code) || - ts.compareValues(d1.message, d2.message) || - 0; - } - - export function getErrorBaseline(inputFiles: { unitName: string; content: string }[], diagnostics: HarnessDiagnostic[]) { - diagnostics.sort(compareDiagnostics); + export function getErrorBaseline(inputFiles: { unitName: string; content: string }[], diagnostics: ts.Diagnostic[]) { + diagnostics.sort(ts.compareDiagnostics); var outputLines: string[] = []; // Count up all the errors we find so we don't miss any var totalErrorsReported = 0; - function outputErrorText(error: Harness.Compiler.HarnessDiagnostic) { - var errLines = RunnerBase.removeFullPaths(error.message) + function outputErrorText(error: ts.Diagnostic) { + var message = ts.flattenDiagnosticMessageText(error.messageText, ts.sys.newLine); + + var errLines = RunnerBase.removeFullPaths(message) .split('\n') .map(s => s.length > 0 && s.charAt(s.length - 1) === '\r' ? s.substr(0, s.length - 1) : s) .filter(s => s.length > 0) - .map(s => '!!! ' + error.category + " TS" + error.code + ": " + s); + .map(s => '!!! ' + ts.DiagnosticCategory[error.category].toLowerCase() + " TS" + error.code + ": " + s); errLines.forEach(e => outputLines.push(e)); totalErrorsReported++; } // Report global errors - var globalErrors = diagnostics.filter(err => !err.fileName); + var globalErrors = diagnostics.filter(err => !err.file); globalErrors.forEach(outputErrorText); // 'merge' the lines of each input file with any errors associated with it inputFiles.filter(f => f.content !== undefined).forEach(inputFile => { // Filter down to the errors in the file var fileErrors = diagnostics.filter(e => { - var errFn = e.fileName; - return errFn && errFn === inputFile.unitName; + var errFn = e.file; + return errFn && errFn.fileName === inputFile.unitName; }); @@ -1330,18 +1327,19 @@ module Harness { outputLines.push(' ' + line); fileErrors.forEach(err => { // Does any error start or continue on to this line? Emit squiggles - if ((err.end >= thisLineStart) && ((err.start < nextLineStart) || (lineIndex === lines.length - 1))) { + let end = ts.textSpanEnd(err); + if ((end >= thisLineStart) && ((err.start < nextLineStart) || (lineIndex === lines.length - 1))) { // How many characters from the start of this line the error starts at (could be positive or negative) var relativeOffset = err.start - thisLineStart; // How many characters of the error are on this line (might be longer than this line in reality) - var length = (err.end - err.start) - Math.max(0, thisLineStart - err.start); + var length = (end - err.start) - Math.max(0, thisLineStart - err.start); // Calculate the start of the squiggle var squiggleStart = Math.max(0, relativeOffset); // TODO/REVIEW: this doesn't work quite right in the browser if a multi file test has files whose names are just the right length relative to one another outputLines.push(' ' + line.substr(0, squiggleStart).replace(/[^\s]/g, ' ') + new Array(Math.min(length, line.length - squiggleStart) + 1).join('~')); // If the error ended here, or we're at the end of the file, emit its message - if ((lineIndex === lines.length - 1) || nextLineStart > err.end) { + if ((lineIndex === lines.length - 1) || nextLineStart > end) { // Just like above, we need to do a split on a string instead of on a regex // because the JS engine does regexes wrong @@ -1357,12 +1355,12 @@ module Harness { }); var numLibraryDiagnostics = ts.countWhere(diagnostics, diagnostic => { - return diagnostic.fileName && (isLibraryFile(diagnostic.fileName) || isBuiltFile(diagnostic.fileName)); + return diagnostic.file && (isLibraryFile(diagnostic.file.fileName) || isBuiltFile(diagnostic.file.fileName)); }); var numTest262HarnessDiagnostics = ts.countWhere(diagnostics, diagnostic => { // Count an error generated from tests262-harness folder.This should only apply for test262 - return diagnostic.fileName && diagnostic.fileName.indexOf("test262-harness") >= 0; + return diagnostic.file && diagnostic.file.fileName.indexOf("test262-harness") >= 0; }); // Verify we didn't miss any errors in total @@ -1372,29 +1370,30 @@ module Harness { ts.sys.newLine + ts.sys.newLine + outputLines.join('\r\n'); } - export function collateOutputs(outputFiles: Harness.Compiler.GeneratedFile[], clean?: (s: string) => string) { + export function collateOutputs(outputFiles: Harness.Compiler.GeneratedFile[]): string { // Collect, test, and sort the fileNames - function cleanName(fn: string) { - var lastSlash = ts.normalizeSlashes(fn).lastIndexOf('/'); - return fn.substr(lastSlash + 1).toLowerCase(); - } outputFiles.sort((a, b) => cleanName(a.fileName).localeCompare(cleanName(b.fileName))); // Emit them var result = ''; - ts.forEach(outputFiles, outputFile => { + for (let outputFile of outputFiles) { // Some extra spacing if this isn't the first file - if (result.length) result = result + '\r\n\r\n'; + if (result.length) { + result += '\r\n\r\n'; + } // FileName header + content - result = result + '/*====== ' + outputFile.fileName + ' ======*/\r\n'; - if (clean) { - result = result + clean(outputFile.code); - } else { - result = result + outputFile.code; - } - }); + result += '/*====== ' + outputFile.fileName + ' ======*/\r\n'; + + result += outputFile.code; + } + return result; + + function cleanName(fn: string) { + var lastSlash = ts.normalizeSlashes(fn).lastIndexOf('/'); + return fn.substr(lastSlash + 1).toLowerCase(); + } } /** The harness' compiler instance used when tests are actually run. Reseting or changing settings of this compiler instance must be done within a test case (i.e., describe/it) */ @@ -1415,17 +1414,6 @@ module Harness { //harnessCompiler.compileString(code, unitName, callback); } - export interface HarnessDiagnostic { - fileName: string; - start: number; - end: number; - line: number; - character: number; - message: string; - category: string; - code: number; - } - export interface GeneratedFile { fileName: string; code: string; @@ -1455,12 +1443,12 @@ module Harness { /** Contains the code and errors of a compilation and some helper methods to check its status. */ export class CompilerResult { public files: GeneratedFile[] = []; - public errors: HarnessDiagnostic[] = []; + public errors: ts.Diagnostic[] = []; public declFilesCode: GeneratedFile[] = []; public sourceMaps: GeneratedFile[] = []; /** @param fileResults an array of strings for the fileName and an ITextWriter with its code */ - constructor(fileResults: GeneratedFile[], errors: HarnessDiagnostic[], public program: ts.Program, + constructor(fileResults: GeneratedFile[], errors: ts.Diagnostic[], public program: ts.Program, public currentDirectoryForProgram: string, private sourceMapData: ts.SourceMapData[]) { fileResults.forEach(emittedFile => { @@ -1485,15 +1473,6 @@ module Harness { return Harness.SourceMapRecoder.getSourceMapRecord(this.sourceMapData, this.program, this.files); } } - - public isErrorAt(line: number, column: number, message: string) { - for (var i = 0; i < this.errors.length; i++) { - if ((this.errors[i].line + 1) === line && (this.errors[i].character + 1) === column && this.errors[i].message === message) - return true; - } - - return false; - } } } @@ -1516,15 +1495,6 @@ module Harness { // Regex for parsing options in the format "@Alpha: Value of any sort" var optionRegex = /^[\/]{2}\s*@(\w+)\s*:\s*(\S*)/gm; // multiple matches on multiple lines - // List of allowed metadata names - var fileMetadataNames = ["filename", "comments", "declaration", "module", - "nolib", "sourcemap", "target", "out", "outdir", "noemithelpers", "noemitonerror", - "noimplicitany", "noresolve", "newline", "normalizenewline", "emitbom", - "errortruncation", "usecasesensitivefilenames", "preserveconstenums", - "includebuiltfile", "suppressimplicitanyindexerrors", "stripinternal", - "separatecompilation", "inlinesourcemap", "maproot", "sourceroot", - "inlinesources", "emitdecoratormetadata"]; - function extractCompilerSettings(content: string): CompilerSetting[] { var opts: CompilerSetting[] = []; @@ -1558,10 +1528,8 @@ module Harness { if (testMetaData) { // Comment line, check for global/file @options and record them optionRegex.lastIndex = 0; - var fileNameIndex = fileMetadataNames.indexOf(testMetaData[1].toLowerCase()); - if (fileNameIndex === -1) { - throw new Error('Unrecognized metadata name "' + testMetaData[1] + '". Available file metadata names are: ' + fileMetadataNames.join(', ')); - } else if (fileNameIndex === 0) { + var metaDataName = testMetaData[1].toLowerCase(); + if (metaDataName === "filename") { currentFileOptions[testMetaData[1]] = testMetaData[2]; } else { continue; @@ -1647,9 +1615,9 @@ module Harness { function baselinePath(fileName: string, type: string, baselineFolder: string, subfolder?: string) { if (subfolder !== undefined) { - return Harness.userSpecifiedroot + baselineFolder + '/' + subfolder + '/' + type + '/' + fileName; + return Harness.userSpecifiedRoot + baselineFolder + '/' + subfolder + '/' + type + '/' + fileName; } else { - return Harness.userSpecifiedroot + baselineFolder + '/' + type + '/' + fileName; + return Harness.userSpecifiedRoot + baselineFolder + '/' + type + '/' + fileName; } } @@ -1758,7 +1726,7 @@ module Harness { } export function getDefaultLibraryFile(): { unitName: string, content: string } { - var libFile = Harness.userSpecifiedroot + Harness.libFolder + "/" + "lib.d.ts"; + var libFile = Harness.userSpecifiedRoot + Harness.libFolder + "/" + "lib.d.ts"; return { unitName: libFile, content: IO.readFile(libFile) diff --git a/src/harness/harnessLanguageService.ts b/src/harness/harnessLanguageService.ts index 0e0b8d82918..8eb77817533 100644 --- a/src/harness/harnessLanguageService.ts +++ b/src/harness/harnessLanguageService.ts @@ -583,7 +583,7 @@ module Harness.LanguageService { // This host is just a proxy for the clientHost, it uses the client // host to answer server queries about files on disk var serverHost = new SessionServerHost(clientHost); - var server = new ts.server.Session(serverHost, serverHost); + var server = new ts.server.Session(serverHost, Buffer.byteLength, process.hrtime, serverHost); // Fake the connection between the client and the server serverHost.writeMessage = client.onMessage.bind(client); diff --git a/src/harness/project.ts b/src/harness/project.ts deleted file mode 100644 index d94cbd576d5..00000000000 --- a/src/harness/project.ts +++ /dev/null @@ -1,19 +0,0 @@ -// -// 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 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -/// -/// -/// -/// diff --git a/src/harness/projectsRunner.ts b/src/harness/projectsRunner.ts index 39221d55b29..5eb0016ff8d 100644 --- a/src/harness/projectsRunner.ts +++ b/src/harness/projectsRunner.ts @@ -110,6 +110,7 @@ class ProjectRunner extends RunnerBase { else if (url.indexOf(diskProjectPath) === 0) { // Replace the disk specific path into the project root path url = url.substr(diskProjectPath.length); + // TODO: should be '!=='? if (url.charCodeAt(0) != ts.CharacterCodes.slash) { url = "/" + url; } @@ -240,7 +241,7 @@ class ProjectRunner extends RunnerBase { if (Harness.Compiler.isJS(fileName)) { // Make sure if there is URl we have it cleaned up var indexOfSourceMapUrl = data.lastIndexOf("//# sourceMappingURL="); - if (indexOfSourceMapUrl != -1) { + if (indexOfSourceMapUrl !== -1) { data = data.substring(0, indexOfSourceMapUrl + 21) + cleanProjectUrl(data.substring(indexOfSourceMapUrl + 21)); } } @@ -323,9 +324,8 @@ class ProjectRunner extends RunnerBase { sourceFile => { return { unitName: sourceFile.fileName, content: sourceFile.text }; }); - var diagnostics = ts.map(compilerResult.errors, error => Harness.Compiler.getMinimalDiagnostic(error)); - return Harness.Compiler.getErrorBaseline(inputFiles, diagnostics); + return Harness.Compiler.getErrorBaseline(inputFiles, compilerResult.errors); } var name = 'Compiling project for ' + testCase.scenario + ': testcase ' + testCaseFileName; diff --git a/src/harness/runner.ts b/src/harness/runner.ts index 37451639d75..1e9c6470421 100644 --- a/src/harness/runner.ts +++ b/src/harness/runner.ts @@ -18,6 +18,7 @@ /// /// /// +/// function runTests(runners: RunnerBase[]) { for (var i = iterations; i > 0; i--) { @@ -38,41 +39,47 @@ var testConfigFile = (Harness.IO.fileExists(testconfig) ? Harness.IO.readFile(testconfig) : ''); if (testConfigFile !== '') { - // TODO: not sure why this is crashing mocha - //var testConfig = JSON.parse(testConfigRaw); - var testConfig = testConfigFile.match(/test:\s\['(.*)'\]/); - var options = testConfig ? [testConfig[1]] : []; - for (var i = 0; i < options.length; i++) { - switch (options[i]) { - case 'compiler': - runners.push(new CompilerBaselineRunner(CompilerTestType.Conformance)); - runners.push(new CompilerBaselineRunner(CompilerTestType.Regressions)); - runners.push(new ProjectRunner()); - break; - case 'conformance': - runners.push(new CompilerBaselineRunner(CompilerTestType.Conformance)); - break; - case 'project': - runners.push(new ProjectRunner()); - break; - case 'fourslash': - runners.push(new FourSlashRunner(FourSlashTestType.Native)); - break; - case 'fourslash-shims': - runners.push(new FourSlashRunner(FourSlashTestType.Shims)); - break; - case 'fourslash-server': - runners.push(new FourSlashRunner(FourSlashTestType.Server)); - break; - case 'fourslash-generated': - runners.push(new GeneratedFourslashRunner(FourSlashTestType.Native)); - break; - case 'rwc': - runners.push(new RWCRunner()); - break; - case 'test262': - runners.push(new Test262BaselineRunner()); - break; + var testConfig = JSON.parse(testConfigFile); + if (testConfig.light) { + Harness.lightMode = true; + } + + if (testConfig.test && testConfig.test.length > 0) { + for (let option of testConfig.test) { + if (!option) { + continue; + } + switch (option) { + case 'compiler': + runners.push(new CompilerBaselineRunner(CompilerTestType.Conformance)); + runners.push(new CompilerBaselineRunner(CompilerTestType.Regressions)); + runners.push(new ProjectRunner()); + break; + case 'conformance': + runners.push(new CompilerBaselineRunner(CompilerTestType.Conformance)); + break; + case 'project': + runners.push(new ProjectRunner()); + break; + case 'fourslash': + runners.push(new FourSlashRunner(FourSlashTestType.Native)); + break; + case 'fourslash-shims': + runners.push(new FourSlashRunner(FourSlashTestType.Shims)); + break; + case 'fourslash-server': + runners.push(new FourSlashRunner(FourSlashTestType.Server)); + break; + case 'fourslash-generated': + runners.push(new GeneratedFourslashRunner(FourSlashTestType.Native)); + break; + case 'rwc': + runners.push(new RWCRunner()); + break; + case 'test262': + runners.push(new Test262BaselineRunner()); + break; + } } } } diff --git a/src/harness/runnerbase.ts b/src/harness/runnerbase.ts index 49ca796448a..269e889704c 100644 --- a/src/harness/runnerbase.ts +++ b/src/harness/runnerbase.ts @@ -12,7 +12,7 @@ class RunnerBase { } public enumerateFiles(folder: string, regex?: RegExp, options?: { recursive: boolean }): string[] { - return Harness.IO.listFiles(Harness.userSpecifiedroot + folder, regex, { recursive: (options ? options.recursive : false) }); + return Harness.IO.listFiles(Harness.userSpecifiedRoot + folder, regex, { recursive: (options ? options.recursive : false) }); } /** Setup the runner's tests so that they are ready to be executed by the harness diff --git a/src/harness/rwcRunner.ts b/src/harness/rwcRunner.ts index 49a15112e9f..43a118b6aec 100644 --- a/src/harness/rwcRunner.ts +++ b/src/harness/rwcRunner.ts @@ -1,6 +1,5 @@ /// /// -/// /// /// @@ -75,7 +74,7 @@ module RWC { }); // Add files to compilation - for(let fileRead of ioLog.filesRead) { + for (let fileRead of ioLog.filesRead) { // Check if the file is already added into the set of input files. var resolvedPath = ts.normalizeSlashes(ts.sys.resolvePath(fileRead.path)); var inInputList = ts.forEach(inputFiles, inputFile => inputFile.unitName === resolvedPath); @@ -107,14 +106,14 @@ module RWC { opts.options.noLib = true; // Emit the results - compilerOptions = harnessCompiler.compileFiles(inputFiles, otherFiles, compileResult => { - compilerResult = compileResult; - }, + compilerOptions = harnessCompiler.compileFiles( + inputFiles, + otherFiles, + newCompilerResults => { compilerResult = newCompilerResults; }, /*settingsCallback*/ undefined, opts.options, - // Since all Rwc json file specified current directory in its json file, we need to pass this information to compilerHost - // so that when the host is asked for current directory, it should give the value from json rather than from process - currentDirectory, - /*assertInvariants:*/ false); + // Since each RWC json file specifies its current directory in its json file, we need + // to pass this information in explicitly instead of acquiring it from the process. + currentDirectory); }); function getHarnessCompilerInputUnit(fileName: string) { @@ -132,7 +131,7 @@ module RWC { it('has the expected emitted code', () => { Harness.Baseline.runBaseline('has the expected emitted code', baseName + '.output.js', () => { - return Harness.Compiler.collateOutputs(compilerResult.files, s => SyntacticCleaner.clean(s)); + return Harness.Compiler.collateOutputs(compilerResult.files); }, false, baselineOpts); }); diff --git a/src/harness/sourceMapRecorder.ts b/src/harness/sourceMapRecorder.ts index 528e6ddd52b..ed079774d94 100644 --- a/src/harness/sourceMapRecorder.ts +++ b/src/harness/sourceMapRecorder.ts @@ -46,7 +46,7 @@ module Harness.SourceMapRecoder { } function isSourceMappingSegmentEnd() { - if (decodingIndex == sourceMapMappings.length) { + if (decodingIndex === sourceMapMappings.length) { return true; } @@ -95,7 +95,7 @@ module Harness.SourceMapRecoder { var currentByte = base64FormatDecode(); // If msb is set, we still have more bits to continue - moreDigits = (currentByte & 32) != 0; + moreDigits = (currentByte & 32) !== 0; // least significant 5 bits are the next msbs in the final value. value = value | ((currentByte & 31) << shiftCount); @@ -103,7 +103,7 @@ module Harness.SourceMapRecoder { } // Least significant bit if 1 represents negative and rest of the msb is actual absolute value - if ((value & 1) == 0) { + if ((value & 1) === 0) { // + number value = value >> 1; } @@ -182,7 +182,7 @@ module Harness.SourceMapRecoder { } } // Dont support reading mappings that dont have information about original source and its line numbers - if (createErrorIfCondition(!isSourceMappingSegmentEnd(), "Unsupported Error Format: There are more entries after " + (decodeOfEncodedMapping.nameIndex == -1 ? "sourceColumn" : "nameIndex"))) { + if (createErrorIfCondition(!isSourceMappingSegmentEnd(), "Unsupported Error Format: There are more entries after " + (decodeOfEncodedMapping.nameIndex === -1 ? "sourceColumn" : "nameIndex"))) { return { error: errorDecodeOfEncodedMapping, sourceMapSpan: decodeOfEncodedMapping }; } @@ -249,7 +249,7 @@ module Harness.SourceMapRecoder { mapString += " name (" + sourceMapNames[mapEntry.nameIndex] + ")"; } else { - if (mapEntry.nameIndex != -1 || getAbsentNameIndex) { + if (mapEntry.nameIndex !== -1 || getAbsentNameIndex) { mapString += " nameIndex (" + mapEntry.nameIndex + ")"; } } @@ -262,12 +262,12 @@ module Harness.SourceMapRecoder { var decodeResult = SourceMapDecoder.decodeNextEncodedSourceMapSpan(); var decodedErrors: string[]; if (decodeResult.error - || decodeResult.sourceMapSpan.emittedLine != sourceMapSpan.emittedLine - || decodeResult.sourceMapSpan.emittedColumn != sourceMapSpan.emittedColumn - || decodeResult.sourceMapSpan.sourceLine != sourceMapSpan.sourceLine - || decodeResult.sourceMapSpan.sourceColumn != sourceMapSpan.sourceColumn - || decodeResult.sourceMapSpan.sourceIndex != sourceMapSpan.sourceIndex - || decodeResult.sourceMapSpan.nameIndex != sourceMapSpan.nameIndex) { + || decodeResult.sourceMapSpan.emittedLine !== sourceMapSpan.emittedLine + || decodeResult.sourceMapSpan.emittedColumn !== sourceMapSpan.emittedColumn + || decodeResult.sourceMapSpan.sourceLine !== sourceMapSpan.sourceLine + || decodeResult.sourceMapSpan.sourceColumn !== sourceMapSpan.sourceColumn + || decodeResult.sourceMapSpan.sourceIndex !== sourceMapSpan.sourceIndex + || decodeResult.sourceMapSpan.nameIndex !== sourceMapSpan.nameIndex) { if (decodeResult.error) { decodedErrors = ["!!^^ !!^^ There was decoding error in the sourcemap at this location: " + decodeResult.error]; } @@ -288,7 +288,7 @@ module Harness.SourceMapRecoder { } export function recordNewSourceFileSpan(sourceMapSpan: ts.SourceMapSpan, newSourceFileCode: string) { - assert.isTrue(spansOnSingleLine.length == 0 || spansOnSingleLine[0].sourceMapSpan.emittedLine !== sourceMapSpan.emittedLine, "new file source map span should be on new line. We currently handle only that scenario"); + assert.isTrue(spansOnSingleLine.length === 0 || spansOnSingleLine[0].sourceMapSpan.emittedLine !== sourceMapSpan.emittedLine, "new file source map span should be on new line. We currently handle only that scenario"); recordSourceMapSpan(sourceMapSpan); assert.isTrue(spansOnSingleLine.length === 1); @@ -395,9 +395,9 @@ module Harness.SourceMapRecoder { var tsCodeLineMap = ts.computeLineStarts(sourceText); for (var i = 0; i < tsCodeLineMap.length; i++) { - writeSourceMapIndent(prevEmittedCol, i == 0 ? markerIds[index] : " >"); + writeSourceMapIndent(prevEmittedCol, i === 0 ? markerIds[index] : " >"); sourceMapRecoder.Write(getTextOfLine(i, tsCodeLineMap, sourceText)); - if (i == tsCodeLineMap.length - 1) { + if (i === tsCodeLineMap.length - 1) { sourceMapRecoder.WriteLine(""); } } @@ -447,7 +447,7 @@ module Harness.SourceMapRecoder { for (var j = 0; j < sourceMapData.sourceMapDecodedMappings.length; j++) { var decodedSourceMapping = sourceMapData.sourceMapDecodedMappings[j]; var currentSourceFile = program.getSourceFile(sourceMapData.inputSourceFileNames[decodedSourceMapping.sourceIndex]); - if (currentSourceFile != prevSourceFile) { + if (currentSourceFile !== prevSourceFile) { SourceMapSpanWriter.recordNewSourceFileSpan(decodedSourceMapping, currentSourceFile.text); prevSourceFile = currentSourceFile; } diff --git a/src/harness/syntacticCleaner.ts b/src/harness/syntacticCleaner.ts deleted file mode 100644 index 05b42951246..00000000000 --- a/src/harness/syntacticCleaner.ts +++ /dev/null @@ -1,30 +0,0 @@ -// Use this to get emitter-agnostic baselines - -class SyntacticCleaner { - static clean(sourceFileContents: string) { - return sourceFileContents; - } -} - -/* TODO: Re-implement or maybe delete -class SyntacticCleaner extends TypeScript.SyntaxWalker { - private emit: string[] = []; - - public visitToken(token: TypeScript.ISyntaxToken): void { - this.emit.push(token.text()); - if (token.kind() === TypeScript.SyntaxKind.SemicolonToken) { - this.emit.push('\r\n'); - } else { - this.emit.push(' '); - - } - } - - static clean(sourceFileContents: string): string { - var parsed = TypeScript.Parser.parse('_emitted.ts', TypeScript.SimpleText.fromString(sourceFileContents), TypeScript.LanguageVersion.EcmaScript5, false); - var cleaner = new SyntacticCleaner(); - cleaner.visitSourceUnit(parsed.sourceUnit()); - return cleaner.emit.join(''); - } -} -*/ diff --git a/src/harness/test262Runner.ts b/src/harness/test262Runner.ts index 0091da5e911..5f8250c5e23 100644 --- a/src/harness/test262Runner.ts +++ b/src/harness/test262Runner.ts @@ -1,6 +1,5 @@ /// /// -/// class Test262BaselineRunner extends RunnerBase { private static basePath = 'internal/cases/test262'; @@ -65,7 +64,7 @@ class Test262BaselineRunner extends RunnerBase { it('has the expected emitted code', () => { Harness.Baseline.runBaseline('has the expected emitted code', testState.filename + '.output.js', () => { var files = testState.compilerResult.files.filter(f=> f.fileName !== Test262BaselineRunner.helpersFilePath); - return Harness.Compiler.collateOutputs(files, s => SyntacticCleaner.clean(s)); + return Harness.Compiler.collateOutputs(files); }, false, Test262BaselineRunner.baselineOptions); }); diff --git a/src/harness/typeWriter.ts b/src/harness/typeWriter.ts index 533f90a2d83..b68e606c79d 100644 --- a/src/harness/typeWriter.ts +++ b/src/harness/typeWriter.ts @@ -41,7 +41,10 @@ class TypeWriterWalker { var lineAndCharacter = this.currentSourceFile.getLineAndCharacterOfPosition(actualPos); var sourceText = ts.getTextOfNodeFromSourceText(this.currentSourceFile.text, node); - var type = this.checker.getTypeAtLocation(node); + // Workaround to ensure we output 'C' instead of 'typeof C' for base class expressions + // var type = this.checker.getTypeAtLocation(node); + var type = node.parent && ts.isExpressionWithTypeArgumentsInClassExtendsClause(node.parent) && this.checker.getTypeAtLocation(node.parent) || this.checker.getTypeAtLocation(node); + ts.Debug.assert(type !== undefined, "type doesn't exist"); var symbol = this.checker.getSymbolAtLocation(node); diff --git a/src/lib/core.d.ts b/src/lib/core.d.ts index c03ab344ab2..78971965664 100644 --- a/src/lib/core.d.ts +++ b/src/lib/core.d.ts @@ -1150,7 +1150,7 @@ interface ArrayConstructor { (arrayLength?: number): any[]; (arrayLength: number): T[]; (...items: T[]): T[]; - isArray(arg: any): boolean; + isArray(arg: any): arg is Array; prototype: Array; } diff --git a/src/lib/dom.es6.d.ts b/src/lib/dom.es6.d.ts new file mode 100644 index 00000000000..8702201bb9e --- /dev/null +++ b/src/lib/dom.es6.d.ts @@ -0,0 +1,11 @@ +interface DOMTokenList { + [Symbol.iterator](): IterableIterator; +} + +interface NodeList { + [Symbol.iterator](): IterableIterator +} + +interface NodeListOf { + [Symbol.iterator](): IterableIterator +} \ No newline at end of file diff --git a/src/lib/dom.generated.d.ts b/src/lib/dom.generated.d.ts index 5a4151c0c1c..e1f06f11009 100644 --- a/src/lib/dom.generated.d.ts +++ b/src/lib/dom.generated.d.ts @@ -7677,10 +7677,10 @@ declare var MediaQueryList: { interface MediaSource extends EventTarget { activeSourceBuffers: SourceBufferList; duration: number; - readyState: string; + readyState: number; sourceBuffers: SourceBufferList; addSourceBuffer(type: string): SourceBuffer; - endOfStream(error?: string): void; + endOfStream(error?: number): void; removeSourceBuffer(sourceBuffer: SourceBuffer): void; } @@ -8409,7 +8409,7 @@ declare var PopStateEvent: { interface Position { coords: Coordinates; - timestamp: Date; + timestamp: number; } declare var Position: { @@ -11090,9 +11090,17 @@ interface WebGLRenderingContext { stencilMaskSeparate(face: number, mask: number): void; stencilOp(fail: number, zfail: number, zpass: number): void; stencilOpSeparate(face: number, fail: number, zfail: number, zpass: number): void; + texImage2D(target: number, level: number, internalformat: number, width: number, height: number, border: number, format: number, type: number, pixels: ArrayBufferView): void; + texImage2D(target: number, level: number, internalformat: number, format: number, type: number, image: HTMLImageElement): void; + texImage2D(target: number, level: number, internalformat: number, format: number, type: number, canvas: HTMLCanvasElement): void; + texImage2D(target: number, level: number, internalformat: number, format: number, type: number, video: HTMLVideoElement): void; texImage2D(target: number, level: number, internalformat: number, format: number, type: number, pixels: ImageData): void; texParameterf(target: number, pname: number, param: number): void; texParameteri(target: number, pname: number, param: number): void; + texSubImage2D(target: number, level: number, xoffset: number, yoffset: number, width: number, height: number, format: number, type: number, pixels: ArrayBufferView): void; + texSubImage2D(target: number, level: number, xoffset: number, yoffset: number, format: number, type: number, image: HTMLImageElement): void; + texSubImage2D(target: number, level: number, xoffset: number, yoffset: number, format: number, type: number, canvas: HTMLCanvasElement): void; + texSubImage2D(target: number, level: number, xoffset: number, yoffset: number, format: number, type: number, video: HTMLVideoElement): void; texSubImage2D(target: number, level: number, xoffset: number, yoffset: number, format: number, type: number, pixels: ImageData): void; uniform1f(location: WebGLUniformLocation, x: number): void; uniform1fv(location: WebGLUniformLocation, v: any): void; @@ -12332,10 +12340,11 @@ interface DocumentEvent { createEvent(eventInterface:"AriaRequestEvent"): AriaRequestEvent; createEvent(eventInterface:"AudioProcessingEvent"): AudioProcessingEvent; createEvent(eventInterface:"BeforeUnloadEvent"): BeforeUnloadEvent; + createEvent(eventInterface:"ClipboardEvent"): ClipboardEvent; createEvent(eventInterface:"CloseEvent"): CloseEvent; createEvent(eventInterface:"CommandEvent"): CommandEvent; createEvent(eventInterface:"CompositionEvent"): CompositionEvent; - createEvent(eventInterface: "CustomEvent"): CustomEvent; + createEvent(eventInterface:"CustomEvent"): CustomEvent; createEvent(eventInterface:"DeviceMotionEvent"): DeviceMotionEvent; createEvent(eventInterface:"DeviceOrientationEvent"): DeviceOrientationEvent; createEvent(eventInterface:"DragEvent"): DragEvent; @@ -12358,8 +12367,6 @@ interface DocumentEvent { createEvent(eventInterface:"MouseEvent"): MouseEvent; createEvent(eventInterface:"MouseEvents"): MouseEvent; createEvent(eventInterface:"MouseWheelEvent"): MouseWheelEvent; - createEvent(eventInterface:"MSGestureEvent"): MSGestureEvent; - createEvent(eventInterface:"MSPointerEvent"): MSPointerEvent; createEvent(eventInterface:"MutationEvent"): MutationEvent; createEvent(eventInterface:"MutationEvents"): MutationEvent; createEvent(eventInterface:"NavigationCompletedEvent"): NavigationCompletedEvent; @@ -12971,4 +12978,4 @@ declare function addEventListener(type: "unload", listener: (ev: Event) => any, declare function addEventListener(type: "volumechange", listener: (ev: Event) => any, useCapture?: boolean): void; declare function addEventListener(type: "waiting", listener: (ev: Event) => any, useCapture?: boolean): void; declare function addEventListener(type: "wheel", listener: (ev: WheelEvent) => any, useCapture?: boolean): void; -declare function addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; \ No newline at end of file +declare function addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; diff --git a/src/lib/es6.d.ts b/src/lib/es6.d.ts index dc082c8f0a6..625a4eca9e1 100644 --- a/src/lib/es6.d.ts +++ b/src/lib/es6.d.ts @@ -316,6 +316,11 @@ interface Array { copyWithin(target: number, start: number, end?: number): T[]; } +interface IArguments { + /** Iterator */ + [Symbol.iterator](): IterableIterator; +} + interface ArrayConstructor { /** * Creates an array from an array-like object. @@ -500,14 +505,6 @@ interface GeneratorFunctionConstructor { } declare var GeneratorFunction: GeneratorFunctionConstructor; -interface Generator extends IterableIterator { - next(value?: any): IteratorResult; - throw(exception: any): IteratorResult; - return(value: T): IteratorResult; - [Symbol.iterator](): Generator; - [Symbol.toStringTag]: string; -} - interface Math { /** * Returns the number of leading zero bits in the 32-bit binary representation of a number. diff --git a/src/lib/intl.d.ts b/src/lib/intl.d.ts index 66e51ddbc5a..57df70672d4 100644 --- a/src/lib/intl.d.ts +++ b/src/lib/intl.d.ts @@ -41,6 +41,11 @@ declare module Intl { currency?: string; currencyDisplay?: string; useGrouping?: boolean; + minimumintegerDigits?: number; + minimumFractionDigits?: number; + maximumFractionDigits?: number; + minimumSignificantDigits?: number; + maximumSignificantDigits?: number; } interface ResolvedNumberFormatOptions { @@ -103,7 +108,7 @@ declare module Intl { } interface DateTimeFormat { - format(date: number): string; + format(date?: Date | number): string; resolvedOptions(): ResolvedDateTimeFormatOptions; } var DateTimeFormat: { diff --git a/src/server/client.ts b/src/server/client.ts index 3582d508322..e4a524dd210 100644 --- a/src/server/client.ts +++ b/src/server/client.ts @@ -1,6 +1,6 @@ /// -module ts.server { +namespace ts.server { export interface SessionClientHost extends LanguageServiceHost { writeMessage(message: string): void; @@ -171,6 +171,21 @@ module ts.server { documentation: [{ kind: "text", text: response.body.documentation }] }; } + + getProjectInfo(fileName: string, needFileNameList: boolean): protocol.ProjectInfo { + var args: protocol.ProjectInfoRequestArgs = { + file: fileName, + needFileNameList: needFileNameList + }; + + var request = this.processRequest(CommandNames.ProjectInfo, args); + var response = this.processResponse(request); + + return { + configFileName: response.body.configFileName, + fileNameList: response.body.fileNameList + }; + } getCompletionsAtPosition(fileName: string, position: number): CompletionInfo { var lineOffset = this.positionToOneBasedLineOffset(fileName, position); @@ -204,7 +219,7 @@ module ts.server { var request = this.processRequest(CommandNames.CompletionDetails, args); var response = this.processResponse(request); - Debug.assert(response.body.length == 1, "Unexpected length of completion details response body."); + Debug.assert(response.body.length === 1, "Unexpected length of completion details response body."); return response.body[0]; } @@ -414,8 +429,8 @@ module ts.server { if (!this.lastRenameEntry || this.lastRenameEntry.fileName !== fileName || this.lastRenameEntry.position !== position || - this.lastRenameEntry.findInStrings != findInStrings || - this.lastRenameEntry.findInComments != findInComments) { + this.lastRenameEntry.findInStrings !== findInStrings || + this.lastRenameEntry.findInComments !== findInComments) { this.getRenameInfo(fileName, position, findInStrings, findInComments); } diff --git a/src/server/editorServices.ts b/src/server/editorServices.ts index 9c87a20c851..91d400ff263 100644 --- a/src/server/editorServices.ts +++ b/src/server/editorServices.ts @@ -2,9 +2,8 @@ /// /// /// -/// -module ts.server { +namespace ts.server { export interface Logger { close(): void; isVerbose(): boolean; @@ -28,7 +27,7 @@ module ts.server { }); } - class ScriptInfo { + export class ScriptInfo { svc: ScriptVersionCache; children: ScriptInfo[] = []; // files referenced by this file defaultProject: Project; // project to use by default for file @@ -36,7 +35,7 @@ module ts.server { formatCodeOptions = ts.clone(CompilerService.defaultFormatCodeOptions); constructor(private host: ServerHost, public fileName: string, public content: string, public isOpen = false) { - this.svc = ScriptVersionCache.fromString(content); + this.svc = ScriptVersionCache.fromString(host, content); } setFormatOptions(formatOptions: protocol.FormatOptions): void { @@ -80,7 +79,7 @@ module ts.server { } } - class LSHost implements ts.LanguageServiceHost { + export class LSHost implements ts.LanguageServiceHost { ls: ts.LanguageService = null; compilationSettings: ts.CompilerOptions; filenameToScript: ts.Map = {}; @@ -273,7 +272,7 @@ module ts.server { } } - interface ProjectOptions { + export interface ProjectOptions { // these fields can be present in the project file files?: string[]; compilerOptions?: ts.CompilerOptions; @@ -305,6 +304,11 @@ module ts.server { return this.projectService.openFile(filename, false); } + getFileNameList() { + let sourceFiles = this.program.getSourceFiles(); + return sourceFiles.map(sourceFile => sourceFile.fileName); + } + getSourceFile(info: ScriptInfo) { return this.filenameToSourceFile[info.fileName]; } @@ -371,7 +375,7 @@ module ts.server { } } - interface ProjectOpenResult { + export interface ProjectOpenResult { success?: boolean; errorMsg?: string; project?: Project; @@ -387,11 +391,11 @@ module ts.server { return copiedList; } - interface ProjectServiceEventHandler { + export interface ProjectServiceEventHandler { (eventName: string, project: Project, fileName: string): void; } - interface HostConfiguration { + export interface HostConfiguration { formatCodeOptions: ts.FormatCodeOptions; hostInfo: string; } @@ -624,7 +628,7 @@ module ts.server { for (var i = 0, len = this.openFilesReferenced.length; i < len; i++) { var f = this.openFilesReferenced[i]; // if f was referenced by the removed project, remember it - if (f.defaultProject == removedProject) { + if (f.defaultProject === removedProject) { f.defaultProject = undefined; orphanFiles.push(f); } @@ -651,7 +655,7 @@ module ts.server { for (var i = 0, len = this.inferredProjects.length; i < len; i++) { var inferredProject = this.inferredProjects[i]; inferredProject.updateGraph(); - if (inferredProject != excludedProject) { + if (inferredProject !== excludedProject) { if (inferredProject.getSourceFile(info)) { info.defaultProject = inferredProject; referencingProjects.push(inferredProject); @@ -705,7 +709,7 @@ module ts.server { var rootFile = this.openFileRoots[i]; var rootedProject = rootFile.defaultProject; var referencingProjects = this.findReferencingProjects(rootFile, rootedProject); - if (referencingProjects.length == 0) { + if (referencingProjects.length === 0) { rootFile.defaultProject = rootedProject; openFileRoots.push(rootFile); } @@ -911,7 +915,7 @@ module ts.server { return rawConfig.error; } else { - var parsedCommandLine = ts.parseConfigFile(rawConfig.config, ts.sys, dirPath); + var parsedCommandLine = ts.parseConfigFile(rawConfig.config, this.host, dirPath); if (parsedCommandLine.errors && (parsedCommandLine.errors.length > 0)) { return { errorMsg: "tsconfig option errors" }; } @@ -948,7 +952,7 @@ module ts.server { } - class CompilerService { + export class CompilerService { host: LSHost; languageService: ts.LanguageService; classifier: ts.Classifier; @@ -980,7 +984,7 @@ module ts.server { static defaultFormatCodeOptions: ts.FormatCodeOptions = { IndentSize: 4, TabSize: 4, - NewLineCharacter: ts.sys.newLine, + NewLineCharacter: ts.sys ? ts.sys.newLine : '\n', ConvertTabsToSpaces: true, InsertSpaceAfterCommaDelimiter: true, InsertSpaceAfterSemicolonInForStatements: true, @@ -994,7 +998,7 @@ module ts.server { } - interface LineCollection { + export interface LineCollection { charCount(): number; lineCount(): number; isLeaf(): boolean; @@ -1008,7 +1012,7 @@ module ts.server { leaf?: LineLeaf; } - enum CharRangeSection { + export enum CharRangeSection { PreStart, Start, Entire, @@ -1017,7 +1021,7 @@ module ts.server { PostEnd } - interface ILineIndexWalker { + export interface ILineIndexWalker { goSubtree: boolean; done: boolean; leaf(relativeStart: number, relativeLength: number, lineCollection: LineLeaf): void; @@ -1077,7 +1081,7 @@ module ts.server { for (var k = this.endBranch.length - 1; k >= 0; k--) { (this.endBranch[k]).updateCounts(); - if (this.endBranch[k].charCount() == 0) { + if (this.endBranch[k].charCount() === 0) { lastZeroCount = this.endBranch[k]; if (k > 0) { branchParent = this.endBranch[k - 1]; @@ -1142,7 +1146,7 @@ module ts.server { post(relativeStart: number, relativeLength: number, lineCollection: LineCollection, parent: LineCollection, nodeType: CharRangeSection): LineCollection { // have visited the path for start of range, now looking for end // if range is on single line, we will never make this state transition - if (lineCollection == this.lineCollectionAtBranch) { + if (lineCollection === this.lineCollectionAtBranch) { this.state = CharRangeSection.End; } // always pop stack because post only called when child has been visited @@ -1154,7 +1158,7 @@ module ts.server { // currentNode corresponds to parent, but in the new tree var currentNode = this.stack[this.stack.length - 1]; - if ((this.state == CharRangeSection.Entire) && (nodeType == CharRangeSection.Start)) { + if ((this.state === CharRangeSection.Entire) && (nodeType === CharRangeSection.Start)) { // if range is on single line, we will never make this state transition this.state = CharRangeSection.Start; this.branchNode = currentNode; @@ -1171,12 +1175,12 @@ module ts.server { switch (nodeType) { case CharRangeSection.PreStart: this.goSubtree = false; - if (this.state != CharRangeSection.End) { + if (this.state !== CharRangeSection.End) { currentNode.add(lineCollection); } break; case CharRangeSection.Start: - if (this.state == CharRangeSection.End) { + if (this.state === CharRangeSection.End) { this.goSubtree = false; } else { @@ -1186,7 +1190,7 @@ module ts.server { } break; case CharRangeSection.Entire: - if (this.state != CharRangeSection.End) { + if (this.state !== CharRangeSection.End) { child = fresh(lineCollection); currentNode.add(child); this.startPath[this.startPath.length] = child; @@ -1203,7 +1207,7 @@ module ts.server { this.goSubtree = false; break; case CharRangeSection.End: - if (this.state != CharRangeSection.End) { + if (this.state !== CharRangeSection.End) { this.goSubtree = false; } else { @@ -1216,7 +1220,7 @@ module ts.server { break; case CharRangeSection.PostEnd: this.goSubtree = false; - if (this.state != CharRangeSection.Start) { + if (this.state !== CharRangeSection.Start) { currentNode.add(lineCollection); } break; @@ -1228,10 +1232,10 @@ module ts.server { } // just gather text from the leaves leaf(relativeStart: number, relativeLength: number, ll: LineLeaf) { - if (this.state == CharRangeSection.Start) { + if (this.state === CharRangeSection.Start) { this.initialText = ll.text.substring(0, relativeStart); } - else if (this.state == CharRangeSection.Entire) { + else if (this.state === CharRangeSection.Entire) { this.initialText = ll.text.substring(0, relativeStart); this.trailingText = ll.text.substring(relativeStart + relativeLength); } @@ -1243,7 +1247,7 @@ module ts.server { } // text change information - class TextChange { + export class TextChange { constructor(public pos: number, public deleteLen: number, public insertedText?: string) { } @@ -1258,6 +1262,7 @@ module ts.server { versions: LineIndexSnapshot[] = []; minVersion = 0; // no versions earlier than min version will maintain change history private currentVersion = 0; + private host: ServerHost; static changeNumberThreshold = 8; static changeLengthThreshold = 256; @@ -1285,7 +1290,7 @@ module ts.server { } reloadFromFile(filename: string, cb?: () => any) { - var content = ts.sys.readFile(filename); + var content = this.host.readFile(filename); this.reload(content); if (cb) cb(); @@ -1355,10 +1360,11 @@ module ts.server { } } - static fromString(script: string) { + static fromString(host: ServerHost, script: string) { var svc = new ScriptVersionCache(); var snap = new LineIndexSnapshot(0, svc); svc.versions[svc.currentVersion] = snap; + svc.host = host; snap.index = new LineIndex(); var lm = LineIndex.linesFromText(script); snap.index.load(lm.lines); @@ -1366,7 +1372,7 @@ module ts.server { } } - class LineIndexSnapshot implements ts.IScriptSnapshot { + export class LineIndexSnapshot implements ts.IScriptSnapshot { index: LineIndex; changesSincePreviousVersion: TextChange[] = []; @@ -1494,8 +1500,8 @@ module ts.server { function editFlat(source: string, s: number, dl: number, nt = "") { return source.substring(0, s) + nt + source.substring(s + dl, source.length); } - if (this.root.charCount() == 0) { - // TODO: assert deleteLength == 0 + if (this.root.charCount() === 0) { + // TODO: assert deleteLength === 0 if (newText) { this.load(LineIndex.linesFromText(newText).lines); return this; @@ -1523,7 +1529,7 @@ module ts.server { // check whether last characters deleted are line break var e = pos + deleteLength; var lineInfo = this.charOffsetToLineNumberAndPos(e); - if ((lineInfo && (lineInfo.offset == 0))) { + if ((lineInfo && (lineInfo.offset === 0))) { // move range end just past line that will merge with previous line deleteLength += lineInfo.text.length; // store text by appending to end of insertedText @@ -1569,7 +1575,7 @@ module ts.server { interiorNodes[i].totalChars = charCount; interiorNodes[i].totalLines = lineCount; } - if (interiorNodes.length == 1) { + if (interiorNodes.length === 1) { return interiorNodes[0]; } else { @@ -1580,7 +1586,7 @@ module ts.server { static linesFromText(text: string) { var lineStarts = ts.computeLineStarts(text); - if (lineStarts.length == 0) { + if (lineStarts.length === 0) { return { lines: [], lineMap: lineStarts }; } var lines = new Array(lineStarts.length); @@ -1600,7 +1606,7 @@ module ts.server { } } - class LineNode implements LineCollection { + export class LineNode implements LineCollection { totalChars = 0; totalLines = 0; children: LineCollection[] = []; @@ -1816,7 +1822,7 @@ module ts.server { findChildIndex(child: LineCollection) { var childIndex = 0; var clen = this.children.length; - while ((this.children[childIndex] != child) && (childIndex < clen)) childIndex++; + while ((this.children[childIndex] !== child) && (childIndex < clen)) childIndex++; return childIndex; } @@ -1825,7 +1831,7 @@ module ts.server { var clen = this.children.length; var nodeCount = nodes.length; // if child is last and there is more room and only one node to place, place it - if ((clen < lineCollectionCapacity) && (childIndex == (clen - 1)) && (nodeCount == 1)) { + if ((clen < lineCollectionCapacity) && (childIndex === (clen - 1)) && (nodeCount === 1)) { this.add(nodes[0]); this.updateCounts(); return []; @@ -1849,13 +1855,13 @@ module ts.server { var splitNode = splitNodes[0]; while (nodeIndex < nodeCount) { splitNode.add(nodes[nodeIndex++]); - if (splitNode.children.length == lineCollectionCapacity) { + if (splitNode.children.length === lineCollectionCapacity) { splitNodeIndex++; splitNode = splitNodes[splitNodeIndex]; } } for (i = splitNodes.length - 1; i >= 0; i--) { - if (splitNodes[i].children.length == 0) { + if (splitNodes[i].children.length === 0) { splitNodes.length--; } } @@ -1886,7 +1892,7 @@ module ts.server { } } - class LineLeaf implements LineCollection { + export class LineLeaf implements LineCollection { udata: any; constructor(public text: string) { diff --git a/src/server/node.d.ts b/src/server/node.d.ts index 2002f973a37..8f7237382e5 100644 --- a/src/server/node.d.ts +++ b/src/server/node.d.ts @@ -584,9 +584,9 @@ declare module NodeJS { export interface Response extends Message { request_seq: number; success: boolean; - /** Contains error message if success == false. */ + /** Contains error message if success === false. */ message?: string; - /** Contains message body if success == true. */ + /** Contains message body if success === true. */ body?: any; } diff --git a/src/server/protocol.d.ts b/src/server/protocol.d.ts index b95d5e99864..017a8c1d81a 100644 --- a/src/server/protocol.d.ts +++ b/src/server/protocol.d.ts @@ -1,7 +1,7 @@ /** * Declaration module describing the TypeScript Server protocol */ -declare module ts.server.protocol { +declare namespace ts.server.protocol { /** * A TypeScript Server message */ @@ -67,12 +67,12 @@ declare module ts.server.protocol { command: string; /** - * Contains error message if success == false. + * Contains error message if success === false. */ message?: string; /** - * Contains message body if success == true. + * Contains message body if success === true. */ body?: any; } @@ -87,6 +87,45 @@ declare module ts.server.protocol { file: string; } + /** + * Arguments for ProjectInfoRequest request. + */ + export interface ProjectInfoRequestArgs extends FileRequestArgs { + /** + * Indicate if the file name list of the project is needed + */ + needFileNameList: boolean; + } + + /** + * A request to get the project information of the current file + */ + export interface ProjectInfoRequest extends Request { + arguments: ProjectInfoRequestArgs + } + + /** + * Response message body for "projectInfo" request + */ + export interface ProjectInfo { + /** + * For configured project, this is the normalized path of the 'tsconfig.json' file + * For inferred project, this is undefined + */ + configFileName: string; + /** + * The list of normalized file name in the project, including 'lib.d.ts' + */ + fileNameList?: string[]; + } + + /** + * Response message for "projectInfo" request + */ + export interface ProjectInfoResponse extends Response { + body?: ProjectInfo; + } + /** * Request whose sole parameter is a file name. */ diff --git a/src/server/server.ts b/src/server/server.ts index 828deca2b2d..843197b918a 100644 --- a/src/server/server.ts +++ b/src/server/server.ts @@ -1,7 +1,7 @@ /// /// -module ts.server { +namespace ts.server { var nodeproto: typeof NodeJS._debugger = require('_debugger'); var readline: NodeJS.ReadLine = require('readline'); var path: NodeJS.Path = require('path'); @@ -11,7 +11,7 @@ module ts.server { input: process.stdin, output: process.stdout, terminal: false, - }); + }); class Logger implements ts.server.Logger { fd = -1; @@ -123,7 +123,7 @@ module ts.server { if (err) { watchedFile.callback(watchedFile.fileName); } - else if (watchedFile.mtime.getTime() != stats.mtime.getTime()) { + else if (watchedFile.mtime.getTime() !== stats.mtime.getTime()) { watchedFile.mtime = WatchedFileSet.getModifiedTime(watchedFile.fileName); watchedFile.callback(watchedFile.fileName); } @@ -138,7 +138,7 @@ module ts.server { var count = 0; var nextToCheck = this.nextFileToCheck; var firstCheck = -1; - while ((count < this.chunkSize) && (nextToCheck != firstCheck)) { + while ((count < this.chunkSize) && (nextToCheck !== firstCheck)) { this.poll(nextToCheck); if (firstCheck < 0) { firstCheck = nextToCheck; @@ -170,11 +170,11 @@ module ts.server { removeFile(file: WatchedFile) { this.watchedFiles = WatchedFileSet.copyListRemovingItem(file, this.watchedFiles); } - } + } class IOSession extends Session { constructor(host: ServerHost, logger: ts.server.Logger) { - super(host, logger); + super(host, Buffer.byteLength, process.hrtime, logger); } exit() { diff --git a/src/server/session.ts b/src/server/session.ts index baf0a085ad4..c95b1a7cc1b 100644 --- a/src/server/session.ts +++ b/src/server/session.ts @@ -1,10 +1,9 @@ /// /// -/// /// /// -module ts.server { +namespace ts.server { var spaceCache:string[] = []; interface StackTraceError extends Error { @@ -31,7 +30,7 @@ module ts.server { if (a < b) { return -1; } - else if (a == b) { + else if (a === b) { return 0; } else return 1; @@ -43,7 +42,7 @@ module ts.server { } else if (a.file == b.file) { var n = compareNumber(a.start.line, b.start.line); - if (n == 0) { + if (n === 0) { return compareNumber(a.start.offset, b.start.offset); } else return n; @@ -61,7 +60,7 @@ module ts.server { }; } - interface PendingErrorCheck { + export interface PendingErrorCheck { fileName: string; project: Project; } @@ -76,29 +75,30 @@ module ts.server { } export module CommandNames { - export var Brace = "brace"; - export var Change = "change"; - export var Close = "close"; - export var Completions = "completions"; - export var CompletionDetails = "completionEntryDetails"; - export var Configure = "configure"; - export var Definition = "definition"; - export var Exit = "exit"; - export var Format = "format"; - export var Formatonkey = "formatonkey"; - export var Geterr = "geterr"; - export var NavBar = "navbar"; - export var Navto = "navto"; - export var Occurrences = "occurrences"; - export var Open = "open"; - export var Quickinfo = "quickinfo"; - export var References = "references"; - export var Reload = "reload"; - export var Rename = "rename"; - export var Saveto = "saveto"; - export var SignatureHelp = "signatureHelp"; - export var TypeDefinition = "typeDefinition"; - export var Unknown = "unknown"; + export const Brace = "brace"; + export const Change = "change"; + export const Close = "close"; + export const Completions = "completions"; + export const CompletionDetails = "completionEntryDetails"; + export const Configure = "configure"; + export const Definition = "definition"; + export const Exit = "exit"; + export const Format = "format"; + export const Formatonkey = "formatonkey"; + export const Geterr = "geterr"; + export const NavBar = "navbar"; + export const Navto = "navto"; + export const Occurrences = "occurrences"; + export const Open = "open"; + export const Quickinfo = "quickinfo"; + export const References = "references"; + export const Reload = "reload"; + export const Rename = "rename"; + export const Saveto = "saveto"; + export const SignatureHelp = "signatureHelp"; + export const TypeDefinition = "typeDefinition"; + export const ProjectInfo = "projectInfo"; + export const Unknown = "unknown"; } module Errors { @@ -113,11 +113,16 @@ module ts.server { pendingOperation = false; fileHash: ts.Map = {}; nextFileId = 1; - errorTimer: NodeJS.Timer; + errorTimer: any; /*NodeJS.Timer | number*/ immediateId: any; changeSeq = 0; - constructor(private host: ServerHost, private logger: Logger) { + constructor( + private host: ServerHost, + private byteLength: (buf: string, encoding?: string) => number, + private hrtime: (start?: number[]) => number[], + private logger: Logger + ) { this.projectService = new ProjectService(host, logger, (eventName,project,fileName) => { this.handleEvent(eventName, project, fileName); @@ -128,7 +133,7 @@ module ts.server { if (eventName == "context") { this.projectService.log("got context event, updating diagnostics for" + fileName, "Info"); this.updateErrorCheck([{ fileName, project }], this.changeSeq, - (n) => n == this.changeSeq, 100); + (n) => n === this.changeSeq, 100); } } @@ -148,17 +153,17 @@ module ts.server { this.host.write(line + this.host.newLine); } - send(msg: NodeJS._debugger.Message) { + send(msg: protocol.Message) { var json = JSON.stringify(msg); if (this.logger.isVerbose()) { this.logger.info(msg.type + ": " + json); } - this.sendLineToClient('Content-Length: ' + (1 + Buffer.byteLength(json, 'utf8')) + + this.sendLineToClient('Content-Length: ' + (1 + this.byteLength(json, 'utf8')) + '\r\n\r\n' + json); } event(info: any, eventName: string) { - var ev: NodeJS._debugger.Event = { + var ev: protocol.Event = { seq: 0, type: "event", event: eventName, @@ -338,6 +343,21 @@ module ts.server { }); } + getProjectInfo(fileName: string, needFileNameList: boolean): protocol.ProjectInfo { + fileName = ts.normalizePath(fileName) + let project = this.projectService.getProjectForFile(fileName) + + let projectInfo: protocol.ProjectInfo = { + configFileName: project.projectFilename + } + + if (needFileNameList) { + projectInfo.fileNameList = project.getFileNameList(); + } + + return projectInfo; + } + getRenameLocations(line: number, offset: number, fileName: string,findInComments: boolean, findInStrings: boolean): protocol.RenameResponseBody { var file = ts.normalizePath(fileName); var project = this.projectService.getProjectForFile(file); @@ -530,7 +550,7 @@ module ts.server { // getFormattingEditsAfterKeytroke either empty or pertaining // only to the previous line. If all this is true, then // add edits necessary to properly indent the current line. - if ((key == "\n") && ((!edits) || (edits.length == 0) || allEditsBeforePos(edits, position))) { + if ((key == "\n") && ((!edits) || (edits.length === 0) || allEditsBeforePos(edits, position))) { var scriptInfo = compilerService.host.getScriptInfo(file); if (scriptInfo) { var lineInfo = scriptInfo.getLineInfo(line); @@ -606,7 +626,7 @@ module ts.server { } return completions.entries.reduce((result: protocol.CompletionEntry[], entry: ts.CompletionEntry) => { - if (completions.isMemberCompletion || (entry.name.toLowerCase().indexOf(prefix.toLowerCase()) == 0)) { + if (completions.isMemberCompletion || (entry.name.toLowerCase().indexOf(prefix.toLowerCase()) === 0)) { result.push(entry); } return result; @@ -673,7 +693,7 @@ module ts.server { }, []); if (checkList.length > 0) { - this.updateErrorCheck(checkList, this.changeSeq,(n) => n == this.changeSeq, delay) + this.updateErrorCheck(checkList, this.changeSeq,(n) => n === this.changeSeq, delay) } } @@ -688,7 +708,7 @@ module ts.server { compilerService.host.editScript(file, start, end, insertString); this.changeSeq++; } - this.updateProjectStructure(this.changeSeq, (n) => n == this.changeSeq); + this.updateProjectStructure(this.changeSeq, (n) => n === this.changeSeq); } } @@ -822,7 +842,7 @@ module ts.server { onMessage(message: string) { if (this.logger.isVerbose()) { this.logger.info("request: " + message); - var start = process.hrtime(); + var start = this.hrtime(); } try { var request = JSON.parse(message); @@ -951,6 +971,11 @@ module ts.server { response = this.getOccurrences(line, offset, fileName); break; } + case CommandNames.ProjectInfo: { + var { file, needFileNameList } = request.arguments; + response = this.getProjectInfo(file, needFileNameList); + break; + } default: { this.projectService.log("Unrecognized JSON command: " + message); this.output(undefined, CommandNames.Unknown, request.seq, "Unrecognized JSON command: " + request.command); @@ -959,7 +984,7 @@ module ts.server { } if (this.logger.isVerbose()) { - var elapsed = process.hrtime(start); + var elapsed = this.hrtime(start); var seconds = elapsed[0] var nanoseconds = elapsed[1]; var elapsedMs = ((1e9 * seconds) + nanoseconds)/1000000.0; diff --git a/src/services/breakpoints.ts b/src/services/breakpoints.ts index 41079c08201..227ba6a7970 100644 --- a/src/services/breakpoints.ts +++ b/src/services/breakpoints.ts @@ -4,7 +4,7 @@ /// /* @internal */ -module ts.BreakpointResolver { +namespace ts.BreakpointResolver { /** * Get the breakpoint span in given sourceFile */ @@ -75,7 +75,7 @@ module ts.BreakpointResolver { return textSpan(node); } - if (node.parent.kind == SyntaxKind.ArrowFunction && (node.parent).body == node) { + if (node.parent.kind === SyntaxKind.ArrowFunction && (node.parent).body === node) { // If this is body of arrow function, it is allowed to have the breakpoint return textSpan(node); } diff --git a/src/services/formatting/formatting.ts b/src/services/formatting/formatting.ts index ef25d23a5c9..011f7d7fa5e 100644 --- a/src/services/formatting/formatting.ts +++ b/src/services/formatting/formatting.ts @@ -4,7 +4,7 @@ /// /* @internal */ -module ts.formatting { +namespace ts.formatting { export interface TextRangeWithKind extends TextRange { kind: SyntaxKind; diff --git a/src/services/formatting/formattingContext.ts b/src/services/formatting/formattingContext.ts index 84c09b86bb9..ab182797a3c 100644 --- a/src/services/formatting/formattingContext.ts +++ b/src/services/formatting/formattingContext.ts @@ -1,7 +1,7 @@ /// /* @internal */ -module ts.formatting { +namespace ts.formatting { export class FormattingContext { public currentTokenSpan: TextRangeWithKind; public nextTokenSpan: TextRangeWithKind; @@ -59,7 +59,7 @@ module ts.formatting { if (this.tokensAreOnSameLine === undefined) { let startLine = this.sourceFile.getLineAndCharacterOfPosition(this.currentTokenSpan.pos).line; let endLine = this.sourceFile.getLineAndCharacterOfPosition(this.nextTokenSpan.pos).line; - this.tokensAreOnSameLine = (startLine == endLine); + this.tokensAreOnSameLine = (startLine === endLine); } return this.tokensAreOnSameLine; @@ -84,7 +84,7 @@ module ts.formatting { private NodeIsOnOneLine(node: Node): boolean { let startLine = this.sourceFile.getLineAndCharacterOfPosition(node.getStart(this.sourceFile)).line; let endLine = this.sourceFile.getLineAndCharacterOfPosition(node.getEnd()).line; - return startLine == endLine; + return startLine === endLine; } private BlockIsOnOneLine(node: Node): boolean { diff --git a/src/services/formatting/formattingRequestKind.ts b/src/services/formatting/formattingRequestKind.ts index 4bdc83ffd45..d0397e4a8d9 100644 --- a/src/services/formatting/formattingRequestKind.ts +++ b/src/services/formatting/formattingRequestKind.ts @@ -1,7 +1,7 @@ /// /* @internal */ -module ts.formatting { +namespace ts.formatting { export const enum FormattingRequestKind { FormatDocument, FormatSelection, diff --git a/src/services/formatting/formattingScanner.ts b/src/services/formatting/formattingScanner.ts index e09b5dfba92..7e77878051c 100644 --- a/src/services/formatting/formattingScanner.ts +++ b/src/services/formatting/formattingScanner.ts @@ -2,7 +2,7 @@ /// /* @internal */ -module ts.formatting { +namespace ts.formatting { let scanner = createScanner(ScriptTarget.Latest, /*skipTrivia*/ false); export interface FormattingScanner { @@ -224,7 +224,7 @@ module ts.formatting { } function isOnToken(): boolean { - let current = (lastTokenInfo && lastTokenInfo.token.kind) || scanner.getToken(); + let current = (lastTokenInfo && lastTokenInfo.token.kind) || scanner.getToken(); let startPos = (lastTokenInfo && lastTokenInfo.token.pos) || scanner.getStartPos(); return startPos < endPos && current !== SyntaxKind.EndOfFileToken && !isTrivia(current); } diff --git a/src/services/formatting/rule.ts b/src/services/formatting/rule.ts index f1bb39e69c2..543295f364f 100644 --- a/src/services/formatting/rule.ts +++ b/src/services/formatting/rule.ts @@ -1,7 +1,7 @@ /// /* @internal */ -module ts.formatting { +namespace ts.formatting { export class Rule { constructor( public Descriptor: RuleDescriptor, diff --git a/src/services/formatting/ruleAction.ts b/src/services/formatting/ruleAction.ts index e5734b1a03c..13e9043e1c6 100644 --- a/src/services/formatting/ruleAction.ts +++ b/src/services/formatting/ruleAction.ts @@ -1,7 +1,7 @@ /// /* @internal */ -module ts.formatting { +namespace ts.formatting { export const enum RuleAction { Ignore = 0x00000001, Space = 0x00000002, diff --git a/src/services/formatting/ruleDescriptor.ts b/src/services/formatting/ruleDescriptor.ts index f3492715f3a..96506adc3dc 100644 --- a/src/services/formatting/ruleDescriptor.ts +++ b/src/services/formatting/ruleDescriptor.ts @@ -1,7 +1,7 @@ /// /* @internal */ -module ts.formatting { +namespace ts.formatting { export class RuleDescriptor { constructor(public LeftTokenRange: Shared.TokenRange, public RightTokenRange: Shared.TokenRange) { } diff --git a/src/services/formatting/ruleFlag.ts b/src/services/formatting/ruleFlag.ts index 4e6e002c184..7619f232ad4 100644 --- a/src/services/formatting/ruleFlag.ts +++ b/src/services/formatting/ruleFlag.ts @@ -2,7 +2,7 @@ /* @internal */ -module ts.formatting { +namespace ts.formatting { export const enum RuleFlags { None, CanDeleteNewLines diff --git a/src/services/formatting/ruleOperation.ts b/src/services/formatting/ruleOperation.ts index 1cca437e491..e897513bd27 100644 --- a/src/services/formatting/ruleOperation.ts +++ b/src/services/formatting/ruleOperation.ts @@ -1,7 +1,7 @@ /// /* @internal */ -module ts.formatting { +namespace ts.formatting { export class RuleOperation { public Context: RuleOperationContext; public Action: RuleAction; diff --git a/src/services/formatting/ruleOperationContext.ts b/src/services/formatting/ruleOperationContext.ts index 69ed3453a75..47330faa0dd 100644 --- a/src/services/formatting/ruleOperationContext.ts +++ b/src/services/formatting/ruleOperationContext.ts @@ -1,7 +1,7 @@ /// /* @internal */ -module ts.formatting { +namespace ts.formatting { export class RuleOperationContext { private customContextChecks: { (context: FormattingContext): boolean; }[]; @@ -14,7 +14,7 @@ module ts.formatting { public IsAny(): boolean { - return this == RuleOperationContext.Any; + return this === RuleOperationContext.Any; } public InContext(context: FormattingContext): boolean { diff --git a/src/services/formatting/rules.ts b/src/services/formatting/rules.ts index 4686616c3cc..abb08f5bf22 100644 --- a/src/services/formatting/rules.ts +++ b/src/services/formatting/rules.ts @@ -1,7 +1,7 @@ /// /* @internal */ -module ts.formatting { +namespace ts.formatting { export class Rules { public getRuleName(rule: Rule) { let o: ts.Map = this; @@ -199,6 +199,12 @@ module ts.formatting { public NoSpaceAfterAt: Rule; public SpaceAfterDecorator: Rule; + // Generator: function* + public NoSpaceBetweenFunctionKeywordAndStar: Rule; + public SpaceAfterStarInGeneratorDeclaration: Rule; + public NoSpaceBetweenYieldKeywordAndStar: Rule; + public SpaceBetweenYieldOrYieldStarAndOperand: Rule; + constructor() { /// /// Common Rules @@ -340,6 +346,11 @@ module ts.formatting { this.NoSpaceAfterAt = new Rule(RuleDescriptor.create3(SyntaxKind.AtToken, Shared.TokenRange.Any), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext), RuleAction.Delete)); this.SpaceAfterDecorator = new Rule(RuleDescriptor.create4(Shared.TokenRange.Any, Shared.TokenRange.FromTokens([SyntaxKind.Identifier, SyntaxKind.ExportKeyword, SyntaxKind.DefaultKeyword, SyntaxKind.ClassKeyword, SyntaxKind.StaticKeyword, SyntaxKind.PublicKeyword, SyntaxKind.PrivateKeyword, SyntaxKind.ProtectedKeyword, SyntaxKind.GetKeyword, SyntaxKind.SetKeyword, SyntaxKind.OpenBracketToken, SyntaxKind.AsteriskToken])), RuleOperation.create2(new RuleOperationContext(Rules.IsEndOfDecoratorContextOnSameLine), RuleAction.Space)); + this.NoSpaceBetweenFunctionKeywordAndStar = new Rule(RuleDescriptor.create1(SyntaxKind.FunctionKeyword, SyntaxKind.AsteriskToken), RuleOperation.create2(new RuleOperationContext(Rules.IsFunctionDeclarationOrFunctionExpressionContext), RuleAction.Delete)); + this.SpaceAfterStarInGeneratorDeclaration = new Rule(RuleDescriptor.create3(SyntaxKind.AsteriskToken, Shared.TokenRange.FromTokens([SyntaxKind.Identifier, SyntaxKind.OpenParenToken])), RuleOperation.create2(new RuleOperationContext(Rules.IsFunctionDeclarationOrFunctionExpressionContext), RuleAction.Space)); + this.NoSpaceBetweenYieldKeywordAndStar = new Rule(RuleDescriptor.create1(SyntaxKind.YieldKeyword, SyntaxKind.AsteriskToken), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsYieldOrYieldStarWithOperand), RuleAction.Delete)); + this.SpaceBetweenYieldOrYieldStarAndOperand = new Rule(RuleDescriptor.create4(Shared.TokenRange.FromTokens([SyntaxKind.YieldKeyword, SyntaxKind.AsteriskToken]), Shared.TokenRange.Any), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsYieldOrYieldStarWithOperand), RuleAction.Space)); + // These rules are higher in priority than user-configurable rules. this.HighPriorityCommonRules = [ @@ -357,7 +368,9 @@ module ts.formatting { this.NoSpaceAfterCloseBrace, this.SpaceAfterOpenBrace, this.SpaceBeforeCloseBrace, this.NewLineBeforeCloseBraceInBlockContext, this.SpaceAfterCloseBrace, this.SpaceBetweenCloseBraceAndElse, this.SpaceBetweenCloseBraceAndWhile, this.NoSpaceBetweenEmptyBraceBrackets, + this.NoSpaceBetweenFunctionKeywordAndStar, this.SpaceAfterStarInGeneratorDeclaration, this.SpaceAfterFunctionInFuncDecl, this.NewLineAfterOpenBraceInBlockContext, this.SpaceAfterGetSetInMember, + this.NoSpaceBetweenYieldKeywordAndStar, this.SpaceBetweenYieldOrYieldStarAndOperand, this.NoSpaceBetweenReturnAndSemicolon, this.SpaceAfterCertainKeywords, this.SpaceAfterLetConstInVariableDeclaration, @@ -457,8 +470,9 @@ module ts.formatting { switch (context.contextNode.kind) { case SyntaxKind.BinaryExpression: case SyntaxKind.ConditionalExpression: + case SyntaxKind.TypePredicate: return true; - + // equals in binding elements: function foo([[x, y] = [1, 2]]) case SyntaxKind.BindingElement: // equals in type X = ... @@ -574,6 +588,10 @@ module ts.formatting { return false; } + static IsFunctionDeclarationOrFunctionExpressionContext(context: FormattingContext): boolean { + return context.contextNode.kind === SyntaxKind.FunctionDeclaration || context.contextNode.kind === SyntaxKind.FunctionExpression; + } + static IsTypeScriptDeclWithBlockContext(context: FormattingContext): boolean { return Rules.NodeIsTypeScriptDeclWithBlockContext(context.contextNode); } @@ -674,7 +692,7 @@ module ts.formatting { } static IsNotFormatOnEnter(context: FormattingContext): boolean { - return context.formattingRequestKind != FormattingRequestKind.FormatOnEnter; + return context.formattingRequestKind !== FormattingRequestKind.FormatOnEnter; } static IsModuleDeclContext(context: FormattingContext): boolean { @@ -717,5 +735,9 @@ module ts.formatting { static IsVoidOpContext(context: FormattingContext): boolean { return context.currentTokenSpan.kind === SyntaxKind.VoidKeyword && context.currentTokenParent.kind === SyntaxKind.VoidExpression; } + + static IsYieldOrYieldStarWithOperand(context: FormattingContext): boolean { + return context.contextNode.kind === SyntaxKind.YieldExpression && (context.contextNode).expression !== undefined; + } } } \ No newline at end of file diff --git a/src/services/formatting/rulesMap.ts b/src/services/formatting/rulesMap.ts index 5aae6f40fcd..bffbb75c02e 100644 --- a/src/services/formatting/rulesMap.ts +++ b/src/services/formatting/rulesMap.ts @@ -1,7 +1,7 @@ /// /* @internal */ -module ts.formatting { +namespace ts.formatting { export class RulesMap { public map: RulesBucket[]; public mapRowLength: number; @@ -41,15 +41,15 @@ module ts.formatting { } private FillRule(rule: Rule, rulesBucketConstructionStateList: RulesBucketConstructionState[]): void { - let specificRule = rule.Descriptor.LeftTokenRange != Shared.TokenRange.Any && - rule.Descriptor.RightTokenRange != Shared.TokenRange.Any; + let specificRule = rule.Descriptor.LeftTokenRange !== Shared.TokenRange.Any && + rule.Descriptor.RightTokenRange !== Shared.TokenRange.Any; rule.Descriptor.LeftTokenRange.GetTokens().forEach((left) => { rule.Descriptor.RightTokenRange.GetTokens().forEach((right) => { let rulesBucketIndex = this.GetRuleBucketIndex(left, right); let rulesBucket = this.map[rulesBucketIndex]; - if (rulesBucket == undefined) { + if (rulesBucket === undefined) { rulesBucket = this.map[rulesBucketIndex] = new RulesBucket(); } @@ -124,7 +124,7 @@ module ts.formatting { public IncreaseInsertionIndex(maskPosition: RulesPosition): void { let value = (this.rulesInsertionIndexBitmap >> maskPosition) & Mask; value++; - Debug.assert((value & Mask) == value, "Adding more rules into the sub-bucket than allowed. Maximum allowed is 32 rules."); + Debug.assert((value & Mask) === value, "Adding more rules into the sub-bucket than allowed. Maximum allowed is 32 rules."); let temp = this.rulesInsertionIndexBitmap & ~(Mask << maskPosition); temp |= value << maskPosition; @@ -147,7 +147,7 @@ module ts.formatting { public AddRule(rule: Rule, specificTokens: boolean, constructionState: RulesBucketConstructionState[], rulesBucketIndex: number): void { let position: RulesPosition; - if (rule.Operation.Action == RuleAction.Ignore) { + if (rule.Operation.Action === RuleAction.Ignore) { position = specificTokens ? RulesPosition.IgnoreRulesSpecific : RulesPosition.IgnoreRulesAny; diff --git a/src/services/formatting/rulesProvider.ts b/src/services/formatting/rulesProvider.ts index 0867bcf31c0..ac1494571d1 100644 --- a/src/services/formatting/rulesProvider.ts +++ b/src/services/formatting/rulesProvider.ts @@ -1,7 +1,7 @@ /// /* @internal */ -module ts.formatting { +namespace ts.formatting { export class RulesProvider { private globalRules: Rules; private options: ts.FormatCodeOptions; @@ -25,6 +25,7 @@ module ts.formatting { } public ensureUpToDate(options: ts.FormatCodeOptions) { + // TODO: Should this be '==='? if (this.options == null || !ts.compareDataObjects(this.options, options)) { let activeRules = this.createActiveRules(options); let rulesMap = RulesMap.create(activeRules); diff --git a/src/services/formatting/smartIndenter.ts b/src/services/formatting/smartIndenter.ts index 9cd28a40a54..a82e57f050f 100644 --- a/src/services/formatting/smartIndenter.ts +++ b/src/services/formatting/smartIndenter.ts @@ -1,7 +1,7 @@ /// /* @internal */ -module ts.formatting { +namespace ts.formatting { export module SmartIndenter { const enum Value { diff --git a/src/services/formatting/tokenRange.ts b/src/services/formatting/tokenRange.ts index 712d6f3792e..3391365f328 100644 --- a/src/services/formatting/tokenRange.ts +++ b/src/services/formatting/tokenRange.ts @@ -1,7 +1,7 @@ /// /* @internal */ -module ts.formatting { +namespace ts.formatting { export module Shared { export interface ITokenAccess { GetTokens(): SyntaxKind[]; @@ -54,7 +54,7 @@ module ts.formatting { } public Contains(tokenValue: SyntaxKind): boolean { - return tokenValue == this.token; + return tokenValue === this.token; } } @@ -112,7 +112,7 @@ module ts.formatting { static AnyIncludingMultilineComments = TokenRange.FromTokens(TokenRange.Any.GetTokens().concat([SyntaxKind.MultiLineCommentTrivia])); static Keywords = TokenRange.FromRange(SyntaxKind.FirstKeyword, SyntaxKind.LastKeyword); static BinaryOperators = TokenRange.FromRange(SyntaxKind.FirstBinaryOperator, SyntaxKind.LastBinaryOperator); - static BinaryKeywordOperators = TokenRange.FromTokens([SyntaxKind.InKeyword, SyntaxKind.InstanceOfKeyword, SyntaxKind.OfKeyword]); + static BinaryKeywordOperators = TokenRange.FromTokens([SyntaxKind.InKeyword, SyntaxKind.InstanceOfKeyword, SyntaxKind.OfKeyword, SyntaxKind.IsKeyword]); static UnaryPrefixOperators = TokenRange.FromTokens([SyntaxKind.PlusPlusToken, SyntaxKind.MinusMinusToken, SyntaxKind.TildeToken, SyntaxKind.ExclamationToken]); static UnaryPrefixExpressions = TokenRange.FromTokens([SyntaxKind.NumericLiteral, SyntaxKind.Identifier, SyntaxKind.OpenParenToken, SyntaxKind.OpenBracketToken, SyntaxKind.OpenBraceToken, SyntaxKind.ThisKeyword, SyntaxKind.NewKeyword]); static UnaryPreincrementExpressions = TokenRange.FromTokens([SyntaxKind.Identifier, SyntaxKind.OpenParenToken, SyntaxKind.ThisKeyword, SyntaxKind.NewKeyword]); diff --git a/src/services/navigateTo.ts b/src/services/navigateTo.ts index aec3bdf765f..a4cc7ec2ad5 100644 --- a/src/services/navigateTo.ts +++ b/src/services/navigateTo.ts @@ -1,5 +1,5 @@ /* @internal */ -module ts.NavigateTo { +namespace ts.NavigateTo { type RawNavigateToItem = { name: string; fileName: string; matchKind: PatternMatchKind; isCaseSensitive: boolean; declaration: Declaration }; export function getNavigateToItems(program: Program, cancellationToken: CancellationTokenObject, searchValue: string, maxResultCount: number): NavigateToItem[] { diff --git a/src/services/navigationBar.ts b/src/services/navigationBar.ts index 8acdbac20c5..ead9bc519ce 100644 --- a/src/services/navigationBar.ts +++ b/src/services/navigationBar.ts @@ -1,7 +1,7 @@ /// /* @internal */ -module ts.NavigationBar { +namespace ts.NavigationBar { export function getNavigationBarItems(sourceFile: SourceFile): ts.NavigationBarItem[] { // If the source file has any child items, then it included in the tree // and takes lexical ownership of all other top-level items. diff --git a/src/services/outliningElementsCollector.ts b/src/services/outliningElementsCollector.ts index d413f611209..08b089cd75e 100644 --- a/src/services/outliningElementsCollector.ts +++ b/src/services/outliningElementsCollector.ts @@ -1,5 +1,5 @@ /* @internal */ -module ts { +namespace ts { export module OutliningElementsCollector { export function collectElements(sourceFile: SourceFile): OutliningSpan[] { let elements: OutliningSpan[] = []; diff --git a/src/services/patternMatcher.ts b/src/services/patternMatcher.ts index 88cd9fdbb0f..ea433867c46 100644 --- a/src/services/patternMatcher.ts +++ b/src/services/patternMatcher.ts @@ -1,5 +1,5 @@ /* @internal */ -module ts { +namespace ts { // Note(cyrusn): this enum is ordered from strongest match type to weakest match type. export enum PatternMatchKind { exact, @@ -686,7 +686,7 @@ module ts { if (charIsPunctuation(identifier.charCodeAt(i - 1)) || charIsPunctuation(identifier.charCodeAt(i)) || - lastIsDigit != currentIsDigit || + lastIsDigit !== currentIsDigit || hasTransitionFromLowerToUpper || hasTransitionFromUpperToLower) { @@ -757,7 +757,7 @@ module ts { // 3) HTMLDocument -> HTML, Document // // etc. - if (index != wordStart && + if (index !== wordStart && index + 1 < identifier.length) { let currentIsUpper = isUpperCaseLetter(identifier.charCodeAt(index)); let nextIsLower = isLowerCaseLetter(identifier.charCodeAt(index + 1)); diff --git a/src/services/services.ts b/src/services/services.ts index 1019c532192..18510b9a178 100644 --- a/src/services/services.ts +++ b/src/services/services.ts @@ -10,7 +10,7 @@ /// /// -module ts { +namespace ts { /** The version of the language service API */ export let servicesVersion = "0.4" @@ -167,7 +167,7 @@ module ts { } public getFullWidth(): number { - return this.end - this.getFullStart(); + return this.end - this.pos; } public getLeadingTriviaWidth(sourceFile?: SourceFile): number { @@ -735,7 +735,7 @@ module ts { public endOfFileToken: Node; public amdDependencies: { name: string; path: string }[]; - public amdModuleName: string; + public moduleName: string; public referencedFiles: FileReference[]; public syntacticDiagnostics: Diagnostic[]; @@ -743,6 +743,7 @@ module ts { public parseDiagnostics: Diagnostic[]; public bindDiagnostics: Diagnostic[]; + public isDefaultLib: boolean; public hasNoDefaultLib: boolean; public externalModuleIndicator: Node; // The first node that causes this file to be an external module public nodeCount: number; @@ -960,6 +961,7 @@ module ts { log? (s: string): void; trace? (s: string): void; error? (s: string): void; + useCaseSensitiveFileNames? (): boolean; } // @@ -971,6 +973,9 @@ module ts { getSyntacticDiagnostics(fileName: string): Diagnostic[]; getSemanticDiagnostics(fileName: string): Diagnostic[]; + + // TODO: Rename this to getProgramDiagnostics to better indicate that these are any + // diagnostics present for the program level, and not just 'options' diagnostics. getCompilerOptionsDiagnostics(): Diagnostic[]; /** @@ -1510,6 +1515,7 @@ module ts { public static typeParameterName = "type parameter name"; public static typeAliasName = "type alias name"; public static parameterName = "parameter name"; + public static docCommentTagName = "doc comment tag name"; } export const enum ClassificationType { @@ -1529,7 +1535,8 @@ module ts { moduleName = 14, typeParameterName = 15, typeAliasName = 16, - parameterName = 17 + parameterName = 17, + docCommentTagName = 18, } /// Language Service @@ -1630,12 +1637,12 @@ module ts { // at each language service public entry point, since we don't know when // set of scripts handled by the host changes. class HostCache { - private fileNameToEntry: Map; + private fileNameToEntry: FileMap; private _compilationSettings: CompilerOptions; - constructor(private host: LanguageServiceHost, private getCanonicalFileName: (fileName: string) => string) { + constructor(private host: LanguageServiceHost, getCanonicalFileName: (fileName: string) => string) { // script id => script index - this.fileNameToEntry = {}; + this.fileNameToEntry = createFileMap(getCanonicalFileName); // Initialize the list with the root file names let rootFileNames = host.getScriptFileNames(); @@ -1651,10 +1658,6 @@ module ts { return this._compilationSettings; } - private normalizeFileName(fileName: string): string { - return this.getCanonicalFileName(normalizeSlashes(fileName)); - } - private createEntry(fileName: string) { let entry: HostFileInformation; let scriptSnapshot = this.host.getScriptSnapshot(fileName); @@ -1666,15 +1669,16 @@ module ts { }; } - return this.fileNameToEntry[this.normalizeFileName(fileName)] = entry; + this.fileNameToEntry.set(fileName, entry); + return entry; } private getEntry(fileName: string): HostFileInformation { - return lookUp(this.fileNameToEntry, this.normalizeFileName(fileName)); + return this.fileNameToEntry.get(fileName); } private contains(fileName: string): boolean { - return hasProperty(this.fileNameToEntry, this.normalizeFileName(fileName)); + return this.fileNameToEntry.contains(fileName); } public getOrCreateEntry(fileName: string): HostFileInformation { @@ -1688,10 +1692,9 @@ module ts { public getRootFileNames(): string[] { let fileNames: string[] = []; - forEachKey(this.fileNameToEntry, key => { - let entry = this.getEntry(key); - if (entry) { - fileNames.push(entry.hostFileName); + this.fileNameToEntry.forEachValue(value => { + if (value) { + fileNames.push(value.hostFileName); } }); @@ -1761,26 +1764,36 @@ module ts { * This function will compile source text from 'input' argument using specified compiler options. * If not options are provided - it will use a set of default compiler options. * Extra compiler options that will unconditionally be used bu this function are: - * - separateCompilation = true + * - isolatedModules = true * - allowNonTsExtensions = true + * - noLib = true + * - noResolve = true */ - export function transpile(input: string, compilerOptions?: CompilerOptions, fileName?: string, diagnostics?: Diagnostic[]): string { + export function transpile(input: string, compilerOptions?: CompilerOptions, fileName?: string, diagnostics?: Diagnostic[], moduleName?: string): string { let options = compilerOptions ? clone(compilerOptions) : getDefaultCompilerOptions(); - options.separateCompilation = true; + options.isolatedModules = true; // Filename can be non-ts file. options.allowNonTsExtensions = true; - // Parse - var inputFileName = fileName || "module.ts"; - var sourceFile = createSourceFile(inputFileName, input, options.target); + // We are not returning a sourceFile for lib file when asked by the program, + // so pass --noLib to avoid reporting a file not found error. + options.noLib = true; - // Store syntactic diagnostics - if (diagnostics && sourceFile.parseDiagnostics) { - diagnostics.push(...sourceFile.parseDiagnostics); + // We are not doing a full typecheck, we are not resolving the whole context, + // so pass --noResolve to avoid reporting missing file errors. + options.noResolve = true; + + // Parse + let inputFileName = fileName || "module.ts"; + let sourceFile = createSourceFile(inputFileName, input, options.target); + if (moduleName) { + sourceFile.moduleName = moduleName; } + let newLine = getNewLineCharacter(options); + // Output let outputText: string; @@ -1795,14 +1808,13 @@ module ts { useCaseSensitiveFileNames: () => false, getCanonicalFileName: fileName => fileName, getCurrentDirectory: () => "", - getNewLine: () => (sys && sys.newLine) || "\r\n" + getNewLine: () => newLine }; var program = createProgram([inputFileName], options, compilerHost); - if (diagnostics) { - diagnostics.push(...program.getGlobalDiagnostics()); - } + addRange(/*to*/ diagnostics, /*from*/ program.getSyntacticDiagnostics(sourceFile)); + addRange(/*to*/ diagnostics, /*from*/ program.getOptionsDiagnostics()); // Emit program.emit(); @@ -1813,7 +1825,8 @@ module ts { } export function createLanguageServiceSourceFile(fileName: string, scriptSnapshot: IScriptSnapshot, scriptTarget: ScriptTarget, version: string, setNodeParents: boolean): SourceFile { - let sourceFile = createSourceFile(fileName, scriptSnapshot.getText(0, scriptSnapshot.getLength()), scriptTarget, setNodeParents); + let text = scriptSnapshot.getText(0, scriptSnapshot.getLength()); + let sourceFile = createSourceFile(fileName, text, scriptTarget, setNodeParents); setSourceFileFields(sourceFile, scriptSnapshot, version); // after full parsing we can use table with interned strings as name table sourceFile.nameTable = sourceFile.identifiers; @@ -1870,20 +1883,28 @@ module ts { return createLanguageServiceSourceFile(sourceFile.fileName, scriptSnapshot, sourceFile.languageVersion, version, /*setNodeParents:*/ true); } - export function createDocumentRegistry(): DocumentRegistry { + function createGetCanonicalFileName(useCaseSensitivefileNames: boolean): (fileName: string) => string { + return useCaseSensitivefileNames + ? ((fileName) => fileName) + : ((fileName) => fileName.toLowerCase()); + } + + + export function createDocumentRegistry(useCaseSensitiveFileNames?: boolean): DocumentRegistry { // Maps from compiler setting target (ES3, ES5, etc.) to all the cached documents we have // for those settings. - let buckets: Map> = {}; + let buckets: Map> = {}; + let getCanonicalFileName = createGetCanonicalFileName(!!useCaseSensitiveFileNames); function getKeyFromCompilationSettings(settings: CompilerOptions): string { return "_" + settings.target; // + "|" + settings.propagateEnumConstantoString() } - function getBucketForCompilationSettings(settings: CompilerOptions, createIfMissing: boolean): Map { + function getBucketForCompilationSettings(settings: CompilerOptions, createIfMissing: boolean): FileMap { let key = getKeyFromCompilationSettings(settings); let bucket = lookUp(buckets, key); if (!bucket && createIfMissing) { - buckets[key] = bucket = {}; + buckets[key] = bucket = createFileMap(getCanonicalFileName); } return bucket; } @@ -1893,7 +1914,7 @@ module ts { let entries = lookUp(buckets, name); let sourceFiles: { name: string; refCount: number; references: string[]; }[] = []; for (let i in entries) { - let entry = entries[i]; + let entry = entries.get(i); sourceFiles.push({ name: i, refCount: entry.languageServiceRefCount, @@ -1925,18 +1946,19 @@ module ts { acquiring: boolean): SourceFile { let bucket = getBucketForCompilationSettings(compilationSettings, /*createIfMissing*/ true); - let entry = lookUp(bucket, fileName); + let entry = bucket.get(fileName); if (!entry) { Debug.assert(acquiring, "How could we be trying to update a document that the registry doesn't have?"); // Have never seen this file with these settings. Create a new source file for it. let sourceFile = createLanguageServiceSourceFile(fileName, scriptSnapshot, compilationSettings.target, version, /*setNodeParents:*/ false); - bucket[fileName] = entry = { + entry = { sourceFile: sourceFile, languageServiceRefCount: 0, owners: [] }; + bucket.set(fileName, entry); } else { // We have an entry for this file. However, it may be for a different version of @@ -1964,12 +1986,12 @@ module ts { let bucket = getBucketForCompilationSettings(compilationSettings, false); Debug.assert(bucket !== undefined); - let entry = lookUp(bucket, fileName); + let entry = bucket.get(fileName); entry.languageServiceRefCount--; Debug.assert(entry.languageServiceRefCount >= 0); if (entry.languageServiceRefCount === 0) { - delete bucket[fileName]; + bucket.remove(fileName); } } @@ -2397,9 +2419,7 @@ module ts { } } - function getCanonicalFileName(fileName: string) { - return useCaseSensitivefileNames ? fileName : fileName.toLowerCase(); - } + let getCanonicalFileName = createGetCanonicalFileName(useCaseSensitivefileNames); function getValidSourceFile(fileName: string): SourceFile { fileName = normalizeSlashes(fileName); @@ -2475,6 +2495,10 @@ module ts { } } + // hostCache is captured in the closure for 'getOrCreateSourceFile' but it should not be used past this point. + // It needs to be cleared to allow all collected snapshots to be released + hostCache = undefined; + program = newProgram; // Make sure all the nodes in the program are both bound, and have their parent @@ -2483,6 +2507,7 @@ module ts { return; function getOrCreateSourceFile(fileName: string): SourceFile { + Debug.assert(hostCache !== undefined); // The program is asking for this file, check first if the host can locate it. // If the host can not locate the file, then it does not exist. return undefined // to the program to allow reporting of errors for missing files. @@ -2768,7 +2793,7 @@ module ts { function getCompilerOptionsDiagnostics() { synchronizeHostData(); - return program.getGlobalDiagnostics(); + return program.getOptionsDiagnostics().concat(program.getGlobalDiagnostics()); } /// Completion @@ -2832,6 +2857,7 @@ module ts { let typeChecker = program.getTypeChecker(); let syntacticStart = new Date().getTime(); let sourceFile = getValidSourceFile(fileName); + let isJavaScriptFile = isJavaScript(fileName); let start = new Date().getTime(); let currentToken = getTokenAtPosition(sourceFile, position); @@ -2932,13 +2958,29 @@ module ts { } let type = typeChecker.getTypeAtLocation(node); + addTypeProperties(type); + } + + function addTypeProperties(type: Type) { if (type) { // Filter private properties - forEach(type.getApparentProperties(), symbol => { + for (let symbol of type.getApparentProperties()) { if (typeChecker.isValidPropertyAccess((node.parent), symbol.name)) { symbols.push(symbol); } - }); + } + + if (isJavaScriptFile && type.flags & TypeFlags.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. + let unionType = type; + for (let elementType of unionType.types) { + addTypeProperties(elementType); + } + } } } @@ -3125,16 +3167,20 @@ module ts { if (previousToken.kind === SyntaxKind.StringLiteral || previousToken.kind === SyntaxKind.RegularExpressionLiteral || isTemplateLiteralKind(previousToken.kind)) { - // The position has to be either: 1. entirely within the token text, or - // 2. at the end position of an unterminated token. let start = previousToken.getStart(); let end = previousToken.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 < position && position < end) { return true; } - else if (position === end) { - return !!(previousToken).isUnterminated; + + if (position === end) { + return !!(previousToken).isUnterminated || + previousToken.kind === SyntaxKind.RegularExpressionLiteral; } } @@ -4139,7 +4185,7 @@ module ts { var result: DefinitionInfo[] = []; forEach((type).types, t => { if (t.symbol) { - result.push(...getDefinitionFromSymbol(t.symbol, node)); + addRange(/*to*/ result, /*from*/ getDefinitionFromSymbol(t.symbol, node)); } }); return result; @@ -5762,7 +5808,8 @@ module ts { node = node.parent; } - return node.parent.kind === SyntaxKind.TypeReference || node.parent.kind === SyntaxKind.ExpressionWithTypeArguments; + return node.parent.kind === SyntaxKind.TypeReference || + (node.parent.kind === SyntaxKind.ExpressionWithTypeArguments && !isExpressionWithTypeArgumentsInClassExtendsClause(node.parent)); } function isNamespaceReference(node: Node): boolean { @@ -5943,6 +5990,7 @@ module ts { let typeChecker = program.getTypeChecker(); let result: number[] = []; + let classifiableNames = program.getClassifiableNames(); processNode(sourceFile); return { spans: result, endOfLineState: EndOfLineState.None }; @@ -5955,6 +6003,9 @@ module ts { function classifySymbol(symbol: Symbol, meaningAtPosition: SemanticMeaning): ClassificationType { let flags = symbol.getFlags(); + if ((flags & SymbolFlags.Classifiable) === SymbolFlags.None) { + return; + } if (flags & SymbolFlags.Class) { return ClassificationType.className; @@ -5990,20 +6041,28 @@ module ts { */ function hasValueSideModule(symbol: Symbol): boolean { return forEach(symbol.declarations, declaration => { - return declaration.kind === SyntaxKind.ModuleDeclaration && getModuleInstanceState(declaration) == ModuleInstanceState.Instantiated; + return declaration.kind === SyntaxKind.ModuleDeclaration && + getModuleInstanceState(declaration) === ModuleInstanceState.Instantiated; }); } } function processNode(node: Node) { // Only walk into nodes that intersect the requested span. - if (node && textSpanIntersectsWith(span, node.getStart(), node.getWidth())) { - if (node.kind === SyntaxKind.Identifier && node.getWidth() > 0) { - let symbol = typeChecker.getSymbolAtLocation(node); - if (symbol) { - let type = classifySymbol(symbol, getMeaningFromLocation(node)); - if (type) { - pushClassification(node.getStart(), node.getWidth(), type); + if (node && textSpanIntersectsWith(span, node.getFullStart(), node.getFullWidth())) { + if (node.kind === SyntaxKind.Identifier && !nodeIsMissing(node)) { + let identifier = node; + + // 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[identifier.text]) { + let symbol = typeChecker.getSymbolAtLocation(node); + if (symbol) { + let type = classifySymbol(symbol, getMeaningFromLocation(node)); + if (type) { + pushClassification(node.getStart(), node.getWidth(), type); + } } } } @@ -6031,6 +6090,7 @@ module ts { case ClassificationType.typeParameterName: return ClassificationTypeNames.typeParameterName; case ClassificationType.typeAliasName: return ClassificationTypeNames.typeAliasName; case ClassificationType.parameterName: return ClassificationTypeNames.parameterName; + case ClassificationType.docCommentTagName: return ClassificationTypeNames.docCommentTagName; } } @@ -6055,6 +6115,8 @@ module ts { function getEncodedSyntacticClassifications(fileName: string, span: TextSpan): Classifications { // doesn't use compiler - no need to synchronize with host let sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); + let spanStart = span.start; + let spanLength = span.length; // Make a scanner we can get trivia from. let triviaScanner = createScanner(ScriptTarget.Latest, /*skipTrivia:*/ false, sourceFile.text); @@ -6071,53 +6133,145 @@ module ts { result.push(type); } - function classifyLeadingTrivia(token: Node): void { - let tokenStart = skipTrivia(sourceFile.text, token.pos, /*stopAfterLineBreak:*/ false); - if (tokenStart === token.pos) { - return; - } - - // token has trivia. Classify them appropriately. + function classifyLeadingTriviaAndGetTokenStart(token: Node): number { triviaScanner.setTextPos(token.pos); while (true) { let start = triviaScanner.getTextPos(); + // only bother scanning if we have something that could be trivia. + if (!couldStartTrivia(sourceFile.text, start)) { + return start; + } + let kind = triviaScanner.scan(); let end = triviaScanner.getTextPos(); let width = end - start; // The moment we get something that isn't trivia, then stop processing. if (!isTrivia(kind)) { - return; + return start; + } + + // Don't bother with newlines/whitespace. + if (kind === SyntaxKind.NewLineTrivia || kind === SyntaxKind.WhitespaceTrivia) { + continue; } // Only bother with the trivia if it at least intersects the span of interest. - if (textSpanIntersectsWith(span, start, width)) { - if (isComment(kind)) { - // Simple comment. Just add as is. + if (isComment(kind)) { + classifyComment(token, kind, start, width); + + // Classifying a comment might cause us to reuse the trivia scanner + // (because of jsdoc comments). So after we classify the comment make + // sure we set the scanner position back to where it needs to be. + triviaScanner.setTextPos(end); + continue; + } + + if (kind === SyntaxKind.ConflictMarkerTrivia) { + let text = sourceFile.text; + let ch = text.charCodeAt(start); + + // for the <<<<<<< and >>>>>>> markers, we just add them in as comments + // in the classification stream. + if (ch === CharacterCodes.lessThan || ch === CharacterCodes.greaterThan) { pushClassification(start, width, ClassificationType.comment); continue; } - if (kind === SyntaxKind.ConflictMarkerTrivia) { - let text = sourceFile.text; - let ch = text.charCodeAt(start); - - // for the <<<<<<< and >>>>>>> markers, we just add them in as comments - // in the classification stream. - if (ch === CharacterCodes.lessThan || ch === CharacterCodes.greaterThan) { - pushClassification(start, width, ClassificationType.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. - Debug.assert(ch === CharacterCodes.equals); - classifyDisabledMergeCode(text, start, end); - } + // for the ======== add a comment for the first line, and then lex all + // subsequent lines up until the end of the conflict marker. + Debug.assert(ch === CharacterCodes.equals); + classifyDisabledMergeCode(text, start, end); } } } + function classifyComment(token: Node, kind: SyntaxKind, start: number, width: number) { + if (kind === SyntaxKind.MultiLineCommentTrivia) { + // See if this is a doc comment. If so, we'll classify certain portions of it + // specially. + let docCommentAndDiagnostics = parseIsolatedJSDocComment(sourceFile.text, start, width); + if (docCommentAndDiagnostics && docCommentAndDiagnostics.jsDocComment) { + docCommentAndDiagnostics.jsDocComment.parent = token; + classifyJSDocComment(docCommentAndDiagnostics.jsDocComment); + return; + } + } + + // Simple comment. Just add as is. + pushCommentRange(start, width); + } + + function pushCommentRange(start: number, width: number) { + pushClassification(start, width, ClassificationType.comment); + } + + function classifyJSDocComment(docComment: JSDocComment) { + let pos = docComment.pos; + + for (let tag of docComment.tags) { + // As we walk through each tag, classify the portion of text from the end of + // the last tag (or the start of the entire doc comment) as 'comment'. + if (tag.pos !== pos) { + pushCommentRange(pos, tag.pos - pos); + } + + pushClassification(tag.atToken.pos, tag.atToken.end - tag.atToken.pos, ClassificationType.punctuation); + pushClassification(tag.tagName.pos, tag.tagName.end - tag.tagName.pos, ClassificationType.docCommentTagName); + + pos = tag.tagName.end; + + switch (tag.kind) { + case SyntaxKind.JSDocParameterTag: + processJSDocParameterTag(tag); + break; + case SyntaxKind.JSDocTemplateTag: + processJSDocTemplateTag(tag); + break; + case SyntaxKind.JSDocTypeTag: + processElement((tag).typeExpression); + break; + case SyntaxKind.JSDocReturnTag: + processElement((tag).typeExpression); + break; + } + + pos = tag.end; + } + + if (pos !== docComment.end) { + pushCommentRange(pos, docComment.end - pos); + } + + 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.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, ClassificationType.parameterName); + pos = tag.postParameterName.end; + } + } + } + + function processJSDocTemplateTag(tag: JSDocTemplateTag) { + for (let child of tag.getChildren()) { + processElement(child); + } + } + function classifyDisabledMergeCode(text: string, start: number, end: number) { // Classify the line that the ======= marker is on as a comment. Then just lex // all further tokens and add them to the result. @@ -6146,12 +6300,18 @@ module ts { } function classifyToken(token: Node): void { - classifyLeadingTrivia(token); + if (nodeIsMissing(token)) { + return; + } - if (token.getWidth() > 0) { + let tokenStart = classifyLeadingTriviaAndGetTokenStart(token); + + let tokenWidth = token.end - tokenStart; + Debug.assert(tokenWidth >= 0); + if (tokenWidth > 0) { let type = classifyTokenType(token.kind, token); if (type) { - pushClassification(token.getStart(), token.getWidth(), type); + pushClassification(tokenStart, tokenWidth, type); } } } @@ -6251,10 +6411,15 @@ module ts { } function processElement(element: Node) { + if (!element) { + return; + } + // Ignore nodes that don't intersect the original span to classify. - if (textSpanIntersectsWith(span, element.getFullStart(), element.getFullWidth())) { - let children = element.getChildren(); - for (let child of children) { + if (decodedTextSpanIntersectsWith(spanStart, spanLength, element.pos, element.getFullWidth())) { + let children = element.getChildren(sourceFile); + for (let i = 0, n = children.length; i < n; i++) { + let child = children[i]; if (isToken(child)) { classifyToken(child); } diff --git a/src/services/shims.ts b/src/services/shims.ts index 27c70ddc878..2e8b3eb774d 100644 --- a/src/services/shims.ts +++ b/src/services/shims.ts @@ -19,7 +19,7 @@ var debugObjectHost = (this); /* @internal */ -module ts { +namespace ts { export interface ScriptSnapshotShim { /** Gets a portion of the script snapshot specified by [start, end). */ getText(start: number, end: number): string; @@ -56,6 +56,7 @@ module ts { getDefaultLibFileName(options: string): string; getNewLine?(): string; getProjectVersion?(): string; + useCaseSensitiveFileNames?(): boolean; } /** Public interface of the the of a config service shim instance.*/ @@ -233,6 +234,7 @@ module ts { public getChangeRange(oldSnapshot: IScriptSnapshot): TextChangeRange { var oldSnapshotShim = oldSnapshot; var encoded = this.scriptSnapshotShim.getChangeRange(oldSnapshotShim.scriptSnapshotShim); + // TODO: should this be '==='? if (encoded == null) { return null; } @@ -245,16 +247,22 @@ module ts { export class LanguageServiceShimHostAdapter implements LanguageServiceHost { private files: string[]; + private loggingEnabled = false; + private tracingEnabled = false; constructor(private shimHost: LanguageServiceShimHost) { } public log(s: string): void { - this.shimHost.log(s); + if (this.loggingEnabled) { + this.shimHost.log(s); + } } public trace(s: string): void { - this.shimHost.trace(s); + if (this.tracingEnabled) { + this.shimHost.trace(s); + } } public error(s: string): void { @@ -270,8 +278,13 @@ module ts { return this.shimHost.getProjectVersion(); } + public useCaseSensitiveFileNames(): boolean { + return this.shimHost.useCaseSensitiveFileNames ? this.shimHost.useCaseSensitiveFileNames() : false; + } + public getCompilationSettings(): CompilerOptions { var settingsJson = this.shimHost.getCompilationSettings(); + // TODO: should this be '==='? if (settingsJson == null || settingsJson == "") { throw Error("LanguageServiceShimHostAdapter.getCompilationSettings: empty compilationSettings"); return null; @@ -344,15 +357,15 @@ module ts { } } - function simpleForwardCall(logger: Logger, actionDescription: string, action: () => any, noPerfLogging: boolean): any { - if (!noPerfLogging) { + function simpleForwardCall(logger: Logger, actionDescription: string, action: () => any, logPerformance: boolean): any { + if (logPerformance) { logger.log(actionDescription); var start = Date.now(); } var result = action(); - if (!noPerfLogging) { + if (logPerformance) { var end = Date.now(); logger.log(actionDescription + " completed in " + (end - start) + " msec"); if (typeof (result) === "string") { @@ -367,9 +380,9 @@ module ts { return result; } - function forwardJSONCall(logger: Logger, actionDescription: string, action: () => any, noPerfLogging: boolean): string { + function forwardJSONCall(logger: Logger, actionDescription: string, action: () => any, logPerformance: boolean): string { try { - var result = simpleForwardCall(logger, actionDescription, action, noPerfLogging); + var result = simpleForwardCall(logger, actionDescription, action, logPerformance); return JSON.stringify({ result: result }); } catch (err) { @@ -408,6 +421,7 @@ module ts { class LanguageServiceShimObject extends ShimBase implements LanguageServiceShim { private logger: Logger; + private logPerformance = false; constructor(factory: ShimFactory, private host: LanguageServiceShimHost, @@ -417,7 +431,7 @@ module ts { } public forwardJSONCall(actionDescription: string, action: () => any): string { - return forwardJSONCall(this.logger, actionDescription, action, /*noPerfLogging:*/ false); + return forwardJSONCall(this.logger, actionDescription, action, this.logPerformance); } /// DISPOSE @@ -806,6 +820,7 @@ module ts { class ClassifierShimObject extends ShimBase implements ClassifierShim { public classifier: Classifier; + private logPerformance = false; constructor(factory: ShimFactory, private logger: Logger) { super(factory); @@ -815,7 +830,7 @@ module ts { public getEncodedLexicalClassifications(text: string, lexState: EndOfLineState, syntacticClassifierAbsent?: boolean): string { return forwardJSONCall(this.logger, "getEncodedLexicalClassifications", () => convertClassifications(this.classifier.getEncodedLexicalClassifications(text, lexState, syntacticClassifierAbsent)), - /*noPerfLogging:*/ true); + this.logPerformance); } /// COLORIZATION @@ -833,13 +848,14 @@ module ts { } class CoreServicesShimObject extends ShimBase implements CoreServicesShim { + private logPerformance = false; constructor(factory: ShimFactory, public logger: Logger, private host: CoreServicesShimHostAdapter) { super(factory); } private forwardJSONCall(actionDescription: string, action: () => any): any { - return forwardJSONCall(this.logger, actionDescription, action, /*noPerfLogging:*/ false); + return forwardJSONCall(this.logger, actionDescription, action, this.logPerformance); } public getPreProcessedFileInfo(fileName: string, sourceTextSnapshot: IScriptSnapshot): string { @@ -909,7 +925,7 @@ module ts { export class TypeScriptServicesFactory implements ShimFactory { private _shims: Shim[] = []; - private documentRegistry: DocumentRegistry = createDocumentRegistry(); + private documentRegistry: DocumentRegistry; /* * Returns script API version. @@ -920,6 +936,9 @@ module ts { public createLanguageServiceShim(host: LanguageServiceShimHost): LanguageServiceShim { try { + if (this.documentRegistry === undefined) { + this.documentRegistry = createDocumentRegistry(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames()); + } var hostAdapter = new LanguageServiceShimHostAdapter(host); var languageService = createLanguageService(hostAdapter, this.documentRegistry); return new LanguageServiceShimObject(this, host, languageService); @@ -989,4 +1008,4 @@ module TypeScript.Services { } /* @internal */ -let toolsVersion = "1.4"; +let toolsVersion = "1.5"; diff --git a/src/services/signatureHelp.ts b/src/services/signatureHelp.ts index 77aba4c85c1..fce4e2c3025 100644 --- a/src/services/signatureHelp.ts +++ b/src/services/signatureHelp.ts @@ -1,6 +1,6 @@ /// /* @internal */ -module ts.SignatureHelp { +namespace ts.SignatureHelp { // A partially written generic type expression is not guaranteed to have the correct syntax tree. the expression could be parsed as less than/greater than expression or a comma expression // or some other combination depending on what the user has typed so far. For the purposes of signature help we need to consider any location after "<" as a possible generic type reference. diff --git a/src/services/utilities.ts b/src/services/utilities.ts index da0a0aa96c1..73b88a3df26 100644 --- a/src/services/utilities.ts +++ b/src/services/utilities.ts @@ -1,6 +1,6 @@ // These utilities are common to multiple language service features. /* @internal */ -module ts { +namespace ts { export interface ListItemInfo { listItemIndex: number; list: Node; @@ -502,7 +502,7 @@ module ts { // Display-part writer helpers /* @internal */ -module ts { +namespace ts { export function isFirstDeclarationOfSymbolParameter(symbol: Symbol) { return symbol.declarations && symbol.declarations.length > 0 && symbol.declarations[0].kind === SyntaxKind.Parameter; } diff --git a/tests/baselines/reference/APISample_linter.js b/tests/baselines/reference/APISample_linter.js index cd2df23ffbf..9b2675535f2 100644 --- a/tests/baselines/reference/APISample_linter.js +++ b/tests/baselines/reference/APISample_linter.js @@ -75,26 +75,26 @@ function delint(sourceFile) { delintNode(sourceFile); function delintNode(node) { switch (node.kind) { - case 187 /* ForStatement */: - case 188 /* ForInStatement */: - case 186 /* WhileStatement */: - case 185 /* DoStatement */: - if (node.statement.kind !== 180 /* Block */) { + case 189 /* ForStatement */: + case 190 /* ForInStatement */: + case 188 /* WhileStatement */: + case 187 /* DoStatement */: + if (node.statement.kind !== 182 /* Block */) { report(node, "A looping statement's contents should be wrapped in a block body."); } break; - case 184 /* IfStatement */: + case 186 /* IfStatement */: var ifStatement = node; - if (ifStatement.thenStatement.kind !== 180 /* Block */) { + if (ifStatement.thenStatement.kind !== 182 /* Block */) { report(ifStatement.thenStatement, "An if statement's contents should be wrapped in a block body."); } if (ifStatement.elseStatement && - ifStatement.elseStatement.kind !== 180 /* Block */ && - ifStatement.elseStatement.kind !== 184 /* IfStatement */) { + ifStatement.elseStatement.kind !== 182 /* Block */ && + ifStatement.elseStatement.kind !== 186 /* IfStatement */) { report(ifStatement.elseStatement, "An else statement's contents should be wrapped in a block body."); } break; - case 170 /* BinaryExpression */: + case 172 /* BinaryExpression */: var op = node.operatorToken.kind; if (op === 28 /* EqualsEqualsToken */ || op == 29 /* ExclamationEqualsToken */) { report(node, "Use '===' and '!=='."); diff --git a/tests/baselines/reference/ArrowFunction3.errors.txt b/tests/baselines/reference/ArrowFunction3.errors.txt index b931fcb1cd8..aa5d1bfb725 100644 --- a/tests/baselines/reference/ArrowFunction3.errors.txt +++ b/tests/baselines/reference/ArrowFunction3.errors.txt @@ -1,11 +1,8 @@ -tests/cases/conformance/parser/ecmascript5/ErrorRecovery/ArrowFunctions/ArrowFunction3.ts(1,13): error TS2355: A function whose declared type is neither 'void' nor 'any' must return a value or consist of a single 'throw' statement. tests/cases/conformance/parser/ecmascript5/ErrorRecovery/ArrowFunctions/ArrowFunction3.ts(1,14): error TS1110: Type expected. -==== tests/cases/conformance/parser/ecmascript5/ErrorRecovery/ArrowFunctions/ArrowFunction3.ts (2 errors) ==== +==== tests/cases/conformance/parser/ecmascript5/ErrorRecovery/ArrowFunctions/ArrowFunction3.ts (1 errors) ==== var v = (a): => { - -!!! error TS2355: A function whose declared type is neither 'void' nor 'any' must return a value or consist of a single 'throw' statement. ~~ !!! error TS1110: Type expected. diff --git a/tests/baselines/reference/ES5For-of17.js b/tests/baselines/reference/ES5For-of17.js index 50064d82932..fb3a02fd0e9 100644 --- a/tests/baselines/reference/ES5For-of17.js +++ b/tests/baselines/reference/ES5For-of17.js @@ -11,7 +11,7 @@ for (let v of []) { for (var _i = 0, _a = []; _i < _a.length; _i++) { var v = _a[_i]; v; - for (var _b = 0, _c = [v]; _b < _c.length; _b++) { + for (var _b = 0, _c = [v_1]; _b < _c.length; _b++) { var v_1 = _c[_b]; var x = v_1; v_1++; diff --git a/tests/baselines/reference/ES5For-of20.js b/tests/baselines/reference/ES5For-of20.js index c6376ab05d7..d21ab73f8b5 100644 --- a/tests/baselines/reference/ES5For-of20.js +++ b/tests/baselines/reference/ES5For-of20.js @@ -10,7 +10,7 @@ for (let v of []) { for (var _i = 0, _a = []; _i < _a.length; _i++) { var v = _a[_i]; var v_1; - for (var _b = 0, _c = [v]; _b < _c.length; _b++) { + for (var _b = 0, _c = [v_2]; _b < _c.length; _b++) { var v_2 = _c[_b]; var v_3; } diff --git a/tests/baselines/reference/ExportClassWithAccessibleTypesInTypeParameterConstraintsClassHeritageListMemberTypeAnnotations.js b/tests/baselines/reference/ExportClassWithAccessibleTypesInTypeParameterConstraintsClassHeritageListMemberTypeAnnotations.js index ec30d5b4dc7..3e48462062d 100644 --- a/tests/baselines/reference/ExportClassWithAccessibleTypesInTypeParameterConstraintsClassHeritageListMemberTypeAnnotations.js +++ b/tests/baselines/reference/ExportClassWithAccessibleTypesInTypeParameterConstraintsClassHeritageListMemberTypeAnnotations.js @@ -24,8 +24,7 @@ module A { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var A; (function (A) { diff --git a/tests/baselines/reference/ExportClassWithInaccessibleTypeInTypeParameterConstraint.js b/tests/baselines/reference/ExportClassWithInaccessibleTypeInTypeParameterConstraint.js index 4d296bf9ea5..a1386033e9f 100644 --- a/tests/baselines/reference/ExportClassWithInaccessibleTypeInTypeParameterConstraint.js +++ b/tests/baselines/reference/ExportClassWithInaccessibleTypeInTypeParameterConstraint.js @@ -28,8 +28,7 @@ module A { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var A; (function (A) { diff --git a/tests/baselines/reference/FunctionDeclaration10_es6.errors.txt b/tests/baselines/reference/FunctionDeclaration10_es6.errors.txt index 8c6b09c82d6..35edf48564a 100644 --- a/tests/baselines/reference/FunctionDeclaration10_es6.errors.txt +++ b/tests/baselines/reference/FunctionDeclaration10_es6.errors.txt @@ -1,8 +1,8 @@ -tests/cases/conformance/es6/functionDeclarations/FunctionDeclaration10_es6.ts(1,10): error TS9001: Generators are not currently supported. +tests/cases/conformance/es6/functionDeclarations/FunctionDeclaration10_es6.ts(1,10): error TS1220: Generators are only available when targeting ECMAScript 6 or higher. ==== tests/cases/conformance/es6/functionDeclarations/FunctionDeclaration10_es6.ts (1 errors) ==== function * foo(a = yield => yield) { ~ -!!! error TS9001: Generators are not currently supported. +!!! error TS1220: Generators are only available when targeting ECMAScript 6 or higher. } \ No newline at end of file diff --git a/tests/baselines/reference/FunctionDeclaration11_es6.errors.txt b/tests/baselines/reference/FunctionDeclaration11_es6.errors.txt index 1dd8c3f6a1b..e24f702213c 100644 --- a/tests/baselines/reference/FunctionDeclaration11_es6.errors.txt +++ b/tests/baselines/reference/FunctionDeclaration11_es6.errors.txt @@ -1,8 +1,8 @@ -tests/cases/conformance/es6/functionDeclarations/FunctionDeclaration11_es6.ts(1,10): error TS9001: Generators are not currently supported. +tests/cases/conformance/es6/functionDeclarations/FunctionDeclaration11_es6.ts(1,10): error TS1220: Generators are only available when targeting ECMAScript 6 or higher. ==== tests/cases/conformance/es6/functionDeclarations/FunctionDeclaration11_es6.ts (1 errors) ==== function * yield() { ~ -!!! error TS9001: Generators are not currently supported. +!!! error TS1220: Generators are only available when targeting ECMAScript 6 or higher. } \ No newline at end of file diff --git a/tests/baselines/reference/FunctionDeclaration13_es6.errors.txt b/tests/baselines/reference/FunctionDeclaration13_es6.errors.txt index a46097e8a1a..2b090f4a733 100644 --- a/tests/baselines/reference/FunctionDeclaration13_es6.errors.txt +++ b/tests/baselines/reference/FunctionDeclaration13_es6.errors.txt @@ -1,11 +1,11 @@ -tests/cases/conformance/es6/functionDeclarations/FunctionDeclaration13_es6.ts(1,10): error TS9001: Generators are not currently supported. +tests/cases/conformance/es6/functionDeclarations/FunctionDeclaration13_es6.ts(1,10): error TS1220: Generators are only available when targeting ECMAScript 6 or higher. tests/cases/conformance/es6/functionDeclarations/FunctionDeclaration13_es6.ts(3,11): error TS2304: Cannot find name 'yield'. ==== tests/cases/conformance/es6/functionDeclarations/FunctionDeclaration13_es6.ts (2 errors) ==== function * foo() { ~ -!!! error TS9001: Generators are not currently supported. +!!! error TS1220: Generators are only available when targeting ECMAScript 6 or higher. // Legal to use 'yield' in a type context. var v: yield; ~~~~~ diff --git a/tests/baselines/reference/FunctionDeclaration1_es6.errors.txt b/tests/baselines/reference/FunctionDeclaration1_es6.errors.txt index 71b09983939..52bdfbd1afe 100644 --- a/tests/baselines/reference/FunctionDeclaration1_es6.errors.txt +++ b/tests/baselines/reference/FunctionDeclaration1_es6.errors.txt @@ -1,8 +1,8 @@ -tests/cases/conformance/es6/functionDeclarations/FunctionDeclaration1_es6.ts(1,10): error TS9001: Generators are not currently supported. +tests/cases/conformance/es6/functionDeclarations/FunctionDeclaration1_es6.ts(1,10): error TS1220: Generators are only available when targeting ECMAScript 6 or higher. ==== tests/cases/conformance/es6/functionDeclarations/FunctionDeclaration1_es6.ts (1 errors) ==== function * foo() { ~ -!!! error TS9001: Generators are not currently supported. +!!! error TS1220: Generators are only available when targeting ECMAScript 6 or higher. } \ No newline at end of file diff --git a/tests/baselines/reference/FunctionDeclaration6_es6.errors.txt b/tests/baselines/reference/FunctionDeclaration6_es6.errors.txt index b5ea3f494a7..9f696e71084 100644 --- a/tests/baselines/reference/FunctionDeclaration6_es6.errors.txt +++ b/tests/baselines/reference/FunctionDeclaration6_es6.errors.txt @@ -1,11 +1,11 @@ -tests/cases/conformance/es6/functionDeclarations/FunctionDeclaration6_es6.ts(1,9): error TS9001: Generators are not currently supported. +tests/cases/conformance/es6/functionDeclarations/FunctionDeclaration6_es6.ts(1,9): error TS1220: Generators are only available when targeting ECMAScript 6 or higher. tests/cases/conformance/es6/functionDeclarations/FunctionDeclaration6_es6.ts(1,18): error TS2304: Cannot find name 'yield'. ==== tests/cases/conformance/es6/functionDeclarations/FunctionDeclaration6_es6.ts (2 errors) ==== function*foo(a = yield) { ~ -!!! error TS9001: Generators are not currently supported. +!!! error TS1220: Generators are only available when targeting ECMAScript 6 or higher. ~~~~~ !!! error TS2304: Cannot find name 'yield'. } \ No newline at end of file diff --git a/tests/baselines/reference/FunctionDeclaration7_es6.errors.txt b/tests/baselines/reference/FunctionDeclaration7_es6.errors.txt index f129d3fa30b..91fab36ed31 100644 --- a/tests/baselines/reference/FunctionDeclaration7_es6.errors.txt +++ b/tests/baselines/reference/FunctionDeclaration7_es6.errors.txt @@ -1,16 +1,16 @@ -tests/cases/conformance/es6/functionDeclarations/FunctionDeclaration7_es6.ts(1,9): error TS9001: Generators are not currently supported. -tests/cases/conformance/es6/functionDeclarations/FunctionDeclaration7_es6.ts(3,11): error TS9001: Generators are not currently supported. +tests/cases/conformance/es6/functionDeclarations/FunctionDeclaration7_es6.ts(1,9): error TS1220: Generators are only available when targeting ECMAScript 6 or higher. +tests/cases/conformance/es6/functionDeclarations/FunctionDeclaration7_es6.ts(3,11): error TS1220: Generators are only available when targeting ECMAScript 6 or higher. tests/cases/conformance/es6/functionDeclarations/FunctionDeclaration7_es6.ts(3,20): error TS2304: Cannot find name 'yield'. ==== tests/cases/conformance/es6/functionDeclarations/FunctionDeclaration7_es6.ts (3 errors) ==== function*bar() { ~ -!!! error TS9001: Generators are not currently supported. +!!! error TS1220: Generators are only available when targeting ECMAScript 6 or higher. // 'yield' here is an identifier, and not a yield expression. function*foo(a = yield) { ~ -!!! error TS9001: Generators are not currently supported. +!!! error TS1220: Generators are only available when targeting ECMAScript 6 or higher. ~~~~~ !!! error TS2304: Cannot find name 'yield'. } diff --git a/tests/baselines/reference/FunctionDeclaration9_es6.errors.txt b/tests/baselines/reference/FunctionDeclaration9_es6.errors.txt index 152b1ffc7cc..e4222409a66 100644 --- a/tests/baselines/reference/FunctionDeclaration9_es6.errors.txt +++ b/tests/baselines/reference/FunctionDeclaration9_es6.errors.txt @@ -1,12 +1,9 @@ -tests/cases/conformance/es6/functionDeclarations/FunctionDeclaration9_es6.ts(1,10): error TS9001: Generators are not currently supported. -tests/cases/conformance/es6/functionDeclarations/FunctionDeclaration9_es6.ts(2,14): error TS9000: 'yield' expressions are not currently supported. +tests/cases/conformance/es6/functionDeclarations/FunctionDeclaration9_es6.ts(1,10): error TS1220: Generators are only available when targeting ECMAScript 6 or higher. -==== tests/cases/conformance/es6/functionDeclarations/FunctionDeclaration9_es6.ts (2 errors) ==== +==== tests/cases/conformance/es6/functionDeclarations/FunctionDeclaration9_es6.ts (1 errors) ==== function * foo() { ~ -!!! error TS9001: Generators are not currently supported. +!!! error TS1220: Generators are only available when targeting ECMAScript 6 or higher. var v = { [yield]: foo } - ~~~~~ -!!! error TS9000: 'yield' expressions are not currently supported. } \ No newline at end of file diff --git a/tests/baselines/reference/FunctionExpression1_es6.errors.txt b/tests/baselines/reference/FunctionExpression1_es6.errors.txt index 979178fd4b7..cb2ebd7245e 100644 --- a/tests/baselines/reference/FunctionExpression1_es6.errors.txt +++ b/tests/baselines/reference/FunctionExpression1_es6.errors.txt @@ -1,7 +1,7 @@ -tests/cases/conformance/es6/functionExpressions/FunctionExpression1_es6.ts(1,18): error TS9001: Generators are not currently supported. +tests/cases/conformance/es6/functionExpressions/FunctionExpression1_es6.ts(1,18): error TS1220: Generators are only available when targeting ECMAScript 6 or higher. ==== tests/cases/conformance/es6/functionExpressions/FunctionExpression1_es6.ts (1 errors) ==== var v = function * () { } ~ -!!! error TS9001: Generators are not currently supported. \ No newline at end of file +!!! error TS1220: Generators are only available when targeting ECMAScript 6 or higher. \ No newline at end of file diff --git a/tests/baselines/reference/FunctionExpression2_es6.errors.txt b/tests/baselines/reference/FunctionExpression2_es6.errors.txt index ab27947d7c5..d5350b5fdec 100644 --- a/tests/baselines/reference/FunctionExpression2_es6.errors.txt +++ b/tests/baselines/reference/FunctionExpression2_es6.errors.txt @@ -1,7 +1,7 @@ -tests/cases/conformance/es6/functionExpressions/FunctionExpression2_es6.ts(1,18): error TS9001: Generators are not currently supported. +tests/cases/conformance/es6/functionExpressions/FunctionExpression2_es6.ts(1,18): error TS1220: Generators are only available when targeting ECMAScript 6 or higher. ==== tests/cases/conformance/es6/functionExpressions/FunctionExpression2_es6.ts (1 errors) ==== var v = function * foo() { } ~ -!!! error TS9001: Generators are not currently supported. \ No newline at end of file +!!! error TS1220: Generators are only available when targeting ECMAScript 6 or higher. \ No newline at end of file diff --git a/tests/baselines/reference/FunctionPropertyAssignments1_es6.errors.txt b/tests/baselines/reference/FunctionPropertyAssignments1_es6.errors.txt index bbabbc97463..a2aa32a9dd1 100644 --- a/tests/baselines/reference/FunctionPropertyAssignments1_es6.errors.txt +++ b/tests/baselines/reference/FunctionPropertyAssignments1_es6.errors.txt @@ -1,7 +1,7 @@ -tests/cases/conformance/es6/functionPropertyAssignments/FunctionPropertyAssignments1_es6.ts(1,11): error TS9001: Generators are not currently supported. +tests/cases/conformance/es6/functionPropertyAssignments/FunctionPropertyAssignments1_es6.ts(1,11): error TS1220: Generators are only available when targeting ECMAScript 6 or higher. ==== tests/cases/conformance/es6/functionPropertyAssignments/FunctionPropertyAssignments1_es6.ts (1 errors) ==== var v = { *foo() { } } ~ -!!! error TS9001: Generators are not currently supported. \ No newline at end of file +!!! error TS1220: Generators are only available when targeting ECMAScript 6 or higher. \ No newline at end of file diff --git a/tests/baselines/reference/FunctionPropertyAssignments5_es6.errors.txt b/tests/baselines/reference/FunctionPropertyAssignments5_es6.errors.txt index 596764e58ea..8490be5cdc4 100644 --- a/tests/baselines/reference/FunctionPropertyAssignments5_es6.errors.txt +++ b/tests/baselines/reference/FunctionPropertyAssignments5_es6.errors.txt @@ -1,10 +1,10 @@ -tests/cases/conformance/es6/functionPropertyAssignments/FunctionPropertyAssignments5_es6.ts(1,11): error TS9001: Generators are not currently supported. +tests/cases/conformance/es6/functionPropertyAssignments/FunctionPropertyAssignments5_es6.ts(1,11): error TS1220: Generators are only available when targeting ECMAScript 6 or higher. tests/cases/conformance/es6/functionPropertyAssignments/FunctionPropertyAssignments5_es6.ts(1,13): error TS2304: Cannot find name 'foo'. ==== tests/cases/conformance/es6/functionPropertyAssignments/FunctionPropertyAssignments5_es6.ts (2 errors) ==== var v = { *[foo()]() { } } ~ -!!! error TS9001: Generators are not currently supported. +!!! error TS1220: Generators are only available when targeting ECMAScript 6 or higher. ~~~ !!! error TS2304: Cannot find name 'foo'. \ No newline at end of file diff --git a/tests/baselines/reference/MemberFunctionDeclaration1_es6.errors.txt b/tests/baselines/reference/MemberFunctionDeclaration1_es6.errors.txt index 9d4e312ed22..7766ad8d790 100644 --- a/tests/baselines/reference/MemberFunctionDeclaration1_es6.errors.txt +++ b/tests/baselines/reference/MemberFunctionDeclaration1_es6.errors.txt @@ -1,9 +1,9 @@ -tests/cases/conformance/es6/memberFunctionDeclarations/MemberFunctionDeclaration1_es6.ts(2,4): error TS9001: Generators are not currently supported. +tests/cases/conformance/es6/memberFunctionDeclarations/MemberFunctionDeclaration1_es6.ts(2,4): error TS1220: Generators are only available when targeting ECMAScript 6 or higher. ==== tests/cases/conformance/es6/memberFunctionDeclarations/MemberFunctionDeclaration1_es6.ts (1 errors) ==== class C { *foo() { } ~ -!!! error TS9001: Generators are not currently supported. +!!! error TS1220: Generators are only available when targeting ECMAScript 6 or higher. } \ No newline at end of file diff --git a/tests/baselines/reference/MemberFunctionDeclaration2_es6.errors.txt b/tests/baselines/reference/MemberFunctionDeclaration2_es6.errors.txt index 6373c800994..38a761f6db7 100644 --- a/tests/baselines/reference/MemberFunctionDeclaration2_es6.errors.txt +++ b/tests/baselines/reference/MemberFunctionDeclaration2_es6.errors.txt @@ -1,9 +1,9 @@ -tests/cases/conformance/es6/memberFunctionDeclarations/MemberFunctionDeclaration2_es6.ts(2,11): error TS9001: Generators are not currently supported. +tests/cases/conformance/es6/memberFunctionDeclarations/MemberFunctionDeclaration2_es6.ts(2,11): error TS1220: Generators are only available when targeting ECMAScript 6 or higher. ==== tests/cases/conformance/es6/memberFunctionDeclarations/MemberFunctionDeclaration2_es6.ts (1 errors) ==== class C { public * foo() { } ~ -!!! error TS9001: Generators are not currently supported. +!!! error TS1220: Generators are only available when targeting ECMAScript 6 or higher. } \ No newline at end of file diff --git a/tests/baselines/reference/MemberFunctionDeclaration3_es6.errors.txt b/tests/baselines/reference/MemberFunctionDeclaration3_es6.errors.txt index 826c1d7fd75..e561954035e 100644 --- a/tests/baselines/reference/MemberFunctionDeclaration3_es6.errors.txt +++ b/tests/baselines/reference/MemberFunctionDeclaration3_es6.errors.txt @@ -1,4 +1,4 @@ -tests/cases/conformance/es6/memberFunctionDeclarations/MemberFunctionDeclaration3_es6.ts(2,4): error TS9001: Generators are not currently supported. +tests/cases/conformance/es6/memberFunctionDeclarations/MemberFunctionDeclaration3_es6.ts(2,4): error TS1220: Generators are only available when targeting ECMAScript 6 or higher. tests/cases/conformance/es6/memberFunctionDeclarations/MemberFunctionDeclaration3_es6.ts(2,6): error TS2304: Cannot find name 'foo'. @@ -6,7 +6,7 @@ tests/cases/conformance/es6/memberFunctionDeclarations/MemberFunctionDeclaration class C { *[foo]() { } ~ -!!! error TS9001: Generators are not currently supported. +!!! error TS1220: Generators are only available when targeting ECMAScript 6 or higher. ~~~ !!! error TS2304: Cannot find name 'foo'. } \ No newline at end of file diff --git a/tests/baselines/reference/MemberFunctionDeclaration7_es6.errors.txt b/tests/baselines/reference/MemberFunctionDeclaration7_es6.errors.txt index ea87da50ed3..3eb8f5051a0 100644 --- a/tests/baselines/reference/MemberFunctionDeclaration7_es6.errors.txt +++ b/tests/baselines/reference/MemberFunctionDeclaration7_es6.errors.txt @@ -1,9 +1,9 @@ -tests/cases/conformance/es6/memberFunctionDeclarations/MemberFunctionDeclaration7_es6.ts(2,4): error TS9001: Generators are not currently supported. +tests/cases/conformance/es6/memberFunctionDeclarations/MemberFunctionDeclaration7_es6.ts(2,4): error TS1220: Generators are only available when targeting ECMAScript 6 or higher. ==== tests/cases/conformance/es6/memberFunctionDeclarations/MemberFunctionDeclaration7_es6.ts (1 errors) ==== class C { *foo() { } ~ -!!! error TS9001: Generators are not currently supported. +!!! error TS1220: Generators are only available when targeting ECMAScript 6 or higher. } \ No newline at end of file diff --git a/tests/baselines/reference/TypeGuardWithEnumUnion.types b/tests/baselines/reference/TypeGuardWithEnumUnion.types index 16d999e46f2..61cce562ba5 100644 --- a/tests/baselines/reference/TypeGuardWithEnumUnion.types +++ b/tests/baselines/reference/TypeGuardWithEnumUnion.types @@ -35,14 +35,14 @@ function f1(x: Color | string) { } function f2(x: Color | string | string[]) { ->f2 : (x: string | string[] | Color) => void ->x : string | string[] | Color +>f2 : (x: string | Color | string[]) => void +>x : string | Color | string[] >Color : Color if (typeof x === "object") { >typeof x === "object" : boolean >typeof x : string ->x : string | string[] | Color +>x : string | Color | string[] >"object" : string var y = x; @@ -55,7 +55,7 @@ function f2(x: Color | string | string[]) { if (typeof x === "number") { >typeof x === "number" : boolean >typeof x : string ->x : string | string[] | Color +>x : string | Color | string[] >"number" : string var z = x; @@ -77,7 +77,7 @@ function f2(x: Color | string | string[]) { if (typeof x === "string") { >typeof x === "string" : boolean >typeof x : string ->x : string | string[] | Color +>x : string | Color | string[] >"string" : string var a = x; @@ -89,11 +89,11 @@ function f2(x: Color | string | string[]) { } else { var b = x; ->b : string[] | Color ->x : string[] | Color +>b : Color | string[] +>x : Color | string[] var b: Color | string[]; ->b : string[] | Color +>b : Color | string[] >Color : Color } } diff --git a/tests/baselines/reference/VariableDeclaration11_es6.errors.txt b/tests/baselines/reference/VariableDeclaration11_es6.errors.txt index 8c0ef5f8690..d1e6ab7c154 100644 --- a/tests/baselines/reference/VariableDeclaration11_es6.errors.txt +++ b/tests/baselines/reference/VariableDeclaration11_es6.errors.txt @@ -1,8 +1,11 @@ -tests/cases/conformance/es6/variableDeclarations/VariableDeclaration11_es6.ts(2,4): error TS1123: Variable declaration list cannot be empty. +tests/cases/conformance/es6/variableDeclarations/VariableDeclaration11_es6.ts(2,1): error TS1212: Identifier expected. 'let' is a reserved word in strict mode +tests/cases/conformance/es6/variableDeclarations/VariableDeclaration11_es6.ts(2,1): error TS2304: Cannot find name 'let'. -==== tests/cases/conformance/es6/variableDeclarations/VariableDeclaration11_es6.ts (1 errors) ==== +==== tests/cases/conformance/es6/variableDeclarations/VariableDeclaration11_es6.ts (2 errors) ==== "use strict"; let - -!!! error TS1123: Variable declaration list cannot be empty. \ No newline at end of file + ~~~ +!!! error TS1212: Identifier expected. 'let' is a reserved word in strict mode + ~~~ +!!! error TS2304: Cannot find name 'let'. \ No newline at end of file diff --git a/tests/baselines/reference/VariableDeclaration11_es6.js b/tests/baselines/reference/VariableDeclaration11_es6.js index 83eec6d9a13..cf4c14617bc 100644 --- a/tests/baselines/reference/VariableDeclaration11_es6.js +++ b/tests/baselines/reference/VariableDeclaration11_es6.js @@ -4,4 +4,4 @@ let //// [VariableDeclaration11_es6.js] "use strict"; -let ; +let; diff --git a/tests/baselines/reference/YieldExpression10_es6.errors.txt b/tests/baselines/reference/YieldExpression10_es6.errors.txt index e0d7ea4ad27..99a73c48ba5 100644 --- a/tests/baselines/reference/YieldExpression10_es6.errors.txt +++ b/tests/baselines/reference/YieldExpression10_es6.errors.txt @@ -1,14 +1,14 @@ -tests/cases/conformance/es6/yieldExpressions/YieldExpression10_es6.ts(1,11): error TS9001: Generators are not currently supported. -tests/cases/conformance/es6/yieldExpressions/YieldExpression10_es6.ts(2,5): error TS9000: 'yield' expressions are not currently supported. +tests/cases/conformance/es6/yieldExpressions/YieldExpression10_es6.ts(1,11): error TS1220: Generators are only available when targeting ECMAScript 6 or higher. +tests/cases/conformance/es6/yieldExpressions/YieldExpression10_es6.ts(2,11): error TS2304: Cannot find name 'foo'. ==== tests/cases/conformance/es6/yieldExpressions/YieldExpression10_es6.ts (2 errors) ==== var v = { * foo() { ~ -!!! error TS9001: Generators are not currently supported. +!!! error TS1220: Generators are only available when targeting ECMAScript 6 or higher. yield(foo); - ~~~~~ -!!! error TS9000: 'yield' expressions are not currently supported. + ~~~ +!!! error TS2304: Cannot find name 'foo'. } } \ No newline at end of file diff --git a/tests/baselines/reference/YieldExpression11_es6.errors.txt b/tests/baselines/reference/YieldExpression11_es6.errors.txt index 3f322a81f2f..c19e8b6cfa5 100644 --- a/tests/baselines/reference/YieldExpression11_es6.errors.txt +++ b/tests/baselines/reference/YieldExpression11_es6.errors.txt @@ -1,14 +1,14 @@ -tests/cases/conformance/es6/yieldExpressions/YieldExpression11_es6.ts(2,3): error TS9001: Generators are not currently supported. -tests/cases/conformance/es6/yieldExpressions/YieldExpression11_es6.ts(3,5): error TS9000: 'yield' expressions are not currently supported. +tests/cases/conformance/es6/yieldExpressions/YieldExpression11_es6.ts(2,3): error TS1220: Generators are only available when targeting ECMAScript 6 or higher. +tests/cases/conformance/es6/yieldExpressions/YieldExpression11_es6.ts(3,11): error TS2304: Cannot find name 'foo'. ==== tests/cases/conformance/es6/yieldExpressions/YieldExpression11_es6.ts (2 errors) ==== class C { *foo() { ~ -!!! error TS9001: Generators are not currently supported. +!!! error TS1220: Generators are only available when targeting ECMAScript 6 or higher. yield(foo); - ~~~~~ -!!! error TS9000: 'yield' expressions are not currently supported. + ~~~ +!!! error TS2304: Cannot find name 'foo'. } } \ No newline at end of file diff --git a/tests/baselines/reference/YieldExpression12_es6.errors.txt b/tests/baselines/reference/YieldExpression12_es6.errors.txt index 10843421a3f..42d447ed5d6 100644 --- a/tests/baselines/reference/YieldExpression12_es6.errors.txt +++ b/tests/baselines/reference/YieldExpression12_es6.errors.txt @@ -1,4 +1,4 @@ -tests/cases/conformance/es6/yieldExpressions/YieldExpression12_es6.ts(3,6): error TS1163: 'yield' expression must be contained_within a generator declaration. +tests/cases/conformance/es6/yieldExpressions/YieldExpression12_es6.ts(3,6): error TS1163: A 'yield' expression is only allowed in a generator body. ==== tests/cases/conformance/es6/yieldExpressions/YieldExpression12_es6.ts (1 errors) ==== @@ -6,6 +6,6 @@ tests/cases/conformance/es6/yieldExpressions/YieldExpression12_es6.ts(3,6): erro constructor() { yield foo ~~~~~ -!!! error TS1163: 'yield' expression must be contained_within a generator declaration. +!!! error TS1163: A 'yield' expression is only allowed in a generator body. } } \ No newline at end of file diff --git a/tests/baselines/reference/YieldExpression13_es6.errors.txt b/tests/baselines/reference/YieldExpression13_es6.errors.txt index fc2d885d381..3166d742ae3 100644 --- a/tests/baselines/reference/YieldExpression13_es6.errors.txt +++ b/tests/baselines/reference/YieldExpression13_es6.errors.txt @@ -1,10 +1,7 @@ -tests/cases/conformance/es6/yieldExpressions/YieldExpression13_es6.ts(1,9): error TS9001: Generators are not currently supported. -tests/cases/conformance/es6/yieldExpressions/YieldExpression13_es6.ts(1,19): error TS9000: 'yield' expressions are not currently supported. +tests/cases/conformance/es6/yieldExpressions/YieldExpression13_es6.ts(1,9): error TS1220: Generators are only available when targeting ECMAScript 6 or higher. -==== tests/cases/conformance/es6/yieldExpressions/YieldExpression13_es6.ts (2 errors) ==== +==== tests/cases/conformance/es6/yieldExpressions/YieldExpression13_es6.ts (1 errors) ==== function* foo() { yield } ~ -!!! error TS9001: Generators are not currently supported. - ~~~~~ -!!! error TS9000: 'yield' expressions are not currently supported. \ No newline at end of file +!!! error TS1220: Generators are only available when targeting ECMAScript 6 or higher. \ No newline at end of file diff --git a/tests/baselines/reference/YieldExpression14_es6.errors.txt b/tests/baselines/reference/YieldExpression14_es6.errors.txt index baeaf3ba30e..2e32e7a2388 100644 --- a/tests/baselines/reference/YieldExpression14_es6.errors.txt +++ b/tests/baselines/reference/YieldExpression14_es6.errors.txt @@ -1,4 +1,4 @@ -tests/cases/conformance/es6/yieldExpressions/YieldExpression14_es6.ts(3,6): error TS1163: 'yield' expression must be contained_within a generator declaration. +tests/cases/conformance/es6/yieldExpressions/YieldExpression14_es6.ts(3,6): error TS1163: A 'yield' expression is only allowed in a generator body. ==== tests/cases/conformance/es6/yieldExpressions/YieldExpression14_es6.ts (1 errors) ==== @@ -6,6 +6,6 @@ tests/cases/conformance/es6/yieldExpressions/YieldExpression14_es6.ts(3,6): erro foo() { yield foo ~~~~~ -!!! error TS1163: 'yield' expression must be contained_within a generator declaration. +!!! error TS1163: A 'yield' expression is only allowed in a generator body. } } \ No newline at end of file diff --git a/tests/baselines/reference/YieldExpression15_es6.errors.txt b/tests/baselines/reference/YieldExpression15_es6.errors.txt index 5e548799f5d..bb60f6a8f76 100644 --- a/tests/baselines/reference/YieldExpression15_es6.errors.txt +++ b/tests/baselines/reference/YieldExpression15_es6.errors.txt @@ -1,9 +1,9 @@ -tests/cases/conformance/es6/yieldExpressions/YieldExpression15_es6.ts(2,6): error TS1163: 'yield' expression must be contained_within a generator declaration. +tests/cases/conformance/es6/yieldExpressions/YieldExpression15_es6.ts(2,6): error TS1163: A 'yield' expression is only allowed in a generator body. ==== tests/cases/conformance/es6/yieldExpressions/YieldExpression15_es6.ts (1 errors) ==== var v = () => { yield foo ~~~~~ -!!! error TS1163: 'yield' expression must be contained_within a generator declaration. +!!! error TS1163: A 'yield' expression is only allowed in a generator body. } \ No newline at end of file diff --git a/tests/baselines/reference/YieldExpression16_es6.errors.txt b/tests/baselines/reference/YieldExpression16_es6.errors.txt index c0d2e4c8fc8..e792bc59240 100644 --- a/tests/baselines/reference/YieldExpression16_es6.errors.txt +++ b/tests/baselines/reference/YieldExpression16_es6.errors.txt @@ -1,14 +1,14 @@ -tests/cases/conformance/es6/yieldExpressions/YieldExpression16_es6.ts(1,9): error TS9001: Generators are not currently supported. -tests/cases/conformance/es6/yieldExpressions/YieldExpression16_es6.ts(3,5): error TS1163: 'yield' expression must be contained_within a generator declaration. +tests/cases/conformance/es6/yieldExpressions/YieldExpression16_es6.ts(1,9): error TS1220: Generators are only available when targeting ECMAScript 6 or higher. +tests/cases/conformance/es6/yieldExpressions/YieldExpression16_es6.ts(3,5): error TS1163: A 'yield' expression is only allowed in a generator body. ==== tests/cases/conformance/es6/yieldExpressions/YieldExpression16_es6.ts (2 errors) ==== function* foo() { ~ -!!! error TS9001: Generators are not currently supported. +!!! error TS1220: Generators are only available when targeting ECMAScript 6 or higher. function bar() { yield foo; ~~~~~ -!!! error TS1163: 'yield' expression must be contained_within a generator declaration. +!!! error TS1163: A 'yield' expression is only allowed in a generator body. } } \ No newline at end of file diff --git a/tests/baselines/reference/YieldExpression17_es6.errors.txt b/tests/baselines/reference/YieldExpression17_es6.errors.txt index b39f47b07f9..bc262212526 100644 --- a/tests/baselines/reference/YieldExpression17_es6.errors.txt +++ b/tests/baselines/reference/YieldExpression17_es6.errors.txt @@ -1,6 +1,6 @@ tests/cases/conformance/es6/yieldExpressions/YieldExpression17_es6.ts(1,15): error TS1056: Accessors are only available when targeting ECMAScript 5 and higher. tests/cases/conformance/es6/yieldExpressions/YieldExpression17_es6.ts(1,15): error TS2378: A 'get' accessor must return a value or consist of a single 'throw' statement. -tests/cases/conformance/es6/yieldExpressions/YieldExpression17_es6.ts(1,23): error TS1163: 'yield' expression must be contained_within a generator declaration. +tests/cases/conformance/es6/yieldExpressions/YieldExpression17_es6.ts(1,23): error TS1163: A 'yield' expression is only allowed in a generator body. ==== tests/cases/conformance/es6/yieldExpressions/YieldExpression17_es6.ts (3 errors) ==== @@ -10,4 +10,4 @@ tests/cases/conformance/es6/yieldExpressions/YieldExpression17_es6.ts(1,23): err ~~~ !!! error TS2378: A 'get' accessor must return a value or consist of a single 'throw' statement. ~~~~~ -!!! error TS1163: 'yield' expression must be contained_within a generator declaration. \ No newline at end of file +!!! error TS1163: A 'yield' expression is only allowed in a generator body. \ No newline at end of file diff --git a/tests/baselines/reference/YieldExpression18_es6.errors.txt b/tests/baselines/reference/YieldExpression18_es6.errors.txt index 3a67acdebcd..5dd2807716f 100644 --- a/tests/baselines/reference/YieldExpression18_es6.errors.txt +++ b/tests/baselines/reference/YieldExpression18_es6.errors.txt @@ -1,8 +1,14 @@ -tests/cases/conformance/es6/yieldExpressions/YieldExpression18_es6.ts(2,1): error TS1163: 'yield' expression must be contained_within a generator declaration. +tests/cases/conformance/es6/yieldExpressions/YieldExpression18_es6.ts(2,1): error TS1212: Identifier expected. 'yield' is a reserved word in strict mode +tests/cases/conformance/es6/yieldExpressions/YieldExpression18_es6.ts(2,1): error TS2304: Cannot find name 'yield'. +tests/cases/conformance/es6/yieldExpressions/YieldExpression18_es6.ts(2,7): error TS2304: Cannot find name 'foo'. -==== tests/cases/conformance/es6/yieldExpressions/YieldExpression18_es6.ts (1 errors) ==== +==== tests/cases/conformance/es6/yieldExpressions/YieldExpression18_es6.ts (3 errors) ==== "use strict"; yield(foo); ~~~~~ -!!! error TS1163: 'yield' expression must be contained_within a generator declaration. \ No newline at end of file +!!! error TS1212: Identifier expected. 'yield' is a reserved word in strict mode + ~~~~~ +!!! error TS2304: Cannot find name 'yield'. + ~~~ +!!! error TS2304: Cannot find name 'foo'. \ No newline at end of file diff --git a/tests/baselines/reference/YieldExpression18_es6.js b/tests/baselines/reference/YieldExpression18_es6.js index b4ba37d3ac4..36be3faabfe 100644 --- a/tests/baselines/reference/YieldExpression18_es6.js +++ b/tests/baselines/reference/YieldExpression18_es6.js @@ -4,4 +4,4 @@ yield(foo); //// [YieldExpression18_es6.js] "use strict"; -yield (foo); +yield(foo); diff --git a/tests/baselines/reference/YieldExpression19_es6.errors.txt b/tests/baselines/reference/YieldExpression19_es6.errors.txt index 9d04d9559b0..02591de78ca 100644 --- a/tests/baselines/reference/YieldExpression19_es6.errors.txt +++ b/tests/baselines/reference/YieldExpression19_es6.errors.txt @@ -1,19 +1,16 @@ -tests/cases/conformance/es6/yieldExpressions/YieldExpression19_es6.ts(1,9): error TS9001: Generators are not currently supported. -tests/cases/conformance/es6/yieldExpressions/YieldExpression19_es6.ts(3,13): error TS9001: Generators are not currently supported. -tests/cases/conformance/es6/yieldExpressions/YieldExpression19_es6.ts(4,7): error TS9000: 'yield' expressions are not currently supported. +tests/cases/conformance/es6/yieldExpressions/YieldExpression19_es6.ts(1,9): error TS1220: Generators are only available when targeting ECMAScript 6 or higher. +tests/cases/conformance/es6/yieldExpressions/YieldExpression19_es6.ts(3,13): error TS1220: Generators are only available when targeting ECMAScript 6 or higher. -==== tests/cases/conformance/es6/yieldExpressions/YieldExpression19_es6.ts (3 errors) ==== +==== tests/cases/conformance/es6/yieldExpressions/YieldExpression19_es6.ts (2 errors) ==== function*foo() { ~ -!!! error TS9001: Generators are not currently supported. +!!! error TS1220: Generators are only available when targeting ECMAScript 6 or higher. function bar() { function* quux() { ~ -!!! error TS9001: Generators are not currently supported. +!!! error TS1220: Generators are only available when targeting ECMAScript 6 or higher. yield(foo); - ~~~~~ -!!! error TS9000: 'yield' expressions are not currently supported. } } } \ No newline at end of file diff --git a/tests/baselines/reference/YieldExpression2_es6.errors.txt b/tests/baselines/reference/YieldExpression2_es6.errors.txt index 553dab51fc2..2d1a7082d53 100644 --- a/tests/baselines/reference/YieldExpression2_es6.errors.txt +++ b/tests/baselines/reference/YieldExpression2_es6.errors.txt @@ -1,7 +1,7 @@ -tests/cases/conformance/es6/yieldExpressions/YieldExpression2_es6.ts(1,1): error TS1163: 'yield' expression must be contained_within a generator declaration. +tests/cases/conformance/es6/yieldExpressions/YieldExpression2_es6.ts(1,1): error TS1163: A 'yield' expression is only allowed in a generator body. ==== tests/cases/conformance/es6/yieldExpressions/YieldExpression2_es6.ts (1 errors) ==== yield foo; ~~~~~ -!!! error TS1163: 'yield' expression must be contained_within a generator declaration. \ No newline at end of file +!!! error TS1163: A 'yield' expression is only allowed in a generator body. \ No newline at end of file diff --git a/tests/baselines/reference/YieldExpression3_es6.errors.txt b/tests/baselines/reference/YieldExpression3_es6.errors.txt index 1e284c92786..c03a5f1c469 100644 --- a/tests/baselines/reference/YieldExpression3_es6.errors.txt +++ b/tests/baselines/reference/YieldExpression3_es6.errors.txt @@ -1,16 +1,10 @@ -tests/cases/conformance/es6/yieldExpressions/YieldExpression3_es6.ts(1,9): error TS9001: Generators are not currently supported. -tests/cases/conformance/es6/yieldExpressions/YieldExpression3_es6.ts(2,3): error TS9000: 'yield' expressions are not currently supported. -tests/cases/conformance/es6/yieldExpressions/YieldExpression3_es6.ts(3,3): error TS9000: 'yield' expressions are not currently supported. +tests/cases/conformance/es6/yieldExpressions/YieldExpression3_es6.ts(1,9): error TS1220: Generators are only available when targeting ECMAScript 6 or higher. -==== tests/cases/conformance/es6/yieldExpressions/YieldExpression3_es6.ts (3 errors) ==== +==== tests/cases/conformance/es6/yieldExpressions/YieldExpression3_es6.ts (1 errors) ==== function* foo() { ~ -!!! error TS9001: Generators are not currently supported. +!!! error TS1220: Generators are only available when targeting ECMAScript 6 or higher. yield - ~~~~~ -!!! error TS9000: 'yield' expressions are not currently supported. yield - ~~~~~ -!!! error TS9000: 'yield' expressions are not currently supported. } \ No newline at end of file diff --git a/tests/baselines/reference/YieldExpression4_es6.errors.txt b/tests/baselines/reference/YieldExpression4_es6.errors.txt index 2d2a7ca3257..cea33eabfa4 100644 --- a/tests/baselines/reference/YieldExpression4_es6.errors.txt +++ b/tests/baselines/reference/YieldExpression4_es6.errors.txt @@ -1,16 +1,10 @@ -tests/cases/conformance/es6/yieldExpressions/YieldExpression4_es6.ts(1,9): error TS9001: Generators are not currently supported. -tests/cases/conformance/es6/yieldExpressions/YieldExpression4_es6.ts(2,3): error TS9000: 'yield' expressions are not currently supported. -tests/cases/conformance/es6/yieldExpressions/YieldExpression4_es6.ts(3,3): error TS9000: 'yield' expressions are not currently supported. +tests/cases/conformance/es6/yieldExpressions/YieldExpression4_es6.ts(1,9): error TS1220: Generators are only available when targeting ECMAScript 6 or higher. -==== tests/cases/conformance/es6/yieldExpressions/YieldExpression4_es6.ts (3 errors) ==== +==== tests/cases/conformance/es6/yieldExpressions/YieldExpression4_es6.ts (1 errors) ==== function* foo() { ~ -!!! error TS9001: Generators are not currently supported. +!!! error TS1220: Generators are only available when targeting ECMAScript 6 or higher. yield; - ~~~~~ -!!! error TS9000: 'yield' expressions are not currently supported. yield; - ~~~~~ -!!! error TS9000: 'yield' expressions are not currently supported. } \ No newline at end of file diff --git a/tests/baselines/reference/YieldExpression6_es6.errors.txt b/tests/baselines/reference/YieldExpression6_es6.errors.txt index a3d9481601a..fce6583844f 100644 --- a/tests/baselines/reference/YieldExpression6_es6.errors.txt +++ b/tests/baselines/reference/YieldExpression6_es6.errors.txt @@ -1,12 +1,12 @@ -tests/cases/conformance/es6/yieldExpressions/YieldExpression6_es6.ts(1,9): error TS9001: Generators are not currently supported. -tests/cases/conformance/es6/yieldExpressions/YieldExpression6_es6.ts(2,3): error TS9000: 'yield' expressions are not currently supported. +tests/cases/conformance/es6/yieldExpressions/YieldExpression6_es6.ts(1,9): error TS1220: Generators are only available when targeting ECMAScript 6 or higher. +tests/cases/conformance/es6/yieldExpressions/YieldExpression6_es6.ts(2,9): error TS2488: Type must have a '[Symbol.iterator]()' method that returns an iterator. ==== tests/cases/conformance/es6/yieldExpressions/YieldExpression6_es6.ts (2 errors) ==== function* foo() { ~ -!!! error TS9001: Generators are not currently supported. +!!! error TS1220: Generators are only available when targeting ECMAScript 6 or higher. yield*foo - ~~~~~ -!!! error TS9000: 'yield' expressions are not currently supported. + ~~~ +!!! error TS2488: Type must have a '[Symbol.iterator]()' method that returns an iterator. } \ No newline at end of file diff --git a/tests/baselines/reference/YieldExpression7_es6.errors.txt b/tests/baselines/reference/YieldExpression7_es6.errors.txt index 393a03ee269..39d085b71f9 100644 --- a/tests/baselines/reference/YieldExpression7_es6.errors.txt +++ b/tests/baselines/reference/YieldExpression7_es6.errors.txt @@ -1,12 +1,9 @@ -tests/cases/conformance/es6/yieldExpressions/YieldExpression7_es6.ts(1,9): error TS9001: Generators are not currently supported. -tests/cases/conformance/es6/yieldExpressions/YieldExpression7_es6.ts(2,3): error TS9000: 'yield' expressions are not currently supported. +tests/cases/conformance/es6/yieldExpressions/YieldExpression7_es6.ts(1,9): error TS1220: Generators are only available when targeting ECMAScript 6 or higher. -==== tests/cases/conformance/es6/yieldExpressions/YieldExpression7_es6.ts (2 errors) ==== +==== tests/cases/conformance/es6/yieldExpressions/YieldExpression7_es6.ts (1 errors) ==== function* foo() { ~ -!!! error TS9001: Generators are not currently supported. +!!! error TS1220: Generators are only available when targeting ECMAScript 6 or higher. yield foo - ~~~~~ -!!! error TS9000: 'yield' expressions are not currently supported. } \ No newline at end of file diff --git a/tests/baselines/reference/YieldExpression8_es6.errors.txt b/tests/baselines/reference/YieldExpression8_es6.errors.txt index 3f7933c5bb2..b14fa0872a2 100644 --- a/tests/baselines/reference/YieldExpression8_es6.errors.txt +++ b/tests/baselines/reference/YieldExpression8_es6.errors.txt @@ -1,16 +1,13 @@ tests/cases/conformance/es6/yieldExpressions/YieldExpression8_es6.ts(1,1): error TS2304: Cannot find name 'yield'. -tests/cases/conformance/es6/yieldExpressions/YieldExpression8_es6.ts(2,9): error TS9001: Generators are not currently supported. -tests/cases/conformance/es6/yieldExpressions/YieldExpression8_es6.ts(3,3): error TS9000: 'yield' expressions are not currently supported. +tests/cases/conformance/es6/yieldExpressions/YieldExpression8_es6.ts(2,9): error TS1220: Generators are only available when targeting ECMAScript 6 or higher. -==== tests/cases/conformance/es6/yieldExpressions/YieldExpression8_es6.ts (3 errors) ==== +==== tests/cases/conformance/es6/yieldExpressions/YieldExpression8_es6.ts (2 errors) ==== yield(foo); ~~~~~ !!! error TS2304: Cannot find name 'yield'. function* foo() { ~ -!!! error TS9001: Generators are not currently supported. +!!! error TS1220: Generators are only available when targeting ECMAScript 6 or higher. yield(foo); - ~~~~~ -!!! error TS9000: 'yield' expressions are not currently supported. } \ No newline at end of file diff --git a/tests/baselines/reference/YieldExpression9_es6.errors.txt b/tests/baselines/reference/YieldExpression9_es6.errors.txt index cd753647327..aceb0383200 100644 --- a/tests/baselines/reference/YieldExpression9_es6.errors.txt +++ b/tests/baselines/reference/YieldExpression9_es6.errors.txt @@ -1,12 +1,12 @@ -tests/cases/conformance/es6/yieldExpressions/YieldExpression9_es6.ts(1,17): error TS9001: Generators are not currently supported. -tests/cases/conformance/es6/yieldExpressions/YieldExpression9_es6.ts(2,3): error TS9000: 'yield' expressions are not currently supported. +tests/cases/conformance/es6/yieldExpressions/YieldExpression9_es6.ts(1,17): error TS1220: Generators are only available when targeting ECMAScript 6 or higher. +tests/cases/conformance/es6/yieldExpressions/YieldExpression9_es6.ts(2,9): error TS2304: Cannot find name 'foo'. ==== tests/cases/conformance/es6/yieldExpressions/YieldExpression9_es6.ts (2 errors) ==== var v = function*() { ~ -!!! error TS9001: Generators are not currently supported. +!!! error TS1220: Generators are only available when targeting ECMAScript 6 or higher. yield(foo); - ~~~~~ -!!! error TS9000: 'yield' expressions are not currently supported. + ~~~ +!!! error TS2304: Cannot find name 'foo'. } \ No newline at end of file diff --git a/tests/baselines/reference/YieldStarExpression1_es6.errors.txt b/tests/baselines/reference/YieldStarExpression1_es6.errors.txt new file mode 100644 index 00000000000..9ba5e44f9aa --- /dev/null +++ b/tests/baselines/reference/YieldStarExpression1_es6.errors.txt @@ -0,0 +1,10 @@ +tests/cases/conformance/es6/yieldExpressions/YieldStarExpression1_es6.ts(1,1): error TS2304: Cannot find name 'yield'. +tests/cases/conformance/es6/yieldExpressions/YieldStarExpression1_es6.ts(1,9): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + + +==== tests/cases/conformance/es6/yieldExpressions/YieldStarExpression1_es6.ts (2 errors) ==== + yield * []; + ~~~~~ +!!! error TS2304: Cannot find name 'yield'. + ~~ +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. \ No newline at end of file diff --git a/tests/baselines/reference/YieldStarExpression1_es6.js b/tests/baselines/reference/YieldStarExpression1_es6.js new file mode 100644 index 00000000000..742c5b7d1e7 --- /dev/null +++ b/tests/baselines/reference/YieldStarExpression1_es6.js @@ -0,0 +1,5 @@ +//// [YieldStarExpression1_es6.ts] +yield * []; + +//// [YieldStarExpression1_es6.js] +yield * []; diff --git a/tests/baselines/reference/YieldStarExpression2_es6.errors.txt b/tests/baselines/reference/YieldStarExpression2_es6.errors.txt new file mode 100644 index 00000000000..3d0c89fd23f --- /dev/null +++ b/tests/baselines/reference/YieldStarExpression2_es6.errors.txt @@ -0,0 +1,10 @@ +tests/cases/conformance/es6/yieldExpressions/YieldStarExpression2_es6.ts(1,1): error TS2304: Cannot find name 'yield'. +tests/cases/conformance/es6/yieldExpressions/YieldStarExpression2_es6.ts(1,8): error TS1109: Expression expected. + + +==== tests/cases/conformance/es6/yieldExpressions/YieldStarExpression2_es6.ts (2 errors) ==== + yield *; + ~~~~~ +!!! error TS2304: Cannot find name 'yield'. + ~ +!!! error TS1109: Expression expected. \ No newline at end of file diff --git a/tests/baselines/reference/YieldStarExpression2_es6.js b/tests/baselines/reference/YieldStarExpression2_es6.js new file mode 100644 index 00000000000..5b40963d9a2 --- /dev/null +++ b/tests/baselines/reference/YieldStarExpression2_es6.js @@ -0,0 +1,5 @@ +//// [YieldStarExpression2_es6.ts] +yield *; + +//// [YieldStarExpression2_es6.js] +yield * ; diff --git a/tests/baselines/reference/YieldStarExpression3_es6.errors.txt b/tests/baselines/reference/YieldStarExpression3_es6.errors.txt new file mode 100644 index 00000000000..25cecc80444 --- /dev/null +++ b/tests/baselines/reference/YieldStarExpression3_es6.errors.txt @@ -0,0 +1,9 @@ +tests/cases/conformance/es6/yieldExpressions/YieldStarExpression3_es6.ts(2,12): error TS1109: Expression expected. + + +==== tests/cases/conformance/es6/yieldExpressions/YieldStarExpression3_es6.ts (1 errors) ==== + function *g() { + yield *; + ~ +!!! error TS1109: Expression expected. + } \ No newline at end of file diff --git a/tests/baselines/reference/YieldStarExpression3_es6.js b/tests/baselines/reference/YieldStarExpression3_es6.js new file mode 100644 index 00000000000..7463fc01bc1 --- /dev/null +++ b/tests/baselines/reference/YieldStarExpression3_es6.js @@ -0,0 +1,9 @@ +//// [YieldStarExpression3_es6.ts] +function *g() { + yield *; +} + +//// [YieldStarExpression3_es6.js] +function g() { + yield* ; +} diff --git a/tests/baselines/reference/YieldStarExpression4_es6.errors.txt b/tests/baselines/reference/YieldStarExpression4_es6.errors.txt new file mode 100644 index 00000000000..4935df494d5 --- /dev/null +++ b/tests/baselines/reference/YieldStarExpression4_es6.errors.txt @@ -0,0 +1,12 @@ +tests/cases/conformance/es6/yieldExpressions/YieldStarExpression4_es6.ts(1,10): error TS1220: Generators are only available when targeting ECMAScript 6 or higher. +tests/cases/conformance/es6/yieldExpressions/YieldStarExpression4_es6.ts(2,13): error TS2488: Type must have a '[Symbol.iterator]()' method that returns an iterator. + + +==== tests/cases/conformance/es6/yieldExpressions/YieldStarExpression4_es6.ts (2 errors) ==== + function *g() { + ~ +!!! error TS1220: Generators are only available when targeting ECMAScript 6 or higher. + yield * []; + ~~ +!!! error TS2488: Type must have a '[Symbol.iterator]()' method that returns an iterator. + } \ No newline at end of file diff --git a/tests/baselines/reference/YieldStarExpression4_es6.js b/tests/baselines/reference/YieldStarExpression4_es6.js new file mode 100644 index 00000000000..6283b81cca3 --- /dev/null +++ b/tests/baselines/reference/YieldStarExpression4_es6.js @@ -0,0 +1,9 @@ +//// [YieldStarExpression4_es6.ts] +function *g() { + yield * []; +} + +//// [YieldStarExpression4_es6.js] +function g() { + yield* []; +} diff --git a/tests/baselines/reference/accessOverriddenBaseClassMember1.js b/tests/baselines/reference/accessOverriddenBaseClassMember1.js index f6d3f29f1ab..e3a4d0602b8 100644 --- a/tests/baselines/reference/accessOverriddenBaseClassMember1.js +++ b/tests/baselines/reference/accessOverriddenBaseClassMember1.js @@ -19,8 +19,7 @@ class ColoredPoint extends Point { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var Point = (function () { function Point(x, y) { diff --git a/tests/baselines/reference/accessors_spec_section-4.5_inference.js b/tests/baselines/reference/accessors_spec_section-4.5_inference.js index 8b75e27031a..808019448b7 100644 --- a/tests/baselines/reference/accessors_spec_section-4.5_inference.js +++ b/tests/baselines/reference/accessors_spec_section-4.5_inference.js @@ -28,8 +28,7 @@ class LanguageSpec_section_4_5_inference { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var A = (function () { function A() { diff --git a/tests/baselines/reference/aliasUsageInAccessorsOfClass.js b/tests/baselines/reference/aliasUsageInAccessorsOfClass.js index 06c8b55e23d..11e02297e47 100644 --- a/tests/baselines/reference/aliasUsageInAccessorsOfClass.js +++ b/tests/baselines/reference/aliasUsageInAccessorsOfClass.js @@ -38,8 +38,7 @@ exports.Model = Model; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var Backbone = require("aliasUsage1_backbone"); var VisualizationModel = (function (_super) { diff --git a/tests/baselines/reference/aliasUsageInAccessorsOfClass.types b/tests/baselines/reference/aliasUsageInAccessorsOfClass.types index eccdbc8528c..092643002e4 100644 --- a/tests/baselines/reference/aliasUsageInAccessorsOfClass.types +++ b/tests/baselines/reference/aliasUsageInAccessorsOfClass.types @@ -53,9 +53,9 @@ import Backbone = require("aliasUsage1_backbone"); export class VisualizationModel extends Backbone.Model { >VisualizationModel : VisualizationModel ->Backbone.Model : any +>Backbone.Model : Backbone.Model >Backbone : typeof Backbone ->Model : Backbone.Model +>Model : typeof Backbone.Model // interesting stuff here } diff --git a/tests/baselines/reference/aliasUsageInArray.js b/tests/baselines/reference/aliasUsageInArray.js index e5d44320c7d..ba0c954a3c2 100644 --- a/tests/baselines/reference/aliasUsageInArray.js +++ b/tests/baselines/reference/aliasUsageInArray.js @@ -32,8 +32,7 @@ exports.Model = Model; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var Backbone = require("aliasUsageInArray_backbone"); var VisualizationModel = (function (_super) { diff --git a/tests/baselines/reference/aliasUsageInArray.types b/tests/baselines/reference/aliasUsageInArray.types index ee54300e7d9..488cc97d07f 100644 --- a/tests/baselines/reference/aliasUsageInArray.types +++ b/tests/baselines/reference/aliasUsageInArray.types @@ -41,9 +41,9 @@ import Backbone = require("aliasUsageInArray_backbone"); export class VisualizationModel extends Backbone.Model { >VisualizationModel : VisualizationModel ->Backbone.Model : any +>Backbone.Model : Backbone.Model >Backbone : typeof Backbone ->Model : Backbone.Model +>Model : typeof Backbone.Model // interesting stuff here } diff --git a/tests/baselines/reference/aliasUsageInFunctionExpression.js b/tests/baselines/reference/aliasUsageInFunctionExpression.js index b7b95661ac8..702cbe4d53f 100644 --- a/tests/baselines/reference/aliasUsageInFunctionExpression.js +++ b/tests/baselines/reference/aliasUsageInFunctionExpression.js @@ -31,8 +31,7 @@ exports.Model = Model; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var Backbone = require("aliasUsageInFunctionExpression_backbone"); var VisualizationModel = (function (_super) { diff --git a/tests/baselines/reference/aliasUsageInFunctionExpression.types b/tests/baselines/reference/aliasUsageInFunctionExpression.types index 17994dcab52..eec4341fd67 100644 --- a/tests/baselines/reference/aliasUsageInFunctionExpression.types +++ b/tests/baselines/reference/aliasUsageInFunctionExpression.types @@ -42,9 +42,9 @@ import Backbone = require("aliasUsageInFunctionExpression_backbone"); export class VisualizationModel extends Backbone.Model { >VisualizationModel : VisualizationModel ->Backbone.Model : any +>Backbone.Model : Backbone.Model >Backbone : typeof Backbone ->Model : Backbone.Model +>Model : typeof Backbone.Model // interesting stuff here } diff --git a/tests/baselines/reference/aliasUsageInGenericFunction.js b/tests/baselines/reference/aliasUsageInGenericFunction.js index 856e6ddb43e..8706dd592eb 100644 --- a/tests/baselines/reference/aliasUsageInGenericFunction.js +++ b/tests/baselines/reference/aliasUsageInGenericFunction.js @@ -35,8 +35,7 @@ exports.Model = Model; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var Backbone = require("aliasUsageInGenericFunction_backbone"); var VisualizationModel = (function (_super) { diff --git a/tests/baselines/reference/aliasUsageInGenericFunction.types b/tests/baselines/reference/aliasUsageInGenericFunction.types index 0821732f5fc..c21e691d773 100644 --- a/tests/baselines/reference/aliasUsageInGenericFunction.types +++ b/tests/baselines/reference/aliasUsageInGenericFunction.types @@ -57,9 +57,9 @@ import Backbone = require("aliasUsageInGenericFunction_backbone"); export class VisualizationModel extends Backbone.Model { >VisualizationModel : VisualizationModel ->Backbone.Model : any +>Backbone.Model : Backbone.Model >Backbone : typeof Backbone ->Model : Backbone.Model +>Model : typeof Backbone.Model // interesting stuff here } diff --git a/tests/baselines/reference/aliasUsageInIndexerOfClass.js b/tests/baselines/reference/aliasUsageInIndexerOfClass.js index e05f5e4f5cd..78ddd2d4a94 100644 --- a/tests/baselines/reference/aliasUsageInIndexerOfClass.js +++ b/tests/baselines/reference/aliasUsageInIndexerOfClass.js @@ -37,8 +37,7 @@ exports.Model = Model; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var Backbone = require("aliasUsageInIndexerOfClass_backbone"); var VisualizationModel = (function (_super) { diff --git a/tests/baselines/reference/aliasUsageInIndexerOfClass.types b/tests/baselines/reference/aliasUsageInIndexerOfClass.types index fe67655d4f5..b7e4873ba34 100644 --- a/tests/baselines/reference/aliasUsageInIndexerOfClass.types +++ b/tests/baselines/reference/aliasUsageInIndexerOfClass.types @@ -50,9 +50,9 @@ import Backbone = require("aliasUsageInIndexerOfClass_backbone"); export class VisualizationModel extends Backbone.Model { >VisualizationModel : VisualizationModel ->Backbone.Model : any +>Backbone.Model : Backbone.Model >Backbone : typeof Backbone ->Model : Backbone.Model +>Model : typeof Backbone.Model // interesting stuff here } diff --git a/tests/baselines/reference/aliasUsageInObjectLiteral.js b/tests/baselines/reference/aliasUsageInObjectLiteral.js index cc4b8273e84..f38cdf2111c 100644 --- a/tests/baselines/reference/aliasUsageInObjectLiteral.js +++ b/tests/baselines/reference/aliasUsageInObjectLiteral.js @@ -32,8 +32,7 @@ exports.Model = Model; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var Backbone = require("aliasUsageInObjectLiteral_backbone"); var VisualizationModel = (function (_super) { diff --git a/tests/baselines/reference/aliasUsageInObjectLiteral.types b/tests/baselines/reference/aliasUsageInObjectLiteral.types index 32a78d555b1..5ab294b7350 100644 --- a/tests/baselines/reference/aliasUsageInObjectLiteral.types +++ b/tests/baselines/reference/aliasUsageInObjectLiteral.types @@ -55,9 +55,9 @@ import Backbone = require("aliasUsageInObjectLiteral_backbone"); export class VisualizationModel extends Backbone.Model { >VisualizationModel : VisualizationModel ->Backbone.Model : any +>Backbone.Model : Backbone.Model >Backbone : typeof Backbone ->Model : Backbone.Model +>Model : typeof Backbone.Model // interesting stuff here } diff --git a/tests/baselines/reference/aliasUsageInOrExpression.js b/tests/baselines/reference/aliasUsageInOrExpression.js index f382ee2f617..906a2c019d7 100644 --- a/tests/baselines/reference/aliasUsageInOrExpression.js +++ b/tests/baselines/reference/aliasUsageInOrExpression.js @@ -35,8 +35,7 @@ exports.Model = Model; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var Backbone = require("aliasUsageInOrExpression_backbone"); var VisualizationModel = (function (_super) { diff --git a/tests/baselines/reference/aliasUsageInOrExpression.types b/tests/baselines/reference/aliasUsageInOrExpression.types index 8d3163d481b..e7ca8639762 100644 --- a/tests/baselines/reference/aliasUsageInOrExpression.types +++ b/tests/baselines/reference/aliasUsageInOrExpression.types @@ -79,9 +79,9 @@ import Backbone = require("aliasUsageInOrExpression_backbone"); export class VisualizationModel extends Backbone.Model { >VisualizationModel : VisualizationModel ->Backbone.Model : any +>Backbone.Model : Backbone.Model >Backbone : typeof Backbone ->Model : Backbone.Model +>Model : typeof Backbone.Model // interesting stuff here } diff --git a/tests/baselines/reference/aliasUsageInTypeArgumentOfExtendsClause.js b/tests/baselines/reference/aliasUsageInTypeArgumentOfExtendsClause.js index 39ff58a5322..27f85bb5fcd 100644 --- a/tests/baselines/reference/aliasUsageInTypeArgumentOfExtendsClause.js +++ b/tests/baselines/reference/aliasUsageInTypeArgumentOfExtendsClause.js @@ -35,8 +35,7 @@ exports.Model = Model; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var Backbone = require("aliasUsageInTypeArgumentOfExtendsClause_backbone"); var VisualizationModel = (function (_super) { @@ -51,8 +50,7 @@ exports.VisualizationModel = VisualizationModel; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var moduleA = require("aliasUsageInTypeArgumentOfExtendsClause_moduleA"); var C = (function () { diff --git a/tests/baselines/reference/aliasUsageInTypeArgumentOfExtendsClause.types b/tests/baselines/reference/aliasUsageInTypeArgumentOfExtendsClause.types index 460b422a2a4..ae20caa9c37 100644 --- a/tests/baselines/reference/aliasUsageInTypeArgumentOfExtendsClause.types +++ b/tests/baselines/reference/aliasUsageInTypeArgumentOfExtendsClause.types @@ -25,7 +25,7 @@ class C { } class D extends C { >D : D ->C : C +>C : C >IHasVisualizationModel : IHasVisualizationModel x = moduleA; @@ -46,9 +46,9 @@ import Backbone = require("aliasUsageInTypeArgumentOfExtendsClause_backbone"); export class VisualizationModel extends Backbone.Model { >VisualizationModel : VisualizationModel ->Backbone.Model : any +>Backbone.Model : Backbone.Model >Backbone : typeof Backbone ->Model : Backbone.Model +>Model : typeof Backbone.Model // interesting stuff here } diff --git a/tests/baselines/reference/aliasUsageInVarAssignment.js b/tests/baselines/reference/aliasUsageInVarAssignment.js index 2de34f00566..bfc63868ff4 100644 --- a/tests/baselines/reference/aliasUsageInVarAssignment.js +++ b/tests/baselines/reference/aliasUsageInVarAssignment.js @@ -31,8 +31,7 @@ exports.Model = Model; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var Backbone = require("aliasUsageInVarAssignment_backbone"); var VisualizationModel = (function (_super) { diff --git a/tests/baselines/reference/aliasUsageInVarAssignment.types b/tests/baselines/reference/aliasUsageInVarAssignment.types index b5d20a1b372..6a23293ea7c 100644 --- a/tests/baselines/reference/aliasUsageInVarAssignment.types +++ b/tests/baselines/reference/aliasUsageInVarAssignment.types @@ -37,9 +37,9 @@ import Backbone = require("aliasUsageInVarAssignment_backbone"); export class VisualizationModel extends Backbone.Model { >VisualizationModel : VisualizationModel ->Backbone.Model : any +>Backbone.Model : Backbone.Model >Backbone : typeof Backbone ->Model : Backbone.Model +>Model : typeof Backbone.Model // interesting stuff here } diff --git a/tests/baselines/reference/ambiguousOverloadResolution.js b/tests/baselines/reference/ambiguousOverloadResolution.js index 8c2ceb055c7..23c985d2f8d 100644 --- a/tests/baselines/reference/ambiguousOverloadResolution.js +++ b/tests/baselines/reference/ambiguousOverloadResolution.js @@ -12,8 +12,7 @@ var t: number = f(x, x); // Not an error var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var A = (function () { function A() { diff --git a/tests/baselines/reference/apparentTypeSubtyping.js b/tests/baselines/reference/apparentTypeSubtyping.js index 087a91fb02c..edc0f21323a 100644 --- a/tests/baselines/reference/apparentTypeSubtyping.js +++ b/tests/baselines/reference/apparentTypeSubtyping.js @@ -27,8 +27,7 @@ class Derived2 extends Base2 { // error because of the prototy var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var Base = (function () { function Base() { diff --git a/tests/baselines/reference/apparentTypeSupertype.js b/tests/baselines/reference/apparentTypeSupertype.js index 0b4462bebe7..2ab84c89513 100644 --- a/tests/baselines/reference/apparentTypeSupertype.js +++ b/tests/baselines/reference/apparentTypeSupertype.js @@ -17,8 +17,7 @@ class Derived extends Base { // error var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var Base = (function () { function Base() { diff --git a/tests/baselines/reference/argumentsObjectIterator01_ES5.errors.txt b/tests/baselines/reference/argumentsObjectIterator01_ES5.errors.txt new file mode 100644 index 00000000000..d607ab65d29 --- /dev/null +++ b/tests/baselines/reference/argumentsObjectIterator01_ES5.errors.txt @@ -0,0 +1,14 @@ +tests/cases/compiler/argumentsObjectIterator01_ES5.ts(4,21): error TS2495: Type 'IArguments' is not an array type or a string type. + + +==== tests/cases/compiler/argumentsObjectIterator01_ES5.ts (1 errors) ==== + + function doubleAndReturnAsArray(x: number, y: number, z: number): [number, number, number] { + let result = []; + for (let arg of arguments) { + ~~~~~~~~~ +!!! error TS2495: Type 'IArguments' is not an array type or a string type. + result.push(arg + arg); + } + return <[any, any, any]>result; + } \ No newline at end of file diff --git a/tests/baselines/reference/argumentsObjectIterator01_ES5.js b/tests/baselines/reference/argumentsObjectIterator01_ES5.js new file mode 100644 index 00000000000..bc51d6f5582 --- /dev/null +++ b/tests/baselines/reference/argumentsObjectIterator01_ES5.js @@ -0,0 +1,19 @@ +//// [argumentsObjectIterator01_ES5.ts] + +function doubleAndReturnAsArray(x: number, y: number, z: number): [number, number, number] { + let result = []; + for (let arg of arguments) { + result.push(arg + arg); + } + return <[any, any, any]>result; +} + +//// [argumentsObjectIterator01_ES5.js] +function doubleAndReturnAsArray(x, y, z) { + var result = []; + for (var _i = 0; _i < arguments.length; _i++) { + var arg = arguments[_i]; + result.push(arg + arg); + } + return result; +} diff --git a/tests/baselines/reference/argumentsObjectIterator01_ES6.js b/tests/baselines/reference/argumentsObjectIterator01_ES6.js new file mode 100644 index 00000000000..03744f16b99 --- /dev/null +++ b/tests/baselines/reference/argumentsObjectIterator01_ES6.js @@ -0,0 +1,18 @@ +//// [argumentsObjectIterator01_ES6.ts] + +function doubleAndReturnAsArray(x: number, y: number, z: number): [number, number, number] { + let result = []; + for (let arg of arguments) { + result.push(arg + arg); + } + return <[any, any, any]>result; +} + +//// [argumentsObjectIterator01_ES6.js] +function doubleAndReturnAsArray(x, y, z) { + let result = []; + for (let arg of arguments) { + result.push(arg + arg); + } + return result; +} diff --git a/tests/baselines/reference/argumentsObjectIterator01_ES6.symbols b/tests/baselines/reference/argumentsObjectIterator01_ES6.symbols new file mode 100644 index 00000000000..b4351e579f5 --- /dev/null +++ b/tests/baselines/reference/argumentsObjectIterator01_ES6.symbols @@ -0,0 +1,25 @@ +=== tests/cases/compiler/argumentsObjectIterator01_ES6.ts === + +function doubleAndReturnAsArray(x: number, y: number, z: number): [number, number, number] { +>doubleAndReturnAsArray : Symbol(doubleAndReturnAsArray, Decl(argumentsObjectIterator01_ES6.ts, 0, 0)) +>x : Symbol(x, Decl(argumentsObjectIterator01_ES6.ts, 1, 32)) +>y : Symbol(y, Decl(argumentsObjectIterator01_ES6.ts, 1, 42)) +>z : Symbol(z, Decl(argumentsObjectIterator01_ES6.ts, 1, 53)) + + let result = []; +>result : Symbol(result, Decl(argumentsObjectIterator01_ES6.ts, 2, 7)) + + for (let arg of arguments) { +>arg : Symbol(arg, Decl(argumentsObjectIterator01_ES6.ts, 3, 12)) +>arguments : Symbol(arguments) + + result.push(arg + arg); +>result.push : Symbol(Array.push, Decl(lib.d.ts, 1016, 29)) +>result : Symbol(result, Decl(argumentsObjectIterator01_ES6.ts, 2, 7)) +>push : Symbol(Array.push, Decl(lib.d.ts, 1016, 29)) +>arg : Symbol(arg, Decl(argumentsObjectIterator01_ES6.ts, 3, 12)) +>arg : Symbol(arg, Decl(argumentsObjectIterator01_ES6.ts, 3, 12)) + } + return <[any, any, any]>result; +>result : Symbol(result, Decl(argumentsObjectIterator01_ES6.ts, 2, 7)) +} diff --git a/tests/baselines/reference/argumentsObjectIterator01_ES6.types b/tests/baselines/reference/argumentsObjectIterator01_ES6.types new file mode 100644 index 00000000000..04e3bfe081f --- /dev/null +++ b/tests/baselines/reference/argumentsObjectIterator01_ES6.types @@ -0,0 +1,29 @@ +=== tests/cases/compiler/argumentsObjectIterator01_ES6.ts === + +function doubleAndReturnAsArray(x: number, y: number, z: number): [number, number, number] { +>doubleAndReturnAsArray : (x: number, y: number, z: number) => [number, number, number] +>x : number +>y : number +>z : number + + let result = []; +>result : any[] +>[] : undefined[] + + for (let arg of arguments) { +>arg : any +>arguments : IArguments + + result.push(arg + arg); +>result.push(arg + arg) : number +>result.push : (...items: any[]) => number +>result : any[] +>push : (...items: any[]) => number +>arg + arg : any +>arg : any +>arg : any + } + return <[any, any, any]>result; +><[any, any, any]>result : [any, any, any] +>result : any[] +} diff --git a/tests/baselines/reference/argumentsObjectIterator02_ES5.errors.txt b/tests/baselines/reference/argumentsObjectIterator02_ES5.errors.txt new file mode 100644 index 00000000000..125f69b90b2 --- /dev/null +++ b/tests/baselines/reference/argumentsObjectIterator02_ES5.errors.txt @@ -0,0 +1,18 @@ +tests/cases/compiler/argumentsObjectIterator02_ES5.ts(3,26): error TS2304: Cannot find name 'Symbol'. + + +==== tests/cases/compiler/argumentsObjectIterator02_ES5.ts (1 errors) ==== + + function doubleAndReturnAsArray(x: number, y: number, z: number): [number, number, number] { + let blah = arguments[Symbol.iterator]; + ~~~~~~ +!!! error TS2304: Cannot find name 'Symbol'. + + let result = []; + for (let arg of blah()) { + result.push(arg + arg); + } + return <[any, any, any]>result; + } + + \ No newline at end of file diff --git a/tests/baselines/reference/argumentsObjectIterator02_ES5.js b/tests/baselines/reference/argumentsObjectIterator02_ES5.js new file mode 100644 index 00000000000..366bf8de199 --- /dev/null +++ b/tests/baselines/reference/argumentsObjectIterator02_ES5.js @@ -0,0 +1,24 @@ +//// [argumentsObjectIterator02_ES5.ts] + +function doubleAndReturnAsArray(x: number, y: number, z: number): [number, number, number] { + let blah = arguments[Symbol.iterator]; + + let result = []; + for (let arg of blah()) { + result.push(arg + arg); + } + return <[any, any, any]>result; +} + + + +//// [argumentsObjectIterator02_ES5.js] +function doubleAndReturnAsArray(x, y, z) { + var blah = arguments[Symbol.iterator]; + var result = []; + for (var _i = 0, _a = blah(); _i < _a.length; _i++) { + var arg = _a[_i]; + result.push(arg + arg); + } + return result; +} diff --git a/tests/baselines/reference/argumentsObjectIterator02_ES6.js b/tests/baselines/reference/argumentsObjectIterator02_ES6.js new file mode 100644 index 00000000000..9b9415afd29 --- /dev/null +++ b/tests/baselines/reference/argumentsObjectIterator02_ES6.js @@ -0,0 +1,23 @@ +//// [argumentsObjectIterator02_ES6.ts] + +function doubleAndReturnAsArray(x: number, y: number, z: number): [number, number, number] { + let blah = arguments[Symbol.iterator]; + + let result = []; + for (let arg of blah()) { + result.push(arg + arg); + } + return <[any, any, any]>result; +} + + + +//// [argumentsObjectIterator02_ES6.js] +function doubleAndReturnAsArray(x, y, z) { + let blah = arguments[Symbol.iterator]; + let result = []; + for (let arg of blah()) { + result.push(arg + arg); + } + return result; +} diff --git a/tests/baselines/reference/argumentsObjectIterator02_ES6.symbols b/tests/baselines/reference/argumentsObjectIterator02_ES6.symbols new file mode 100644 index 00000000000..9b68573b378 --- /dev/null +++ b/tests/baselines/reference/argumentsObjectIterator02_ES6.symbols @@ -0,0 +1,34 @@ +=== tests/cases/compiler/argumentsObjectIterator02_ES6.ts === + +function doubleAndReturnAsArray(x: number, y: number, z: number): [number, number, number] { +>doubleAndReturnAsArray : Symbol(doubleAndReturnAsArray, Decl(argumentsObjectIterator02_ES6.ts, 0, 0)) +>x : Symbol(x, Decl(argumentsObjectIterator02_ES6.ts, 1, 32)) +>y : Symbol(y, Decl(argumentsObjectIterator02_ES6.ts, 1, 42)) +>z : Symbol(z, Decl(argumentsObjectIterator02_ES6.ts, 1, 53)) + + let blah = arguments[Symbol.iterator]; +>blah : Symbol(blah, Decl(argumentsObjectIterator02_ES6.ts, 2, 7)) +>arguments : Symbol(arguments) +>Symbol.iterator : Symbol(SymbolConstructor.iterator, Decl(lib.d.ts, 1236, 31)) +>Symbol : Symbol(Symbol, Decl(lib.d.ts, 1186, 52), Decl(lib.d.ts, 1292, 11)) +>iterator : Symbol(SymbolConstructor.iterator, Decl(lib.d.ts, 1236, 31)) + + let result = []; +>result : Symbol(result, Decl(argumentsObjectIterator02_ES6.ts, 4, 7)) + + for (let arg of blah()) { +>arg : Symbol(arg, Decl(argumentsObjectIterator02_ES6.ts, 5, 12)) +>blah : Symbol(blah, Decl(argumentsObjectIterator02_ES6.ts, 2, 7)) + + result.push(arg + arg); +>result.push : Symbol(Array.push, Decl(lib.d.ts, 1016, 29)) +>result : Symbol(result, Decl(argumentsObjectIterator02_ES6.ts, 4, 7)) +>push : Symbol(Array.push, Decl(lib.d.ts, 1016, 29)) +>arg : Symbol(arg, Decl(argumentsObjectIterator02_ES6.ts, 5, 12)) +>arg : Symbol(arg, Decl(argumentsObjectIterator02_ES6.ts, 5, 12)) + } + return <[any, any, any]>result; +>result : Symbol(result, Decl(argumentsObjectIterator02_ES6.ts, 4, 7)) +} + + diff --git a/tests/baselines/reference/argumentsObjectIterator02_ES6.types b/tests/baselines/reference/argumentsObjectIterator02_ES6.types new file mode 100644 index 00000000000..3812107f3be --- /dev/null +++ b/tests/baselines/reference/argumentsObjectIterator02_ES6.types @@ -0,0 +1,40 @@ +=== tests/cases/compiler/argumentsObjectIterator02_ES6.ts === + +function doubleAndReturnAsArray(x: number, y: number, z: number): [number, number, number] { +>doubleAndReturnAsArray : (x: number, y: number, z: number) => [number, number, number] +>x : number +>y : number +>z : number + + let blah = arguments[Symbol.iterator]; +>blah : () => IterableIterator +>arguments[Symbol.iterator] : () => IterableIterator +>arguments : IArguments +>Symbol.iterator : symbol +>Symbol : SymbolConstructor +>iterator : symbol + + let result = []; +>result : any[] +>[] : undefined[] + + for (let arg of blah()) { +>arg : any +>blah() : IterableIterator +>blah : () => IterableIterator + + result.push(arg + arg); +>result.push(arg + arg) : number +>result.push : (...items: any[]) => number +>result : any[] +>push : (...items: any[]) => number +>arg + arg : any +>arg : any +>arg : any + } + return <[any, any, any]>result; +><[any, any, any]>result : [any, any, any] +>result : any[] +} + + diff --git a/tests/baselines/reference/argumentsObjectIterator03_ES5.errors.txt b/tests/baselines/reference/argumentsObjectIterator03_ES5.errors.txt new file mode 100644 index 00000000000..c39ea238317 --- /dev/null +++ b/tests/baselines/reference/argumentsObjectIterator03_ES5.errors.txt @@ -0,0 +1,14 @@ +tests/cases/compiler/argumentsObjectIterator03_ES5.ts(3,9): error TS2461: Type 'IArguments' is not an array type. + + +==== tests/cases/compiler/argumentsObjectIterator03_ES5.ts (1 errors) ==== + + function asReversedTuple(a: number, b: string, c: boolean): [boolean, string, number] { + let [x, y, z] = arguments; + ~~~~~~~~~ +!!! error TS2461: Type 'IArguments' is not an array type. + + return [z, y, x]; + } + + \ No newline at end of file diff --git a/tests/baselines/reference/argumentsObjectIterator03_ES5.js b/tests/baselines/reference/argumentsObjectIterator03_ES5.js new file mode 100644 index 00000000000..7ea7e7b6593 --- /dev/null +++ b/tests/baselines/reference/argumentsObjectIterator03_ES5.js @@ -0,0 +1,15 @@ +//// [argumentsObjectIterator03_ES5.ts] + +function asReversedTuple(a: number, b: string, c: boolean): [boolean, string, number] { + let [x, y, z] = arguments; + + return [z, y, x]; +} + + + +//// [argumentsObjectIterator03_ES5.js] +function asReversedTuple(a, b, c) { + var x = arguments[0], y = arguments[1], z = arguments[2]; + return [z, y, x]; +} diff --git a/tests/baselines/reference/argumentsObjectIterator03_ES6.js b/tests/baselines/reference/argumentsObjectIterator03_ES6.js new file mode 100644 index 00000000000..788887e86eb --- /dev/null +++ b/tests/baselines/reference/argumentsObjectIterator03_ES6.js @@ -0,0 +1,15 @@ +//// [argumentsObjectIterator03_ES6.ts] + +function asReversedTuple(a: number, b: string, c: boolean): [boolean, string, number] { + let [x, y, z] = arguments; + + return [z, y, x]; +} + + + +//// [argumentsObjectIterator03_ES6.js] +function asReversedTuple(a, b, c) { + let [x, y, z] = arguments; + return [z, y, x]; +} diff --git a/tests/baselines/reference/argumentsObjectIterator03_ES6.symbols b/tests/baselines/reference/argumentsObjectIterator03_ES6.symbols new file mode 100644 index 00000000000..97677123f35 --- /dev/null +++ b/tests/baselines/reference/argumentsObjectIterator03_ES6.symbols @@ -0,0 +1,21 @@ +=== tests/cases/compiler/argumentsObjectIterator03_ES6.ts === + +function asReversedTuple(a: number, b: string, c: boolean): [boolean, string, number] { +>asReversedTuple : Symbol(asReversedTuple, Decl(argumentsObjectIterator03_ES6.ts, 0, 0)) +>a : Symbol(a, Decl(argumentsObjectIterator03_ES6.ts, 1, 25)) +>b : Symbol(b, Decl(argumentsObjectIterator03_ES6.ts, 1, 35)) +>c : Symbol(c, Decl(argumentsObjectIterator03_ES6.ts, 1, 46)) + + let [x, y, z] = arguments; +>x : Symbol(x, Decl(argumentsObjectIterator03_ES6.ts, 2, 9)) +>y : Symbol(y, Decl(argumentsObjectIterator03_ES6.ts, 2, 11)) +>z : Symbol(z, Decl(argumentsObjectIterator03_ES6.ts, 2, 14)) +>arguments : Symbol(arguments) + + return [z, y, x]; +>z : Symbol(z, Decl(argumentsObjectIterator03_ES6.ts, 2, 14)) +>y : Symbol(y, Decl(argumentsObjectIterator03_ES6.ts, 2, 11)) +>x : Symbol(x, Decl(argumentsObjectIterator03_ES6.ts, 2, 9)) +} + + diff --git a/tests/baselines/reference/argumentsObjectIterator03_ES6.types b/tests/baselines/reference/argumentsObjectIterator03_ES6.types new file mode 100644 index 00000000000..95188dee0c8 --- /dev/null +++ b/tests/baselines/reference/argumentsObjectIterator03_ES6.types @@ -0,0 +1,22 @@ +=== tests/cases/compiler/argumentsObjectIterator03_ES6.ts === + +function asReversedTuple(a: number, b: string, c: boolean): [boolean, string, number] { +>asReversedTuple : (a: number, b: string, c: boolean) => [boolean, string, number] +>a : number +>b : string +>c : boolean + + let [x, y, z] = arguments; +>x : any +>y : any +>z : any +>arguments : IArguments + + return [z, y, x]; +>[z, y, x] : [any, any, any] +>z : any +>y : any +>x : any +} + + diff --git a/tests/baselines/reference/arrayAssignmentTest1.js b/tests/baselines/reference/arrayAssignmentTest1.js index 43aad9921bb..70177b4cba2 100644 --- a/tests/baselines/reference/arrayAssignmentTest1.js +++ b/tests/baselines/reference/arrayAssignmentTest1.js @@ -89,8 +89,7 @@ arr_any = i1; // should be an error - is var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var C1 = (function () { function C1() { diff --git a/tests/baselines/reference/arrayAssignmentTest2.js b/tests/baselines/reference/arrayAssignmentTest2.js index 5aeb74114bc..61bddd7e8e4 100644 --- a/tests/baselines/reference/arrayAssignmentTest2.js +++ b/tests/baselines/reference/arrayAssignmentTest2.js @@ -63,8 +63,7 @@ arr_any = i1; // should be an error - is var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var C1 = (function () { function C1() { diff --git a/tests/baselines/reference/arrayBestCommonTypes.js b/tests/baselines/reference/arrayBestCommonTypes.js index 8d2445e2739..95dd299ad43 100644 --- a/tests/baselines/reference/arrayBestCommonTypes.js +++ b/tests/baselines/reference/arrayBestCommonTypes.js @@ -111,8 +111,7 @@ module NonEmptyTypes { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var EmptyTypes; (function (EmptyTypes) { diff --git a/tests/baselines/reference/arrayLiteralTypeInference.js b/tests/baselines/reference/arrayLiteralTypeInference.js index dfd662bbf1c..fc573aa390e 100644 --- a/tests/baselines/reference/arrayLiteralTypeInference.js +++ b/tests/baselines/reference/arrayLiteralTypeInference.js @@ -55,8 +55,7 @@ var z3: { id: number }[] = var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var Action = (function () { function Action() { diff --git a/tests/baselines/reference/arrayLiterals.js b/tests/baselines/reference/arrayLiterals.js index cb1d25258f2..0f86b7a7f2a 100644 --- a/tests/baselines/reference/arrayLiterals.js +++ b/tests/baselines/reference/arrayLiterals.js @@ -41,8 +41,7 @@ var context4: Base[] = [new Derived1(), new Derived1()]; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var arr1 = [[], [1], ['']]; var arr2 = [[null], [1], ['']]; diff --git a/tests/baselines/reference/arrayLiterals.types b/tests/baselines/reference/arrayLiterals.types index 841de336965..e103241dd0b 100644 --- a/tests/baselines/reference/arrayLiterals.types +++ b/tests/baselines/reference/arrayLiterals.types @@ -2,8 +2,8 @@ // Empty array literal with no contextual type has type Undefined[] var arr1= [[], [1], ['']]; ->arr1 : (string[] | number[])[] ->[[], [1], ['']] : (string[] | number[])[] +>arr1 : (number[] | string[])[] +>[[], [1], ['']] : (number[] | string[])[] >[] : undefined[] >[1] : number[] >1 : number @@ -11,8 +11,8 @@ var arr1= [[], [1], ['']]; >'' : string var arr2 = [[null], [1], ['']]; ->arr2 : (string[] | number[])[] ->[[null], [1], ['']] : (string[] | number[])[] +>arr2 : (number[] | string[])[] +>[[null], [1], ['']] : (number[] | string[])[] >[null] : null[] >null : null >[1] : number[] diff --git a/tests/baselines/reference/arrayLiterals2ES6.symbols b/tests/baselines/reference/arrayLiterals2ES6.symbols index 3b435de2e51..d8717c2c6d2 100644 --- a/tests/baselines/reference/arrayLiterals2ES6.symbols +++ b/tests/baselines/reference/arrayLiterals2ES6.symbols @@ -79,7 +79,7 @@ interface myArray2 extends Array { } >myArray2 : Symbol(myArray2, Decl(arrayLiterals2ES6.ts, 42, 43)) >Array : Symbol(Array, Decl(lib.d.ts, 1000, 23), Decl(lib.d.ts, 1171, 11), Decl(lib.d.ts, 1439, 1)) >Number : Symbol(Number, Decl(lib.d.ts, 456, 40), Decl(lib.d.ts, 518, 11)) ->String : Symbol(String, Decl(lib.d.ts, 275, 1), Decl(lib.d.ts, 443, 11), Decl(lib.d.ts, 1538, 1)) +>String : Symbol(String, Decl(lib.d.ts, 275, 1), Decl(lib.d.ts, 443, 11), Decl(lib.d.ts, 1543, 1)) var d0 = [1, true, ...temp, ]; // has type (string|number|boolean)[] >d0 : Symbol(d0, Decl(arrayLiterals2ES6.ts, 44, 3)) diff --git a/tests/baselines/reference/arrayLiterals3.errors.txt b/tests/baselines/reference/arrayLiterals3.errors.txt index 74cfdb165d7..36714162de0 100644 --- a/tests/baselines/reference/arrayLiterals3.errors.txt +++ b/tests/baselines/reference/arrayLiterals3.errors.txt @@ -8,8 +8,8 @@ tests/cases/conformance/expressions/arrayLiterals/arrayLiterals3.ts(17,5): error Type '() => string | number | boolean' is not assignable to type '() => number'. Type 'string | number | boolean' is not assignable to type 'number'. Type 'string' is not assignable to type 'number'. -tests/cases/conformance/expressions/arrayLiterals/arrayLiterals3.ts(32,5): error TS2322: Type '(string[] | number[])[]' is not assignable to type 'tup'. - Property '0' is missing in type '(string[] | number[])[]'. +tests/cases/conformance/expressions/arrayLiterals/arrayLiterals3.ts(32,5): error TS2322: Type '(number[] | string[])[]' is not assignable to type 'tup'. + Property '0' is missing in type '(number[] | string[])[]'. tests/cases/conformance/expressions/arrayLiterals/arrayLiterals3.ts(33,5): error TS2322: Type 'number[]' is not assignable to type '[number, number, number]'. Property '0' is missing in type 'number[]'. tests/cases/conformance/expressions/arrayLiterals/arrayLiterals3.ts(34,5): error TS2322: Type '(string | number)[]' is not assignable to type 'myArray'. @@ -68,8 +68,8 @@ tests/cases/conformance/expressions/arrayLiterals/arrayLiterals3.ts(34,5): error interface myArray2 extends Array { } var c0: tup = [...temp2]; // Error ~~ -!!! error TS2322: Type '(string[] | number[])[]' is not assignable to type 'tup'. -!!! error TS2322: Property '0' is missing in type '(string[] | number[])[]'. +!!! error TS2322: Type '(number[] | string[])[]' is not assignable to type 'tup'. +!!! error TS2322: Property '0' is missing in type '(number[] | string[])[]'. var c1: [number, number, number] = [...temp1]; // Error cannot assign number[] to [number, number, number] ~~ !!! error TS2322: Type 'number[]' is not assignable to type '[number, number, number]'. diff --git a/tests/baselines/reference/arrayLiteralsWithRecursiveGenerics.js b/tests/baselines/reference/arrayLiteralsWithRecursiveGenerics.js index b3c0a0f7877..e303415df08 100644 --- a/tests/baselines/reference/arrayLiteralsWithRecursiveGenerics.js +++ b/tests/baselines/reference/arrayLiteralsWithRecursiveGenerics.js @@ -29,8 +29,7 @@ var as = [list, myDerivedList]; // List[] var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var List = (function () { function List() { diff --git a/tests/baselines/reference/arrayLiteralsWithRecursiveGenerics.types b/tests/baselines/reference/arrayLiteralsWithRecursiveGenerics.types index 9b2abf25c2d..9cdbe0a0a61 100644 --- a/tests/baselines/reference/arrayLiteralsWithRecursiveGenerics.types +++ b/tests/baselines/reference/arrayLiteralsWithRecursiveGenerics.types @@ -17,7 +17,7 @@ class List { class DerivedList extends List { >DerivedList : DerivedList >U : U ->List : List +>List : List >U : U foo: U; diff --git a/tests/baselines/reference/arrowFunctionContexts.js b/tests/baselines/reference/arrowFunctionContexts.js index f4a11fb47ae..5d862dcec8c 100644 --- a/tests/baselines/reference/arrowFunctionContexts.js +++ b/tests/baselines/reference/arrowFunctionContexts.js @@ -100,8 +100,7 @@ var asserted2: any; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; // Arrow function used in with statement with (window) { diff --git a/tests/baselines/reference/asiPreventsParsingAsAmbientExternalModule01.js b/tests/baselines/reference/asiPreventsParsingAsAmbientExternalModule01.js new file mode 100644 index 00000000000..caf90acae5f --- /dev/null +++ b/tests/baselines/reference/asiPreventsParsingAsAmbientExternalModule01.js @@ -0,0 +1,17 @@ +//// [asiPreventsParsingAsAmbientExternalModule01.ts] + +var declare: number; +var module: string; + +declare // this is the identifier 'declare' +module // this is the identifier 'module' +"my external module" // this is just a string +{ } // this is a block body + +//// [asiPreventsParsingAsAmbientExternalModule01.js] +var declare; +var module; +declare; // this is the identifier 'declare' +module; // this is the identifier 'module' +"my external module"; // this is just a string +{ } // this is a block body diff --git a/tests/baselines/reference/asiPreventsParsingAsAmbientExternalModule01.symbols b/tests/baselines/reference/asiPreventsParsingAsAmbientExternalModule01.symbols new file mode 100644 index 00000000000..c35432b7ece --- /dev/null +++ b/tests/baselines/reference/asiPreventsParsingAsAmbientExternalModule01.symbols @@ -0,0 +1,16 @@ +=== tests/cases/conformance/externalModules/asiPreventsParsingAsAmbientExternalModule01.ts === + +var declare: number; +>declare : Symbol(declare, Decl(asiPreventsParsingAsAmbientExternalModule01.ts, 1, 3)) + +var module: string; +>module : Symbol(module, Decl(asiPreventsParsingAsAmbientExternalModule01.ts, 2, 3)) + +declare // this is the identifier 'declare' +>declare : Symbol(declare, Decl(asiPreventsParsingAsAmbientExternalModule01.ts, 1, 3)) + +module // this is the identifier 'module' +>module : Symbol(module, Decl(asiPreventsParsingAsAmbientExternalModule01.ts, 2, 3)) + +"my external module" // this is just a string +{ } // this is a block body diff --git a/tests/baselines/reference/asiPreventsParsingAsAmbientExternalModule01.types b/tests/baselines/reference/asiPreventsParsingAsAmbientExternalModule01.types new file mode 100644 index 00000000000..3e6aade9a21 --- /dev/null +++ b/tests/baselines/reference/asiPreventsParsingAsAmbientExternalModule01.types @@ -0,0 +1,18 @@ +=== tests/cases/conformance/externalModules/asiPreventsParsingAsAmbientExternalModule01.ts === + +var declare: number; +>declare : number + +var module: string; +>module : string + +declare // this is the identifier 'declare' +>declare : number + +module // this is the identifier 'module' +>module : string + +"my external module" // this is just a string +>"my external module" : string + +{ } // this is a block body diff --git a/tests/baselines/reference/asiPreventsParsingAsAmbientExternalModule02.js b/tests/baselines/reference/asiPreventsParsingAsAmbientExternalModule02.js new file mode 100644 index 00000000000..20e2693ba7f --- /dev/null +++ b/tests/baselines/reference/asiPreventsParsingAsAmbientExternalModule02.js @@ -0,0 +1,22 @@ +//// [asiPreventsParsingAsAmbientExternalModule02.ts] + +var declare: number; +var module: string; + +module container { + declare // this is the identifier 'declare' + module // this is the identifier 'module' + "my external module" // this is just a string + { } // this is a block body +} + +//// [asiPreventsParsingAsAmbientExternalModule02.js] +var declare; +var module; +var container; +(function (container) { + declare; // this is the identifier 'declare' + module; // this is the identifier 'module' + "my external module"; // this is just a string + { } // this is a block body +})(container || (container = {})); diff --git a/tests/baselines/reference/asiPreventsParsingAsAmbientExternalModule02.symbols b/tests/baselines/reference/asiPreventsParsingAsAmbientExternalModule02.symbols new file mode 100644 index 00000000000..ed97f39fc11 --- /dev/null +++ b/tests/baselines/reference/asiPreventsParsingAsAmbientExternalModule02.symbols @@ -0,0 +1,20 @@ +=== tests/cases/conformance/externalModules/asiPreventsParsingAsAmbientExternalModule02.ts === + +var declare: number; +>declare : Symbol(declare, Decl(asiPreventsParsingAsAmbientExternalModule02.ts, 1, 3)) + +var module: string; +>module : Symbol(module, Decl(asiPreventsParsingAsAmbientExternalModule02.ts, 2, 3)) + +module container { +>container : Symbol(container, Decl(asiPreventsParsingAsAmbientExternalModule02.ts, 2, 19)) + + declare // this is the identifier 'declare' +>declare : Symbol(declare, Decl(asiPreventsParsingAsAmbientExternalModule02.ts, 1, 3)) + + module // this is the identifier 'module' +>module : Symbol(module, Decl(asiPreventsParsingAsAmbientExternalModule02.ts, 2, 3)) + + "my external module" // this is just a string + { } // this is a block body +} diff --git a/tests/baselines/reference/asiPreventsParsingAsAmbientExternalModule02.types b/tests/baselines/reference/asiPreventsParsingAsAmbientExternalModule02.types new file mode 100644 index 00000000000..67671853993 --- /dev/null +++ b/tests/baselines/reference/asiPreventsParsingAsAmbientExternalModule02.types @@ -0,0 +1,22 @@ +=== tests/cases/conformance/externalModules/asiPreventsParsingAsAmbientExternalModule02.ts === + +var declare: number; +>declare : number + +var module: string; +>module : string + +module container { +>container : typeof container + + declare // this is the identifier 'declare' +>declare : number + + module // this is the identifier 'module' +>module : string + + "my external module" // this is just a string +>"my external module" : string + + { } // this is a block body +} diff --git a/tests/baselines/reference/asiPreventsParsingAsInterface01.js b/tests/baselines/reference/asiPreventsParsingAsInterface01.js new file mode 100644 index 00000000000..024ad54371f --- /dev/null +++ b/tests/baselines/reference/asiPreventsParsingAsInterface01.js @@ -0,0 +1,13 @@ +//// [asiPreventsParsingAsInterface01.ts] + +var interface: number, I: string; + +interface // This should be the identifier 'interface' +I // This should be the identifier 'I' +{} // This should be a block body + +//// [asiPreventsParsingAsInterface01.js] +var interface, I; +interface; // This should be the identifier 'interface' +I; // This should be the identifier 'I' +{ } // This should be a block body diff --git a/tests/baselines/reference/asiPreventsParsingAsInterface01.symbols b/tests/baselines/reference/asiPreventsParsingAsInterface01.symbols new file mode 100644 index 00000000000..d92c13e8ceb --- /dev/null +++ b/tests/baselines/reference/asiPreventsParsingAsInterface01.symbols @@ -0,0 +1,13 @@ +=== tests/cases/conformance/interfaces/interfaceDeclarations/asiPreventsParsingAsInterface01.ts === + +var interface: number, I: string; +>interface : Symbol(interface, Decl(asiPreventsParsingAsInterface01.ts, 1, 3)) +>I : Symbol(I, Decl(asiPreventsParsingAsInterface01.ts, 1, 22)) + +interface // This should be the identifier 'interface' +>interface : Symbol(interface, Decl(asiPreventsParsingAsInterface01.ts, 1, 3)) + +I // This should be the identifier 'I' +>I : Symbol(I, Decl(asiPreventsParsingAsInterface01.ts, 1, 22)) + +{} // This should be a block body diff --git a/tests/baselines/reference/asiPreventsParsingAsInterface01.types b/tests/baselines/reference/asiPreventsParsingAsInterface01.types new file mode 100644 index 00000000000..03c1b9fc412 --- /dev/null +++ b/tests/baselines/reference/asiPreventsParsingAsInterface01.types @@ -0,0 +1,13 @@ +=== tests/cases/conformance/interfaces/interfaceDeclarations/asiPreventsParsingAsInterface01.ts === + +var interface: number, I: string; +>interface : number +>I : string + +interface // This should be the identifier 'interface' +>interface : number + +I // This should be the identifier 'I' +>I : string + +{} // This should be a block body diff --git a/tests/baselines/reference/asiPreventsParsingAsInterface02.js b/tests/baselines/reference/asiPreventsParsingAsInterface02.js new file mode 100644 index 00000000000..0ea0421550a --- /dev/null +++ b/tests/baselines/reference/asiPreventsParsingAsInterface02.js @@ -0,0 +1,14 @@ +//// [asiPreventsParsingAsInterface02.ts] + +function f(interface: number, I: string) { + interface // This should be the identifier 'interface' + I // This should be the identifier 'I' + {} // This should be a block body +} + +//// [asiPreventsParsingAsInterface02.js] +function f(interface, I) { + interface; // This should be the identifier 'interface' + I; // This should be the identifier 'I' + { } // This should be a block body +} diff --git a/tests/baselines/reference/asiPreventsParsingAsInterface02.symbols b/tests/baselines/reference/asiPreventsParsingAsInterface02.symbols new file mode 100644 index 00000000000..e1e4febe38c --- /dev/null +++ b/tests/baselines/reference/asiPreventsParsingAsInterface02.symbols @@ -0,0 +1,15 @@ +=== tests/cases/conformance/interfaces/interfaceDeclarations/asiPreventsParsingAsInterface02.ts === + +function f(interface: number, I: string) { +>f : Symbol(f, Decl(asiPreventsParsingAsInterface02.ts, 0, 0)) +>interface : Symbol(interface, Decl(asiPreventsParsingAsInterface02.ts, 1, 11)) +>I : Symbol(I, Decl(asiPreventsParsingAsInterface02.ts, 1, 29)) + + interface // This should be the identifier 'interface' +>interface : Symbol(interface, Decl(asiPreventsParsingAsInterface02.ts, 1, 11)) + + I // This should be the identifier 'I' +>I : Symbol(I, Decl(asiPreventsParsingAsInterface02.ts, 1, 29)) + + {} // This should be a block body +} diff --git a/tests/baselines/reference/asiPreventsParsingAsInterface02.types b/tests/baselines/reference/asiPreventsParsingAsInterface02.types new file mode 100644 index 00000000000..7989cc810a8 --- /dev/null +++ b/tests/baselines/reference/asiPreventsParsingAsInterface02.types @@ -0,0 +1,15 @@ +=== tests/cases/conformance/interfaces/interfaceDeclarations/asiPreventsParsingAsInterface02.ts === + +function f(interface: number, I: string) { +>f : (interface: number, I: string) => void +>interface : number +>I : string + + interface // This should be the identifier 'interface' +>interface : number + + I // This should be the identifier 'I' +>I : string + + {} // This should be a block body +} diff --git a/tests/baselines/reference/asiPreventsParsingAsInterface03.js b/tests/baselines/reference/asiPreventsParsingAsInterface03.js new file mode 100644 index 00000000000..3b3c836f7f4 --- /dev/null +++ b/tests/baselines/reference/asiPreventsParsingAsInterface03.js @@ -0,0 +1,18 @@ +//// [asiPreventsParsingAsInterface03.ts] + +var interface: number, I: string; + +namespace n { + interface // This should be the identifier 'interface' + I // This should be the identifier 'I' + {} // This should be a block body +} + +//// [asiPreventsParsingAsInterface03.js] +var interface, I; +var n; +(function (n) { + interface; // This should be the identifier 'interface' + I; // This should be the identifier 'I' + { } // This should be a block body +})(n || (n = {})); diff --git a/tests/baselines/reference/asiPreventsParsingAsInterface03.symbols b/tests/baselines/reference/asiPreventsParsingAsInterface03.symbols new file mode 100644 index 00000000000..e8c95cf1244 --- /dev/null +++ b/tests/baselines/reference/asiPreventsParsingAsInterface03.symbols @@ -0,0 +1,17 @@ +=== tests/cases/conformance/interfaces/interfaceDeclarations/asiPreventsParsingAsInterface03.ts === + +var interface: number, I: string; +>interface : Symbol(interface, Decl(asiPreventsParsingAsInterface03.ts, 1, 3)) +>I : Symbol(I, Decl(asiPreventsParsingAsInterface03.ts, 1, 22)) + +namespace n { +>n : Symbol(n, Decl(asiPreventsParsingAsInterface03.ts, 1, 33)) + + interface // This should be the identifier 'interface' +>interface : Symbol(interface, Decl(asiPreventsParsingAsInterface03.ts, 1, 3)) + + I // This should be the identifier 'I' +>I : Symbol(I, Decl(asiPreventsParsingAsInterface03.ts, 1, 22)) + + {} // This should be a block body +} diff --git a/tests/baselines/reference/asiPreventsParsingAsInterface03.types b/tests/baselines/reference/asiPreventsParsingAsInterface03.types new file mode 100644 index 00000000000..a58d502fc25 --- /dev/null +++ b/tests/baselines/reference/asiPreventsParsingAsInterface03.types @@ -0,0 +1,17 @@ +=== tests/cases/conformance/interfaces/interfaceDeclarations/asiPreventsParsingAsInterface03.ts === + +var interface: number, I: string; +>interface : number +>I : string + +namespace n { +>n : typeof n + + interface // This should be the identifier 'interface' +>interface : number + + I // This should be the identifier 'I' +>I : string + + {} // This should be a block body +} diff --git a/tests/baselines/reference/asiPreventsParsingAsInterface04.js b/tests/baselines/reference/asiPreventsParsingAsInterface04.js new file mode 100644 index 00000000000..1700636e522 --- /dev/null +++ b/tests/baselines/reference/asiPreventsParsingAsInterface04.js @@ -0,0 +1,15 @@ +//// [asiPreventsParsingAsInterface04.ts] + +var declare: boolean, interface: number, I: string; + +declare // This should be the identifier 'declare' +interface // This should be the identifier 'interface' +I // This should be the identifier 'I' +{} // This should be a block body + +//// [asiPreventsParsingAsInterface04.js] +var declare, interface, I; +declare; // This should be the identifier 'declare' +interface; // This should be the identifier 'interface' +I; // This should be the identifier 'I' +{ } // This should be a block body diff --git a/tests/baselines/reference/asiPreventsParsingAsInterface04.symbols b/tests/baselines/reference/asiPreventsParsingAsInterface04.symbols new file mode 100644 index 00000000000..094411ebed5 --- /dev/null +++ b/tests/baselines/reference/asiPreventsParsingAsInterface04.symbols @@ -0,0 +1,17 @@ +=== tests/cases/conformance/interfaces/interfaceDeclarations/asiPreventsParsingAsInterface04.ts === + +var declare: boolean, interface: number, I: string; +>declare : Symbol(declare, Decl(asiPreventsParsingAsInterface04.ts, 1, 3)) +>interface : Symbol(interface, Decl(asiPreventsParsingAsInterface04.ts, 1, 21)) +>I : Symbol(I, Decl(asiPreventsParsingAsInterface04.ts, 1, 40)) + +declare // This should be the identifier 'declare' +>declare : Symbol(declare, Decl(asiPreventsParsingAsInterface04.ts, 1, 3)) + +interface // This should be the identifier 'interface' +>interface : Symbol(interface, Decl(asiPreventsParsingAsInterface04.ts, 1, 21)) + +I // This should be the identifier 'I' +>I : Symbol(I, Decl(asiPreventsParsingAsInterface04.ts, 1, 40)) + +{} // This should be a block body diff --git a/tests/baselines/reference/asiPreventsParsingAsInterface04.types b/tests/baselines/reference/asiPreventsParsingAsInterface04.types new file mode 100644 index 00000000000..f6d29749ae1 --- /dev/null +++ b/tests/baselines/reference/asiPreventsParsingAsInterface04.types @@ -0,0 +1,17 @@ +=== tests/cases/conformance/interfaces/interfaceDeclarations/asiPreventsParsingAsInterface04.ts === + +var declare: boolean, interface: number, I: string; +>declare : boolean +>interface : number +>I : string + +declare // This should be the identifier 'declare' +>declare : boolean + +interface // This should be the identifier 'interface' +>interface : number + +I // This should be the identifier 'I' +>I : string + +{} // This should be a block body diff --git a/tests/baselines/reference/asiPreventsParsingAsInterface05.errors.txt b/tests/baselines/reference/asiPreventsParsingAsInterface05.errors.txt new file mode 100644 index 00000000000..e070305fdf8 --- /dev/null +++ b/tests/baselines/reference/asiPreventsParsingAsInterface05.errors.txt @@ -0,0 +1,24 @@ +tests/cases/conformance/interfaces/interfaceDeclarations/asiPreventsParsingAsInterface05.ts(3,5): error TS1212: Identifier expected. 'interface' is a reserved word in strict mode +tests/cases/conformance/interfaces/interfaceDeclarations/asiPreventsParsingAsInterface05.ts(10,1): error TS1212: Identifier expected. 'interface' is a reserved word in strict mode +tests/cases/conformance/interfaces/interfaceDeclarations/asiPreventsParsingAsInterface05.ts(11,1): error TS2304: Cannot find name 'I'. + + +==== tests/cases/conformance/interfaces/interfaceDeclarations/asiPreventsParsingAsInterface05.ts (3 errors) ==== + "use strict" + + var interface: number; + ~~~~~~~~~ +!!! error TS1212: Identifier expected. 'interface' is a reserved word in strict mode + + // 'interface' is a strict mode reserved word, and so it would be permissible + // to allow 'interface' and the name of the interface to be on separate lines; + // however, this complicates things, and so it is preferable to restrict interface + // declarations such that their identifier must follow 'interface' on the same line. + + interface // This should be the identifier 'interface' + ~~~~~~~~~ +!!! error TS1212: Identifier expected. 'interface' is a reserved word in strict mode + I // This should be the identifier 'I' + ~ +!!! error TS2304: Cannot find name 'I'. + { } // This should be a block body \ No newline at end of file diff --git a/tests/baselines/reference/asiPreventsParsingAsInterface05.js b/tests/baselines/reference/asiPreventsParsingAsInterface05.js new file mode 100644 index 00000000000..85c19be4473 --- /dev/null +++ b/tests/baselines/reference/asiPreventsParsingAsInterface05.js @@ -0,0 +1,24 @@ +//// [asiPreventsParsingAsInterface05.ts] +"use strict" + +var interface: number; + +// 'interface' is a strict mode reserved word, and so it would be permissible +// to allow 'interface' and the name of the interface to be on separate lines; +// however, this complicates things, and so it is preferable to restrict interface +// declarations such that their identifier must follow 'interface' on the same line. + +interface // This should be the identifier 'interface' +I // This should be the identifier 'I' +{ } // This should be a block body + +//// [asiPreventsParsingAsInterface05.js] +"use strict"; +var interface; +// 'interface' is a strict mode reserved word, and so it would be permissible +// to allow 'interface' and the name of the interface to be on separate lines; +// however, this complicates things, and so it is preferable to restrict interface +// declarations such that their identifier must follow 'interface' on the same line. +interface; // This should be the identifier 'interface' +I; // This should be the identifier 'I' +{ } // This should be a block body diff --git a/tests/baselines/reference/asiPreventsParsingAsNamespace01.js b/tests/baselines/reference/asiPreventsParsingAsNamespace01.js new file mode 100644 index 00000000000..282d9dd1c7c --- /dev/null +++ b/tests/baselines/reference/asiPreventsParsingAsNamespace01.js @@ -0,0 +1,15 @@ +//// [asiPreventsParsingAsNamespace01.ts] + +var namespace: number; +var n: string; + +namespace // this is the identifier 'namespace' +n // this is the identifier 'n' +{ } // this is a block body + +//// [asiPreventsParsingAsNamespace01.js] +var namespace; +var n; +namespace; // this is the identifier 'namespace' +n; // this is the identifier 'n' +{ } // this is a block body diff --git a/tests/baselines/reference/asiPreventsParsingAsNamespace01.symbols b/tests/baselines/reference/asiPreventsParsingAsNamespace01.symbols new file mode 100644 index 00000000000..b196d733352 --- /dev/null +++ b/tests/baselines/reference/asiPreventsParsingAsNamespace01.symbols @@ -0,0 +1,15 @@ +=== tests/cases/conformance/internalModules/moduleDeclarations/asiPreventsParsingAsNamespace01.ts === + +var namespace: number; +>namespace : Symbol(namespace, Decl(asiPreventsParsingAsNamespace01.ts, 1, 3)) + +var n: string; +>n : Symbol(n, Decl(asiPreventsParsingAsNamespace01.ts, 2, 3)) + +namespace // this is the identifier 'namespace' +>namespace : Symbol(namespace, Decl(asiPreventsParsingAsNamespace01.ts, 1, 3)) + +n // this is the identifier 'n' +>n : Symbol(n, Decl(asiPreventsParsingAsNamespace01.ts, 2, 3)) + +{ } // this is a block body diff --git a/tests/baselines/reference/asiPreventsParsingAsNamespace01.types b/tests/baselines/reference/asiPreventsParsingAsNamespace01.types new file mode 100644 index 00000000000..417a96dbed4 --- /dev/null +++ b/tests/baselines/reference/asiPreventsParsingAsNamespace01.types @@ -0,0 +1,15 @@ +=== tests/cases/conformance/internalModules/moduleDeclarations/asiPreventsParsingAsNamespace01.ts === + +var namespace: number; +>namespace : number + +var n: string; +>n : string + +namespace // this is the identifier 'namespace' +>namespace : number + +n // this is the identifier 'n' +>n : string + +{ } // this is a block body diff --git a/tests/baselines/reference/asiPreventsParsingAsNamespace02.js b/tests/baselines/reference/asiPreventsParsingAsNamespace02.js new file mode 100644 index 00000000000..514a026dc78 --- /dev/null +++ b/tests/baselines/reference/asiPreventsParsingAsNamespace02.js @@ -0,0 +1,15 @@ +//// [asiPreventsParsingAsNamespace02.ts] + +var module: number; +var m: string; + +module // this is the identifier 'namespace' +m // this is the identifier 'm' +{ } // this is a block body + +//// [asiPreventsParsingAsNamespace02.js] +var module; +var m; +module; // this is the identifier 'namespace' +m; // this is the identifier 'm' +{ } // this is a block body diff --git a/tests/baselines/reference/asiPreventsParsingAsNamespace02.symbols b/tests/baselines/reference/asiPreventsParsingAsNamespace02.symbols new file mode 100644 index 00000000000..a3bb37c73bc --- /dev/null +++ b/tests/baselines/reference/asiPreventsParsingAsNamespace02.symbols @@ -0,0 +1,15 @@ +=== tests/cases/conformance/internalModules/moduleDeclarations/asiPreventsParsingAsNamespace02.ts === + +var module: number; +>module : Symbol(module, Decl(asiPreventsParsingAsNamespace02.ts, 1, 3)) + +var m: string; +>m : Symbol(m, Decl(asiPreventsParsingAsNamespace02.ts, 2, 3)) + +module // this is the identifier 'namespace' +>module : Symbol(module, Decl(asiPreventsParsingAsNamespace02.ts, 1, 3)) + +m // this is the identifier 'm' +>m : Symbol(m, Decl(asiPreventsParsingAsNamespace02.ts, 2, 3)) + +{ } // this is a block body diff --git a/tests/baselines/reference/asiPreventsParsingAsNamespace02.types b/tests/baselines/reference/asiPreventsParsingAsNamespace02.types new file mode 100644 index 00000000000..e9e1433be7a --- /dev/null +++ b/tests/baselines/reference/asiPreventsParsingAsNamespace02.types @@ -0,0 +1,15 @@ +=== tests/cases/conformance/internalModules/moduleDeclarations/asiPreventsParsingAsNamespace02.ts === + +var module: number; +>module : number + +var m: string; +>m : string + +module // this is the identifier 'namespace' +>module : number + +m // this is the identifier 'm' +>m : string + +{ } // this is a block body diff --git a/tests/baselines/reference/asiPreventsParsingAsNamespace03.js b/tests/baselines/reference/asiPreventsParsingAsNamespace03.js new file mode 100644 index 00000000000..3c27694f5ce --- /dev/null +++ b/tests/baselines/reference/asiPreventsParsingAsNamespace03.js @@ -0,0 +1,20 @@ +//// [asiPreventsParsingAsNamespace03.ts] + +var namespace: number; +var n: string; + +namespace container { + namespace // this is the identifier 'namespace' + n // this is the identifier 'n' + { } // this is a block body +} + +//// [asiPreventsParsingAsNamespace03.js] +var namespace; +var n; +var container; +(function (container) { + namespace; // this is the identifier 'namespace' + n; // this is the identifier 'n' + { } // this is a block body +})(container || (container = {})); diff --git a/tests/baselines/reference/asiPreventsParsingAsNamespace03.symbols b/tests/baselines/reference/asiPreventsParsingAsNamespace03.symbols new file mode 100644 index 00000000000..e77d012a1bf --- /dev/null +++ b/tests/baselines/reference/asiPreventsParsingAsNamespace03.symbols @@ -0,0 +1,19 @@ +=== tests/cases/conformance/internalModules/moduleDeclarations/asiPreventsParsingAsNamespace03.ts === + +var namespace: number; +>namespace : Symbol(namespace, Decl(asiPreventsParsingAsNamespace03.ts, 1, 3)) + +var n: string; +>n : Symbol(n, Decl(asiPreventsParsingAsNamespace03.ts, 2, 3)) + +namespace container { +>container : Symbol(container, Decl(asiPreventsParsingAsNamespace03.ts, 2, 14)) + + namespace // this is the identifier 'namespace' +>namespace : Symbol(namespace, Decl(asiPreventsParsingAsNamespace03.ts, 1, 3)) + + n // this is the identifier 'n' +>n : Symbol(n, Decl(asiPreventsParsingAsNamespace03.ts, 2, 3)) + + { } // this is a block body +} diff --git a/tests/baselines/reference/asiPreventsParsingAsNamespace03.types b/tests/baselines/reference/asiPreventsParsingAsNamespace03.types new file mode 100644 index 00000000000..f119a789e11 --- /dev/null +++ b/tests/baselines/reference/asiPreventsParsingAsNamespace03.types @@ -0,0 +1,19 @@ +=== tests/cases/conformance/internalModules/moduleDeclarations/asiPreventsParsingAsNamespace03.ts === + +var namespace: number; +>namespace : number + +var n: string; +>n : string + +namespace container { +>container : typeof container + + namespace // this is the identifier 'namespace' +>namespace : number + + n // this is the identifier 'n' +>n : string + + { } // this is a block body +} diff --git a/tests/baselines/reference/asiPreventsParsingAsNamespace04.js b/tests/baselines/reference/asiPreventsParsingAsNamespace04.js new file mode 100644 index 00000000000..704c8893e76 --- /dev/null +++ b/tests/baselines/reference/asiPreventsParsingAsNamespace04.js @@ -0,0 +1,8 @@ +//// [asiPreventsParsingAsNamespace04.ts] + +let module = 10; +module in {} + +//// [asiPreventsParsingAsNamespace04.js] +var module = 10; +module in {}; diff --git a/tests/baselines/reference/asiPreventsParsingAsNamespace04.symbols b/tests/baselines/reference/asiPreventsParsingAsNamespace04.symbols new file mode 100644 index 00000000000..60d1f8fcc48 --- /dev/null +++ b/tests/baselines/reference/asiPreventsParsingAsNamespace04.symbols @@ -0,0 +1,8 @@ +=== tests/cases/conformance/internalModules/moduleDeclarations/asiPreventsParsingAsNamespace04.ts === + +let module = 10; +>module : Symbol(module, Decl(asiPreventsParsingAsNamespace04.ts, 1, 3)) + +module in {} +>module : Symbol(module, Decl(asiPreventsParsingAsNamespace04.ts, 1, 3)) + diff --git a/tests/baselines/reference/asiPreventsParsingAsNamespace04.types b/tests/baselines/reference/asiPreventsParsingAsNamespace04.types new file mode 100644 index 00000000000..3fa2a448cf9 --- /dev/null +++ b/tests/baselines/reference/asiPreventsParsingAsNamespace04.types @@ -0,0 +1,11 @@ +=== tests/cases/conformance/internalModules/moduleDeclarations/asiPreventsParsingAsNamespace04.ts === + +let module = 10; +>module : number +>10 : number + +module in {} +>module in {} : boolean +>module : number +>{} : {} + diff --git a/tests/baselines/reference/asiPreventsParsingAsNamespace05.js b/tests/baselines/reference/asiPreventsParsingAsNamespace05.js new file mode 100644 index 00000000000..35f557328c0 --- /dev/null +++ b/tests/baselines/reference/asiPreventsParsingAsNamespace05.js @@ -0,0 +1,25 @@ +//// [asiPreventsParsingAsNamespace05.ts] + +let namespace = 10; +namespace a.b { + export let c = 20; +} + +namespace +a.b.c +{ +} + +//// [asiPreventsParsingAsNamespace05.js] +var namespace = 10; +var a; +(function (a) { + var b; + (function (b) { + b.c = 20; + })(b = a.b || (a.b = {})); +})(a || (a = {})); +namespace; +a.b.c; +{ +} diff --git a/tests/baselines/reference/asiPreventsParsingAsNamespace05.symbols b/tests/baselines/reference/asiPreventsParsingAsNamespace05.symbols new file mode 100644 index 00000000000..47f05862b0a --- /dev/null +++ b/tests/baselines/reference/asiPreventsParsingAsNamespace05.symbols @@ -0,0 +1,24 @@ +=== tests/cases/conformance/internalModules/moduleDeclarations/asiPreventsParsingAsNamespace05.ts === + +let namespace = 10; +>namespace : Symbol(namespace, Decl(asiPreventsParsingAsNamespace05.ts, 1, 3)) + +namespace a.b { +>a : Symbol(a, Decl(asiPreventsParsingAsNamespace05.ts, 1, 19)) +>b : Symbol(b, Decl(asiPreventsParsingAsNamespace05.ts, 2, 12)) + + export let c = 20; +>c : Symbol(c, Decl(asiPreventsParsingAsNamespace05.ts, 3, 14)) +} + +namespace +>namespace : Symbol(namespace, Decl(asiPreventsParsingAsNamespace05.ts, 1, 3)) + +a.b.c +>a.b.c : Symbol(a.b.c, Decl(asiPreventsParsingAsNamespace05.ts, 3, 14)) +>a.b : Symbol(a.b, Decl(asiPreventsParsingAsNamespace05.ts, 2, 12)) +>a : Symbol(a, Decl(asiPreventsParsingAsNamespace05.ts, 1, 19)) +>b : Symbol(a.b, Decl(asiPreventsParsingAsNamespace05.ts, 2, 12)) +>c : Symbol(a.b.c, Decl(asiPreventsParsingAsNamespace05.ts, 3, 14)) +{ +} diff --git a/tests/baselines/reference/asiPreventsParsingAsNamespace05.types b/tests/baselines/reference/asiPreventsParsingAsNamespace05.types new file mode 100644 index 00000000000..515147c1096 --- /dev/null +++ b/tests/baselines/reference/asiPreventsParsingAsNamespace05.types @@ -0,0 +1,26 @@ +=== tests/cases/conformance/internalModules/moduleDeclarations/asiPreventsParsingAsNamespace05.ts === + +let namespace = 10; +>namespace : number +>10 : number + +namespace a.b { +>a : typeof a +>b : typeof b + + export let c = 20; +>c : number +>20 : number +} + +namespace +>namespace : number + +a.b.c +>a.b.c : number +>a.b : typeof a.b +>a : typeof a +>b : typeof a.b +>c : number +{ +} diff --git a/tests/baselines/reference/asiPreventsParsingAsTypeAlias01.js b/tests/baselines/reference/asiPreventsParsingAsTypeAlias01.js new file mode 100644 index 00000000000..b05988290cb --- /dev/null +++ b/tests/baselines/reference/asiPreventsParsingAsTypeAlias01.js @@ -0,0 +1,15 @@ +//// [asiPreventsParsingAsTypeAlias01.ts] + +var type; +var string; +var Foo; + +type +Foo = string; + +//// [asiPreventsParsingAsTypeAlias01.js] +var type; +var string; +var Foo; +type; +Foo = string; diff --git a/tests/baselines/reference/asiPreventsParsingAsTypeAlias01.symbols b/tests/baselines/reference/asiPreventsParsingAsTypeAlias01.symbols new file mode 100644 index 00000000000..fa82d53ac70 --- /dev/null +++ b/tests/baselines/reference/asiPreventsParsingAsTypeAlias01.symbols @@ -0,0 +1,18 @@ +=== tests/cases/conformance/types/typeAliases/asiPreventsParsingAsTypeAlias01.ts === + +var type; +>type : Symbol(type, Decl(asiPreventsParsingAsTypeAlias01.ts, 1, 3)) + +var string; +>string : Symbol(string, Decl(asiPreventsParsingAsTypeAlias01.ts, 2, 3)) + +var Foo; +>Foo : Symbol(Foo, Decl(asiPreventsParsingAsTypeAlias01.ts, 3, 3)) + +type +>type : Symbol(type, Decl(asiPreventsParsingAsTypeAlias01.ts, 1, 3)) + +Foo = string; +>Foo : Symbol(Foo, Decl(asiPreventsParsingAsTypeAlias01.ts, 3, 3)) +>string : Symbol(string, Decl(asiPreventsParsingAsTypeAlias01.ts, 2, 3)) + diff --git a/tests/baselines/reference/asiPreventsParsingAsTypeAlias01.types b/tests/baselines/reference/asiPreventsParsingAsTypeAlias01.types new file mode 100644 index 00000000000..7492a698e3a --- /dev/null +++ b/tests/baselines/reference/asiPreventsParsingAsTypeAlias01.types @@ -0,0 +1,19 @@ +=== tests/cases/conformance/types/typeAliases/asiPreventsParsingAsTypeAlias01.ts === + +var type; +>type : any + +var string; +>string : any + +var Foo; +>Foo : any + +type +>type : any + +Foo = string; +>Foo = string : any +>Foo : any +>string : any + diff --git a/tests/baselines/reference/asiPreventsParsingAsTypeAlias02.js b/tests/baselines/reference/asiPreventsParsingAsTypeAlias02.js new file mode 100644 index 00000000000..eae9898c8d4 --- /dev/null +++ b/tests/baselines/reference/asiPreventsParsingAsTypeAlias02.js @@ -0,0 +1,20 @@ +//// [asiPreventsParsingAsTypeAlias02.ts] + +var type; +var string; +var Foo; + +namespace container { + type + Foo = string; +} + +//// [asiPreventsParsingAsTypeAlias02.js] +var type; +var string; +var Foo; +var container; +(function (container) { + type; + Foo = string; +})(container || (container = {})); diff --git a/tests/baselines/reference/asiPreventsParsingAsTypeAlias02.symbols b/tests/baselines/reference/asiPreventsParsingAsTypeAlias02.symbols new file mode 100644 index 00000000000..4b83dba4c5d --- /dev/null +++ b/tests/baselines/reference/asiPreventsParsingAsTypeAlias02.symbols @@ -0,0 +1,21 @@ +=== tests/cases/conformance/types/typeAliases/asiPreventsParsingAsTypeAlias02.ts === + +var type; +>type : Symbol(type, Decl(asiPreventsParsingAsTypeAlias02.ts, 1, 3)) + +var string; +>string : Symbol(string, Decl(asiPreventsParsingAsTypeAlias02.ts, 2, 3)) + +var Foo; +>Foo : Symbol(Foo, Decl(asiPreventsParsingAsTypeAlias02.ts, 3, 3)) + +namespace container { +>container : Symbol(container, Decl(asiPreventsParsingAsTypeAlias02.ts, 3, 8)) + + type +>type : Symbol(type, Decl(asiPreventsParsingAsTypeAlias02.ts, 1, 3)) + + Foo = string; +>Foo : Symbol(Foo, Decl(asiPreventsParsingAsTypeAlias02.ts, 3, 3)) +>string : Symbol(string, Decl(asiPreventsParsingAsTypeAlias02.ts, 2, 3)) +} diff --git a/tests/baselines/reference/asiPreventsParsingAsTypeAlias02.types b/tests/baselines/reference/asiPreventsParsingAsTypeAlias02.types new file mode 100644 index 00000000000..1e6c7a8caf1 --- /dev/null +++ b/tests/baselines/reference/asiPreventsParsingAsTypeAlias02.types @@ -0,0 +1,22 @@ +=== tests/cases/conformance/types/typeAliases/asiPreventsParsingAsTypeAlias02.ts === + +var type; +>type : any + +var string; +>string : any + +var Foo; +>Foo : any + +namespace container { +>container : typeof container + + type +>type : any + + Foo = string; +>Foo = string : any +>Foo : any +>string : any +} diff --git a/tests/baselines/reference/assignmentCompatWithCallSignatures3.js b/tests/baselines/reference/assignmentCompatWithCallSignatures3.js index 1ad82ca531b..6f2eaf4d5cc 100644 --- a/tests/baselines/reference/assignmentCompatWithCallSignatures3.js +++ b/tests/baselines/reference/assignmentCompatWithCallSignatures3.js @@ -104,8 +104,7 @@ b18 = a18; // ok var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var Base = (function () { function Base() { diff --git a/tests/baselines/reference/assignmentCompatWithCallSignatures4.js b/tests/baselines/reference/assignmentCompatWithCallSignatures4.js index 387395525ad..fc6ca05ad30 100644 --- a/tests/baselines/reference/assignmentCompatWithCallSignatures4.js +++ b/tests/baselines/reference/assignmentCompatWithCallSignatures4.js @@ -103,8 +103,7 @@ module Errors { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var Errors; (function (Errors) { diff --git a/tests/baselines/reference/assignmentCompatWithCallSignatures5.js b/tests/baselines/reference/assignmentCompatWithCallSignatures5.js index 2e3790cd529..ddf16c23f48 100644 --- a/tests/baselines/reference/assignmentCompatWithCallSignatures5.js +++ b/tests/baselines/reference/assignmentCompatWithCallSignatures5.js @@ -70,8 +70,7 @@ b18 = a18; // ok var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var Base = (function () { function Base() { diff --git a/tests/baselines/reference/assignmentCompatWithCallSignatures6.js b/tests/baselines/reference/assignmentCompatWithCallSignatures6.js index a29a607f9ef..e57a5ac07a0 100644 --- a/tests/baselines/reference/assignmentCompatWithCallSignatures6.js +++ b/tests/baselines/reference/assignmentCompatWithCallSignatures6.js @@ -47,8 +47,7 @@ b16 = x.a16; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var Base = (function () { function Base() { diff --git a/tests/baselines/reference/assignmentCompatWithConstructSignatures3.js b/tests/baselines/reference/assignmentCompatWithConstructSignatures3.js index 32176e764e9..d02c635c584 100644 --- a/tests/baselines/reference/assignmentCompatWithConstructSignatures3.js +++ b/tests/baselines/reference/assignmentCompatWithConstructSignatures3.js @@ -104,8 +104,7 @@ b18 = a18; // ok var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var Base = (function () { function Base() { diff --git a/tests/baselines/reference/assignmentCompatWithConstructSignatures4.js b/tests/baselines/reference/assignmentCompatWithConstructSignatures4.js index 21bace1645c..6f9f20333f2 100644 --- a/tests/baselines/reference/assignmentCompatWithConstructSignatures4.js +++ b/tests/baselines/reference/assignmentCompatWithConstructSignatures4.js @@ -103,8 +103,7 @@ module Errors { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var Errors; (function (Errors) { diff --git a/tests/baselines/reference/assignmentCompatWithConstructSignatures5.js b/tests/baselines/reference/assignmentCompatWithConstructSignatures5.js index 76be317e95a..bd4c73e65dd 100644 --- a/tests/baselines/reference/assignmentCompatWithConstructSignatures5.js +++ b/tests/baselines/reference/assignmentCompatWithConstructSignatures5.js @@ -70,8 +70,7 @@ b18 = a18; // ok var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var Base = (function () { function Base() { diff --git a/tests/baselines/reference/assignmentCompatWithConstructSignatures6.js b/tests/baselines/reference/assignmentCompatWithConstructSignatures6.js index dc1d0dd2dee..98477fa1523 100644 --- a/tests/baselines/reference/assignmentCompatWithConstructSignatures6.js +++ b/tests/baselines/reference/assignmentCompatWithConstructSignatures6.js @@ -47,8 +47,7 @@ b16 = x.a16; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var Base = (function () { function Base() { diff --git a/tests/baselines/reference/assignmentCompatWithNumericIndexer.js b/tests/baselines/reference/assignmentCompatWithNumericIndexer.js index 6044c40b3cc..617d136bbb2 100644 --- a/tests/baselines/reference/assignmentCompatWithNumericIndexer.js +++ b/tests/baselines/reference/assignmentCompatWithNumericIndexer.js @@ -48,8 +48,7 @@ module Generics { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var A = (function () { function A() { diff --git a/tests/baselines/reference/assignmentCompatWithNumericIndexer3.js b/tests/baselines/reference/assignmentCompatWithNumericIndexer3.js index b3c073ea0b7..0c5b0be038f 100644 --- a/tests/baselines/reference/assignmentCompatWithNumericIndexer3.js +++ b/tests/baselines/reference/assignmentCompatWithNumericIndexer3.js @@ -45,8 +45,7 @@ module Generics { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var A = (function () { function A() { diff --git a/tests/baselines/reference/assignmentCompatWithObjectMembers4.js b/tests/baselines/reference/assignmentCompatWithObjectMembers4.js index 229525a91f0..20279fb1dc5 100644 --- a/tests/baselines/reference/assignmentCompatWithObjectMembers4.js +++ b/tests/baselines/reference/assignmentCompatWithObjectMembers4.js @@ -96,8 +96,7 @@ module WithBase { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var OnlyDerived; (function (OnlyDerived) { diff --git a/tests/baselines/reference/assignmentCompatWithObjectMembersOptionality.js b/tests/baselines/reference/assignmentCompatWithObjectMembersOptionality.js index 629f7bf5113..6675fab6d69 100644 --- a/tests/baselines/reference/assignmentCompatWithObjectMembersOptionality.js +++ b/tests/baselines/reference/assignmentCompatWithObjectMembersOptionality.js @@ -93,8 +93,7 @@ module SourceHasOptional { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var Base = (function () { function Base() { diff --git a/tests/baselines/reference/assignmentCompatWithObjectMembersOptionality2.js b/tests/baselines/reference/assignmentCompatWithObjectMembersOptionality2.js index 4ffec4aa7dd..b89106eba2b 100644 --- a/tests/baselines/reference/assignmentCompatWithObjectMembersOptionality2.js +++ b/tests/baselines/reference/assignmentCompatWithObjectMembersOptionality2.js @@ -95,8 +95,7 @@ module SourceHasOptional { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var Base = (function () { function Base() { diff --git a/tests/baselines/reference/assignmentCompatWithStringIndexer.js b/tests/baselines/reference/assignmentCompatWithStringIndexer.js index 99457453af4..3391ac5773a 100644 --- a/tests/baselines/reference/assignmentCompatWithStringIndexer.js +++ b/tests/baselines/reference/assignmentCompatWithStringIndexer.js @@ -58,8 +58,7 @@ module Generics { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var A = (function () { function A() { diff --git a/tests/baselines/reference/assignmentLHSIsValue.js b/tests/baselines/reference/assignmentLHSIsValue.js index 33054009d8e..127f85512ac 100644 --- a/tests/baselines/reference/assignmentLHSIsValue.js +++ b/tests/baselines/reference/assignmentLHSIsValue.js @@ -74,8 +74,7 @@ foo() = value; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; // expected error for all the LHS of assignments var value; diff --git a/tests/baselines/reference/autolift4.js b/tests/baselines/reference/autolift4.js index 5986ef4a3f5..f4bbad50c60 100644 --- a/tests/baselines/reference/autolift4.js +++ b/tests/baselines/reference/autolift4.js @@ -27,8 +27,7 @@ class Point3D extends Point { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var Point = (function () { function Point(x, y) { diff --git a/tests/baselines/reference/baseCheck.js b/tests/baselines/reference/baseCheck.js index 4e7db8e6a5b..49038f37b18 100644 --- a/tests/baselines/reference/baseCheck.js +++ b/tests/baselines/reference/baseCheck.js @@ -33,8 +33,7 @@ function f() { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var C = (function () { function C(x, y) { diff --git a/tests/baselines/reference/baseIndexSignatureResolution.js b/tests/baselines/reference/baseIndexSignatureResolution.js index 85b76221e3c..8463ed58a53 100644 --- a/tests/baselines/reference/baseIndexSignatureResolution.js +++ b/tests/baselines/reference/baseIndexSignatureResolution.js @@ -28,8 +28,7 @@ var z: Derived = b.foo(); var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var Base = (function () { function Base() { diff --git a/tests/baselines/reference/baseTypeOrderChecking.js b/tests/baselines/reference/baseTypeOrderChecking.js index 754d90e21ea..4c5fe22ea08 100644 --- a/tests/baselines/reference/baseTypeOrderChecking.js +++ b/tests/baselines/reference/baseTypeOrderChecking.js @@ -40,8 +40,7 @@ class Class4 extends Class3 var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var someVariable; var Class1 = (function () { diff --git a/tests/baselines/reference/baseTypeWrappingInstantiationChain.js b/tests/baselines/reference/baseTypeWrappingInstantiationChain.js index aaa93710339..1de1ebd4bfb 100644 --- a/tests/baselines/reference/baseTypeWrappingInstantiationChain.js +++ b/tests/baselines/reference/baseTypeWrappingInstantiationChain.js @@ -30,8 +30,7 @@ class Wrapper { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var C = (function (_super) { __extends(C, _super); diff --git a/tests/baselines/reference/baseTypeWrappingInstantiationChain.types b/tests/baselines/reference/baseTypeWrappingInstantiationChain.types index 61919bad212..747b672dd0d 100644 --- a/tests/baselines/reference/baseTypeWrappingInstantiationChain.types +++ b/tests/baselines/reference/baseTypeWrappingInstantiationChain.types @@ -2,7 +2,7 @@ class C extends CBase { >C : C >T1 : T1 ->CBase : CBase +>CBase : CBase >T1 : T1 public works() { @@ -35,7 +35,7 @@ class C extends CBase { class CBase extends CBaseBase> { >CBase : CBase >T2 : T2 ->CBaseBase : CBaseBase +>CBaseBase : CBaseBase> >Wrapper : Wrapper >T2 : T2 diff --git a/tests/baselines/reference/bases.js b/tests/baselines/reference/bases.js index 5687e9e0fe1..0275c225dac 100644 --- a/tests/baselines/reference/bases.js +++ b/tests/baselines/reference/bases.js @@ -24,8 +24,7 @@ new C().y; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var B = (function () { function B() { diff --git a/tests/baselines/reference/bestCommonTypeOfConditionalExpressions.js b/tests/baselines/reference/bestCommonTypeOfConditionalExpressions.js index e56e530ad64..abd2cc5e874 100644 --- a/tests/baselines/reference/bestCommonTypeOfConditionalExpressions.js +++ b/tests/baselines/reference/bestCommonTypeOfConditionalExpressions.js @@ -32,8 +32,7 @@ function foo5(t: T, u: U): Object { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var a; var b; diff --git a/tests/baselines/reference/bestCommonTypeOfConditionalExpressions2.js b/tests/baselines/reference/bestCommonTypeOfConditionalExpressions2.js index fb3c15a8fba..e0e7bc3f324 100644 --- a/tests/baselines/reference/bestCommonTypeOfConditionalExpressions2.js +++ b/tests/baselines/reference/bestCommonTypeOfConditionalExpressions2.js @@ -30,8 +30,7 @@ function foo3(t: T, u: U) { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var Base = (function () { function Base() { diff --git a/tests/baselines/reference/bestCommonTypeOfTuple2.js b/tests/baselines/reference/bestCommonTypeOfTuple2.js index 5642df5570c..ed0b0ecb328 100644 --- a/tests/baselines/reference/bestCommonTypeOfTuple2.js +++ b/tests/baselines/reference/bestCommonTypeOfTuple2.js @@ -26,8 +26,7 @@ var e51 = t5[2]; // {} var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var C = (function () { function C() { diff --git a/tests/baselines/reference/callSignatureAssignabilityInInheritance2.js b/tests/baselines/reference/callSignatureAssignabilityInInheritance2.js index 685e33acb6b..e43c22fab75 100644 --- a/tests/baselines/reference/callSignatureAssignabilityInInheritance2.js +++ b/tests/baselines/reference/callSignatureAssignabilityInInheritance2.js @@ -74,8 +74,7 @@ interface I extends A { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var Base = (function () { function Base() { diff --git a/tests/baselines/reference/callSignatureAssignabilityInInheritance3.js b/tests/baselines/reference/callSignatureAssignabilityInInheritance3.js index 135c0c056ae..6105ddf23fa 100644 --- a/tests/baselines/reference/callSignatureAssignabilityInInheritance3.js +++ b/tests/baselines/reference/callSignatureAssignabilityInInheritance3.js @@ -119,8 +119,7 @@ module Errors { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var Errors; (function (Errors) { diff --git a/tests/baselines/reference/callSignatureAssignabilityInInheritance4.js b/tests/baselines/reference/callSignatureAssignabilityInInheritance4.js index c578a49ee55..aee3af6f740 100644 --- a/tests/baselines/reference/callSignatureAssignabilityInInheritance4.js +++ b/tests/baselines/reference/callSignatureAssignabilityInInheritance4.js @@ -54,8 +54,7 @@ interface I extends A { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var Base = (function () { function Base() { diff --git a/tests/baselines/reference/callSignatureAssignabilityInInheritance5.js b/tests/baselines/reference/callSignatureAssignabilityInInheritance5.js index 74987308ef7..c72a77e4020 100644 --- a/tests/baselines/reference/callSignatureAssignabilityInInheritance5.js +++ b/tests/baselines/reference/callSignatureAssignabilityInInheritance5.js @@ -54,8 +54,7 @@ interface I extends B { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var Base = (function () { function Base() { diff --git a/tests/baselines/reference/callSignatureAssignabilityInInheritance6.js b/tests/baselines/reference/callSignatureAssignabilityInInheritance6.js index aa2e9787bd1..e22bb1189ed 100644 --- a/tests/baselines/reference/callSignatureAssignabilityInInheritance6.js +++ b/tests/baselines/reference/callSignatureAssignabilityInInheritance6.js @@ -57,8 +57,7 @@ interface I9 extends A { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var Base = (function () { function Base() { diff --git a/tests/baselines/reference/callWithSpread.js b/tests/baselines/reference/callWithSpread.js index d21b4879daa..50840abfbb7 100644 --- a/tests/baselines/reference/callWithSpread.js +++ b/tests/baselines/reference/callWithSpread.js @@ -54,8 +54,7 @@ class D extends C { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; function foo(x, y) { var z = []; diff --git a/tests/baselines/reference/captureThisInSuperCall.js b/tests/baselines/reference/captureThisInSuperCall.js index 27c80e2991d..611ad93f531 100644 --- a/tests/baselines/reference/captureThisInSuperCall.js +++ b/tests/baselines/reference/captureThisInSuperCall.js @@ -12,8 +12,7 @@ class B extends A { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var A = (function () { function A(p) { diff --git a/tests/baselines/reference/castingTuple.js b/tests/baselines/reference/castingTuple.js index 8b1005d4487..0102d1310a3 100644 --- a/tests/baselines/reference/castingTuple.js +++ b/tests/baselines/reference/castingTuple.js @@ -36,8 +36,7 @@ t4[2] = 10; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var A = (function () { function A() { diff --git a/tests/baselines/reference/chainedAssignment3.js b/tests/baselines/reference/chainedAssignment3.js index 022668ba7cf..04c328031cd 100644 --- a/tests/baselines/reference/chainedAssignment3.js +++ b/tests/baselines/reference/chainedAssignment3.js @@ -26,8 +26,7 @@ a = b = new A(); var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var A = (function () { function A() { diff --git a/tests/baselines/reference/chainedCallsWithTypeParameterConstrainedToOtherTypeParameter.js b/tests/baselines/reference/chainedCallsWithTypeParameterConstrainedToOtherTypeParameter.js index 494f0bc1b5d..e7e1a3a871b 100644 --- a/tests/baselines/reference/chainedCallsWithTypeParameterConstrainedToOtherTypeParameter.js +++ b/tests/baselines/reference/chainedCallsWithTypeParameterConstrainedToOtherTypeParameter.js @@ -23,8 +23,7 @@ class C extends B { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var Chain = (function () { function Chain(value) { diff --git a/tests/baselines/reference/checkForObjectTooStrict.errors.txt b/tests/baselines/reference/checkForObjectTooStrict.errors.txt deleted file mode 100644 index 7af7481f6ae..00000000000 --- a/tests/baselines/reference/checkForObjectTooStrict.errors.txt +++ /dev/null @@ -1,40 +0,0 @@ -tests/cases/compiler/checkForObjectTooStrict.ts(22,19): error TS2311: A class may only extend another class. -tests/cases/compiler/checkForObjectTooStrict.ts(26,9): error TS2335: 'super' can only be referenced in a derived class. - - -==== tests/cases/compiler/checkForObjectTooStrict.ts (2 errors) ==== - module Foo { - - export class Object { - - } - - } - - - - class Bar extends Foo.Object { // should work - - constructor () { - - super(); - - } - - } - - - class Baz extends Object { - ~~~~~~ -!!! error TS2311: A class may only extend another class. - - constructor () { // ERROR, as expected - - super(); - ~~~~~ -!!! error TS2335: 'super' can only be referenced in a derived class. - - } - - } - \ No newline at end of file diff --git a/tests/baselines/reference/checkForObjectTooStrict.js b/tests/baselines/reference/checkForObjectTooStrict.js index bcdde6b3be1..d8f40a3f1d9 100644 --- a/tests/baselines/reference/checkForObjectTooStrict.js +++ b/tests/baselines/reference/checkForObjectTooStrict.js @@ -35,8 +35,7 @@ class Baz extends Object { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var Foo; (function (Foo) { diff --git a/tests/baselines/reference/checkForObjectTooStrict.symbols b/tests/baselines/reference/checkForObjectTooStrict.symbols new file mode 100644 index 00000000000..48e04392c3b --- /dev/null +++ b/tests/baselines/reference/checkForObjectTooStrict.symbols @@ -0,0 +1,42 @@ +=== tests/cases/compiler/checkForObjectTooStrict.ts === +module Foo { +>Foo : Symbol(Foo, Decl(checkForObjectTooStrict.ts, 0, 0)) + + export class Object { +>Object : Symbol(Object, Decl(checkForObjectTooStrict.ts, 0, 12)) + + } + +} + + + +class Bar extends Foo.Object { // should work +>Bar : Symbol(Bar, Decl(checkForObjectTooStrict.ts, 6, 1)) +>Foo.Object : Symbol(Foo.Object, Decl(checkForObjectTooStrict.ts, 0, 12)) +>Foo : Symbol(Foo, Decl(checkForObjectTooStrict.ts, 0, 0)) +>Object : Symbol(Foo.Object, Decl(checkForObjectTooStrict.ts, 0, 12)) + + constructor () { + + super(); +>super : Symbol(Foo.Object, Decl(checkForObjectTooStrict.ts, 0, 12)) + + } + +} + + +class Baz extends Object { +>Baz : Symbol(Baz, Decl(checkForObjectTooStrict.ts, 18, 1)) +>Object : Symbol(Object, Decl(lib.d.ts, 92, 1), Decl(lib.d.ts, 223, 11)) + + constructor () { // ERROR, as expected + + super(); +>super : Symbol(ObjectConstructor, Decl(lib.d.ts, 124, 1)) + + } + +} + diff --git a/tests/baselines/reference/checkForObjectTooStrict.types b/tests/baselines/reference/checkForObjectTooStrict.types new file mode 100644 index 00000000000..f6b63019cd5 --- /dev/null +++ b/tests/baselines/reference/checkForObjectTooStrict.types @@ -0,0 +1,44 @@ +=== tests/cases/compiler/checkForObjectTooStrict.ts === +module Foo { +>Foo : typeof Foo + + export class Object { +>Object : Object + + } + +} + + + +class Bar extends Foo.Object { // should work +>Bar : Bar +>Foo.Object : Foo.Object +>Foo : typeof Foo +>Object : typeof Foo.Object + + constructor () { + + super(); +>super() : void +>super : typeof Foo.Object + + } + +} + + +class Baz extends Object { +>Baz : Baz +>Object : Object + + constructor () { // ERROR, as expected + + super(); +>super() : void +>super : ObjectConstructor + + } + +} + diff --git a/tests/baselines/reference/circularImportAlias.js b/tests/baselines/reference/circularImportAlias.js index 1a50a46221b..8b908a97ee6 100644 --- a/tests/baselines/reference/circularImportAlias.js +++ b/tests/baselines/reference/circularImportAlias.js @@ -24,8 +24,7 @@ var c = new B.a.C(); var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var B; (function (B) { diff --git a/tests/baselines/reference/circularImportAlias.types b/tests/baselines/reference/circularImportAlias.types index 3ab41f6187b..e4b2f27dbbe 100644 --- a/tests/baselines/reference/circularImportAlias.types +++ b/tests/baselines/reference/circularImportAlias.types @@ -10,9 +10,9 @@ module B { export class D extends a.C { >D : D ->a.C : any +>a.C : a.C >a : typeof a ->C : a.C +>C : typeof a.C id: number; >id : number diff --git a/tests/baselines/reference/class2.errors.txt b/tests/baselines/reference/class2.errors.txt index dde3612b68f..62542b41e40 100644 --- a/tests/baselines/reference/class2.errors.txt +++ b/tests/baselines/reference/class2.errors.txt @@ -1,10 +1,10 @@ -tests/cases/compiler/class2.ts(1,29): error TS1129: Statement expected. +tests/cases/compiler/class2.ts(1,29): error TS1128: Declaration or statement expected. tests/cases/compiler/class2.ts(1,45): error TS1128: Declaration or statement expected. ==== tests/cases/compiler/class2.ts (2 errors) ==== class foo { constructor() { static f = 3; } } ~~~~~~ -!!! error TS1129: Statement expected. +!!! error TS1128: Declaration or statement expected. ~ !!! error TS1128: Declaration or statement expected. \ No newline at end of file diff --git a/tests/baselines/reference/classConstructorParametersAccessibility.js b/tests/baselines/reference/classConstructorParametersAccessibility.js index 5d715556ec1..a5538b66ecc 100644 --- a/tests/baselines/reference/classConstructorParametersAccessibility.js +++ b/tests/baselines/reference/classConstructorParametersAccessibility.js @@ -30,8 +30,7 @@ class Derived extends C3 { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var C1 = (function () { function C1(x) { diff --git a/tests/baselines/reference/classConstructorParametersAccessibility2.js b/tests/baselines/reference/classConstructorParametersAccessibility2.js index 1d273e119ec..581746a180b 100644 --- a/tests/baselines/reference/classConstructorParametersAccessibility2.js +++ b/tests/baselines/reference/classConstructorParametersAccessibility2.js @@ -30,8 +30,7 @@ class Derived extends C3 { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var C1 = (function () { function C1(x) { diff --git a/tests/baselines/reference/classConstructorParametersAccessibility3.js b/tests/baselines/reference/classConstructorParametersAccessibility3.js index 43823bbb4d9..d98b094ccdb 100644 --- a/tests/baselines/reference/classConstructorParametersAccessibility3.js +++ b/tests/baselines/reference/classConstructorParametersAccessibility3.js @@ -17,8 +17,7 @@ d.p; // public, OK var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var Base = (function () { function Base(p) { diff --git a/tests/baselines/reference/classDeclarationBlockScoping1.errors.txt b/tests/baselines/reference/classDeclarationBlockScoping1.errors.txt deleted file mode 100644 index 4f15007bb2a..00000000000 --- a/tests/baselines/reference/classDeclarationBlockScoping1.errors.txt +++ /dev/null @@ -1,13 +0,0 @@ -tests/cases/compiler/classDeclarationBlockScoping1.ts(5,11): error TS9004: 'class' declarations are only supported directly inside a module or as a top level declaration. - - -==== tests/cases/compiler/classDeclarationBlockScoping1.ts (1 errors) ==== - class C { - } - - { - class C { - ~ -!!! error TS9004: 'class' declarations are only supported directly inside a module or as a top level declaration. - } - } \ No newline at end of file diff --git a/tests/baselines/reference/classDeclarationBlockScoping1.js b/tests/baselines/reference/classDeclarationBlockScoping1.js index 717c2f788c3..4c7f9d8e24a 100644 --- a/tests/baselines/reference/classDeclarationBlockScoping1.js +++ b/tests/baselines/reference/classDeclarationBlockScoping1.js @@ -14,9 +14,9 @@ var C = (function () { return C; })(); { - var C = (function () { - function C() { + var C_1 = (function () { + function C_1() { } - return C; + return C_1; })(); } diff --git a/tests/baselines/reference/classDeclarationBlockScoping1.symbols b/tests/baselines/reference/classDeclarationBlockScoping1.symbols new file mode 100644 index 00000000000..645d327e256 --- /dev/null +++ b/tests/baselines/reference/classDeclarationBlockScoping1.symbols @@ -0,0 +1,10 @@ +=== tests/cases/compiler/classDeclarationBlockScoping1.ts === +class C { +>C : Symbol(C, Decl(classDeclarationBlockScoping1.ts, 0, 0)) +} + +{ + class C { +>C : Symbol(C, Decl(classDeclarationBlockScoping1.ts, 3, 1)) + } +} diff --git a/tests/baselines/reference/classDeclarationBlockScoping1.types b/tests/baselines/reference/classDeclarationBlockScoping1.types new file mode 100644 index 00000000000..9020ca4a23a --- /dev/null +++ b/tests/baselines/reference/classDeclarationBlockScoping1.types @@ -0,0 +1,10 @@ +=== tests/cases/compiler/classDeclarationBlockScoping1.ts === +class C { +>C : C +} + +{ + class C { +>C : C + } +} diff --git a/tests/baselines/reference/classDeclarationBlockScoping2.errors.txt b/tests/baselines/reference/classDeclarationBlockScoping2.errors.txt deleted file mode 100644 index 2a9885e110b..00000000000 --- a/tests/baselines/reference/classDeclarationBlockScoping2.errors.txt +++ /dev/null @@ -1,18 +0,0 @@ -tests/cases/compiler/classDeclarationBlockScoping2.ts(2,11): error TS9004: 'class' declarations are only supported directly inside a module or as a top level declaration. -tests/cases/compiler/classDeclarationBlockScoping2.ts(5,15): error TS9004: 'class' declarations are only supported directly inside a module or as a top level declaration. - - -==== tests/cases/compiler/classDeclarationBlockScoping2.ts (2 errors) ==== - function f() { - class C {} - ~ -!!! error TS9004: 'class' declarations are only supported directly inside a module or as a top level declaration. - var c1 = C; - { - class C {} - ~ -!!! error TS9004: 'class' declarations are only supported directly inside a module or as a top level declaration. - var c2 = C; - } - return C === c1; - } \ No newline at end of file diff --git a/tests/baselines/reference/classDeclarationBlockScoping2.js b/tests/baselines/reference/classDeclarationBlockScoping2.js index 9e468077119..57001d0d287 100644 --- a/tests/baselines/reference/classDeclarationBlockScoping2.js +++ b/tests/baselines/reference/classDeclarationBlockScoping2.js @@ -18,12 +18,12 @@ function f() { })(); var c1 = C; { - var C = (function () { - function C() { + var C_1 = (function () { + function C_1() { } - return C; + return C_1; })(); - var c2 = C; + var c2 = C_1; } return C === c1; } diff --git a/tests/baselines/reference/classDeclarationBlockScoping2.symbols b/tests/baselines/reference/classDeclarationBlockScoping2.symbols new file mode 100644 index 00000000000..cece47c3ee7 --- /dev/null +++ b/tests/baselines/reference/classDeclarationBlockScoping2.symbols @@ -0,0 +1,22 @@ +=== tests/cases/compiler/classDeclarationBlockScoping2.ts === +function f() { +>f : Symbol(f, Decl(classDeclarationBlockScoping2.ts, 0, 0)) + + class C {} +>C : Symbol(C, Decl(classDeclarationBlockScoping2.ts, 0, 14)) + + var c1 = C; +>c1 : Symbol(c1, Decl(classDeclarationBlockScoping2.ts, 2, 7)) +>C : Symbol(C, Decl(classDeclarationBlockScoping2.ts, 0, 14)) + { + class C {} +>C : Symbol(C, Decl(classDeclarationBlockScoping2.ts, 3, 5)) + + var c2 = C; +>c2 : Symbol(c2, Decl(classDeclarationBlockScoping2.ts, 5, 11)) +>C : Symbol(C, Decl(classDeclarationBlockScoping2.ts, 3, 5)) + } + return C === c1; +>C : Symbol(C, Decl(classDeclarationBlockScoping2.ts, 0, 14)) +>c1 : Symbol(c1, Decl(classDeclarationBlockScoping2.ts, 2, 7)) +} diff --git a/tests/baselines/reference/classDeclarationBlockScoping2.types b/tests/baselines/reference/classDeclarationBlockScoping2.types new file mode 100644 index 00000000000..0431d4dd2fd --- /dev/null +++ b/tests/baselines/reference/classDeclarationBlockScoping2.types @@ -0,0 +1,23 @@ +=== tests/cases/compiler/classDeclarationBlockScoping2.ts === +function f() { +>f : () => boolean + + class C {} +>C : C + + var c1 = C; +>c1 : typeof C +>C : typeof C + { + class C {} +>C : C + + var c2 = C; +>c2 : typeof C +>C : typeof C + } + return C === c1; +>C === c1 : boolean +>C : typeof C +>c1 : typeof C +} diff --git a/tests/baselines/reference/classDeclarationMergedInModuleWithContinuation.js b/tests/baselines/reference/classDeclarationMergedInModuleWithContinuation.js index 7299b04720f..a8d6fcd88e0 100644 --- a/tests/baselines/reference/classDeclarationMergedInModuleWithContinuation.js +++ b/tests/baselines/reference/classDeclarationMergedInModuleWithContinuation.js @@ -15,8 +15,7 @@ module M { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var M; (function (M) { diff --git a/tests/baselines/reference/classDeclarationMergedInModuleWithContinuation.types b/tests/baselines/reference/classDeclarationMergedInModuleWithContinuation.types index f1be8e6d268..11fcac506b6 100644 --- a/tests/baselines/reference/classDeclarationMergedInModuleWithContinuation.types +++ b/tests/baselines/reference/classDeclarationMergedInModuleWithContinuation.types @@ -19,8 +19,8 @@ module M { export class O extends M.N { >O : O ->M.N : any +>M.N : N >M : typeof M ->N : N +>N : typeof N } } diff --git a/tests/baselines/reference/classDoesNotDependOnBaseTypes.js b/tests/baselines/reference/classDoesNotDependOnBaseTypes.js index 52474582315..8515e1d98eb 100644 --- a/tests/baselines/reference/classDoesNotDependOnBaseTypes.js +++ b/tests/baselines/reference/classDoesNotDependOnBaseTypes.js @@ -16,8 +16,7 @@ class StringTreeCollection extends StringTreeCollectionBase { } var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var x; if (typeof x !== "string") { diff --git a/tests/baselines/reference/classExpressionTest1.errors.txt b/tests/baselines/reference/classExpressionTest1.errors.txt deleted file mode 100644 index 4d7e1cda639..00000000000 --- a/tests/baselines/reference/classExpressionTest1.errors.txt +++ /dev/null @@ -1,18 +0,0 @@ -tests/cases/compiler/classExpressionTest1.ts(2,11): error TS9004: 'class' declarations are only supported directly inside a module or as a top level declaration. - - -==== tests/cases/compiler/classExpressionTest1.ts (1 errors) ==== - function M() { - class C { - ~ -!!! error TS9004: 'class' declarations are only supported directly inside a module or as a top level declaration. - f() { - var t: T; - var x: X; - return { t, x }; - } - } - - var v = new C(); - return v.f(); - } \ No newline at end of file diff --git a/tests/baselines/reference/classExpressionTest1.symbols b/tests/baselines/reference/classExpressionTest1.symbols new file mode 100644 index 00000000000..684ee302895 --- /dev/null +++ b/tests/baselines/reference/classExpressionTest1.symbols @@ -0,0 +1,35 @@ +=== tests/cases/compiler/classExpressionTest1.ts === +function M() { +>M : Symbol(M, Decl(classExpressionTest1.ts, 0, 0)) + + class C { +>C : Symbol(C, Decl(classExpressionTest1.ts, 0, 14)) +>X : Symbol(X, Decl(classExpressionTest1.ts, 1, 12)) + + f() { +>f : Symbol(f, Decl(classExpressionTest1.ts, 1, 16)) +>T : Symbol(T, Decl(classExpressionTest1.ts, 2, 10)) + + var t: T; +>t : Symbol(t, Decl(classExpressionTest1.ts, 3, 15)) +>T : Symbol(T, Decl(classExpressionTest1.ts, 2, 10)) + + var x: X; +>x : Symbol(x, Decl(classExpressionTest1.ts, 4, 15)) +>X : Symbol(X, Decl(classExpressionTest1.ts, 1, 12)) + + return { t, x }; +>t : Symbol(t, Decl(classExpressionTest1.ts, 5, 20)) +>x : Symbol(x, Decl(classExpressionTest1.ts, 5, 23)) + } + } + + var v = new C(); +>v : Symbol(v, Decl(classExpressionTest1.ts, 9, 7)) +>C : Symbol(C, Decl(classExpressionTest1.ts, 0, 14)) + + return v.f(); +>v.f : Symbol(C.f, Decl(classExpressionTest1.ts, 1, 16)) +>v : Symbol(v, Decl(classExpressionTest1.ts, 9, 7)) +>f : Symbol(C.f, Decl(classExpressionTest1.ts, 1, 16)) +} diff --git a/tests/baselines/reference/classExpressionTest1.types b/tests/baselines/reference/classExpressionTest1.types new file mode 100644 index 00000000000..bf1ae0f2f7d --- /dev/null +++ b/tests/baselines/reference/classExpressionTest1.types @@ -0,0 +1,38 @@ +=== tests/cases/compiler/classExpressionTest1.ts === +function M() { +>M : () => { t: string; x: number; } + + class C { +>C : C +>X : X + + f() { +>f : () => { t: T; x: X; } +>T : T + + var t: T; +>t : T +>T : T + + var x: X; +>x : X +>X : X + + return { t, x }; +>{ t, x } : { t: T; x: X; } +>t : T +>x : X + } + } + + var v = new C(); +>v : C +>new C() : C +>C : typeof C + + return v.f(); +>v.f() : { t: string; x: number; } +>v.f : () => { t: T; x: number; } +>v : C +>f : () => { t: T; x: number; } +} diff --git a/tests/baselines/reference/classExpressionWithResolutionOfNamespaceOfSameName01.errors.txt b/tests/baselines/reference/classExpressionWithResolutionOfNamespaceOfSameName01.errors.txt new file mode 100644 index 00000000000..8edc1d8f74b --- /dev/null +++ b/tests/baselines/reference/classExpressionWithResolutionOfNamespaceOfSameName01.errors.txt @@ -0,0 +1,14 @@ +tests/cases/compiler/classExpressionWithResolutionOfNamespaceOfSameName01.ts(6,15): error TS9003: 'class' expressions are not currently supported. + + +==== tests/cases/compiler/classExpressionWithResolutionOfNamespaceOfSameName01.ts (1 errors) ==== + namespace C { + export interface type { + } + } + + var x = class C { + ~ +!!! error TS9003: 'class' expressions are not currently supported. + prop: C.type; + } \ No newline at end of file diff --git a/tests/baselines/reference/classExpressionWithResolutionOfNamespaceOfSameName01.js b/tests/baselines/reference/classExpressionWithResolutionOfNamespaceOfSameName01.js new file mode 100644 index 00000000000..7c9f25cdfe6 --- /dev/null +++ b/tests/baselines/reference/classExpressionWithResolutionOfNamespaceOfSameName01.js @@ -0,0 +1,16 @@ +//// [classExpressionWithResolutionOfNamespaceOfSameName01.ts] +namespace C { + export interface type { + } +} + +var x = class C { + prop: C.type; +} + +//// [classExpressionWithResolutionOfNamespaceOfSameName01.js] +var x = (function () { + function C() { + } + return C; +})(); diff --git a/tests/baselines/reference/classExtendingBuiltinType.js b/tests/baselines/reference/classExtendingBuiltinType.js new file mode 100644 index 00000000000..8a4b0dd3849 --- /dev/null +++ b/tests/baselines/reference/classExtendingBuiltinType.js @@ -0,0 +1,89 @@ +//// [classExtendingBuiltinType.ts] +class C1 extends Object { } +class C2 extends Function { } +class C3 extends String { } +class C4 extends Boolean { } +class C5 extends Number { } +class C6 extends Date { } +class C7 extends RegExp { } +class C8 extends Error { } +class C9 extends Array { } +class C10 extends Array { } + + +//// [classExtendingBuiltinType.js] +var __extends = (this && this.__extends) || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); +}; +var C1 = (function (_super) { + __extends(C1, _super); + function C1() { + _super.apply(this, arguments); + } + return C1; +})(Object); +var C2 = (function (_super) { + __extends(C2, _super); + function C2() { + _super.apply(this, arguments); + } + return C2; +})(Function); +var C3 = (function (_super) { + __extends(C3, _super); + function C3() { + _super.apply(this, arguments); + } + return C3; +})(String); +var C4 = (function (_super) { + __extends(C4, _super); + function C4() { + _super.apply(this, arguments); + } + return C4; +})(Boolean); +var C5 = (function (_super) { + __extends(C5, _super); + function C5() { + _super.apply(this, arguments); + } + return C5; +})(Number); +var C6 = (function (_super) { + __extends(C6, _super); + function C6() { + _super.apply(this, arguments); + } + return C6; +})(Date); +var C7 = (function (_super) { + __extends(C7, _super); + function C7() { + _super.apply(this, arguments); + } + return C7; +})(RegExp); +var C8 = (function (_super) { + __extends(C8, _super); + function C8() { + _super.apply(this, arguments); + } + return C8; +})(Error); +var C9 = (function (_super) { + __extends(C9, _super); + function C9() { + _super.apply(this, arguments); + } + return C9; +})(Array); +var C10 = (function (_super) { + __extends(C10, _super); + function C10() { + _super.apply(this, arguments); + } + return C10; +})(Array); diff --git a/tests/baselines/reference/classExtendingBuiltinType.symbols b/tests/baselines/reference/classExtendingBuiltinType.symbols new file mode 100644 index 00000000000..08e85be570e --- /dev/null +++ b/tests/baselines/reference/classExtendingBuiltinType.symbols @@ -0,0 +1,41 @@ +=== tests/cases/conformance/classes/classDeclarations/classExtendingBuiltinType.ts === +class C1 extends Object { } +>C1 : Symbol(C1, Decl(classExtendingBuiltinType.ts, 0, 0)) +>Object : Symbol(Object, Decl(lib.d.ts, 92, 1), Decl(lib.d.ts, 223, 11)) + +class C2 extends Function { } +>C2 : Symbol(C2, Decl(classExtendingBuiltinType.ts, 0, 27)) +>Function : Symbol(Function, Decl(lib.d.ts, 223, 38), Decl(lib.d.ts, 269, 11)) + +class C3 extends String { } +>C3 : Symbol(C3, Decl(classExtendingBuiltinType.ts, 1, 29)) +>String : Symbol(String, Decl(lib.d.ts, 275, 1), Decl(lib.d.ts, 443, 11)) + +class C4 extends Boolean { } +>C4 : Symbol(C4, Decl(classExtendingBuiltinType.ts, 2, 27)) +>Boolean : Symbol(Boolean, Decl(lib.d.ts, 443, 38), Decl(lib.d.ts, 456, 11)) + +class C5 extends Number { } +>C5 : Symbol(C5, Decl(classExtendingBuiltinType.ts, 3, 28)) +>Number : Symbol(Number, Decl(lib.d.ts, 456, 40), Decl(lib.d.ts, 518, 11)) + +class C6 extends Date { } +>C6 : Symbol(C6, Decl(classExtendingBuiltinType.ts, 4, 27)) +>Date : Symbol(Date, Decl(lib.d.ts, 633, 23), Decl(lib.d.ts, 815, 11)) + +class C7 extends RegExp { } +>C7 : Symbol(C7, Decl(classExtendingBuiltinType.ts, 5, 25)) +>RegExp : Symbol(RegExp, Decl(lib.d.ts, 825, 1), Decl(lib.d.ts, 876, 11)) + +class C8 extends Error { } +>C8 : Symbol(C8, Decl(classExtendingBuiltinType.ts, 6, 27)) +>Error : Symbol(Error, Decl(lib.d.ts, 876, 38), Decl(lib.d.ts, 889, 11)) + +class C9 extends Array { } +>C9 : Symbol(C9, Decl(classExtendingBuiltinType.ts, 7, 26)) +>Array : Symbol(Array, Decl(lib.d.ts, 1000, 23), Decl(lib.d.ts, 1171, 11)) + +class C10 extends Array { } +>C10 : Symbol(C10, Decl(classExtendingBuiltinType.ts, 8, 26)) +>Array : Symbol(Array, Decl(lib.d.ts, 1000, 23), Decl(lib.d.ts, 1171, 11)) + diff --git a/tests/baselines/reference/classExtendingBuiltinType.types b/tests/baselines/reference/classExtendingBuiltinType.types new file mode 100644 index 00000000000..b50137e58d6 --- /dev/null +++ b/tests/baselines/reference/classExtendingBuiltinType.types @@ -0,0 +1,41 @@ +=== tests/cases/conformance/classes/classDeclarations/classExtendingBuiltinType.ts === +class C1 extends Object { } +>C1 : C1 +>Object : Object + +class C2 extends Function { } +>C2 : C2 +>Function : Function + +class C3 extends String { } +>C3 : C3 +>String : String + +class C4 extends Boolean { } +>C4 : C4 +>Boolean : Boolean + +class C5 extends Number { } +>C5 : C5 +>Number : Number + +class C6 extends Date { } +>C6 : C6 +>Date : Date + +class C7 extends RegExp { } +>C7 : C7 +>RegExp : RegExp + +class C8 extends Error { } +>C8 : C8 +>Error : Error + +class C9 extends Array { } +>C9 : C9 +>Array : any[] + +class C10 extends Array { } +>C10 : C10 +>Array : number[] + diff --git a/tests/baselines/reference/classExtendingClass.js b/tests/baselines/reference/classExtendingClass.js index b8e079e8ecb..6168cb3418d 100644 --- a/tests/baselines/reference/classExtendingClass.js +++ b/tests/baselines/reference/classExtendingClass.js @@ -35,8 +35,7 @@ var r8 = D2.other(1); var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var C = (function () { function C() { diff --git a/tests/baselines/reference/classExtendingClassLikeType.errors.txt b/tests/baselines/reference/classExtendingClassLikeType.errors.txt new file mode 100644 index 00000000000..6f9aef927ea --- /dev/null +++ b/tests/baselines/reference/classExtendingClassLikeType.errors.txt @@ -0,0 +1,70 @@ +tests/cases/conformance/classes/classDeclarations/classExtendingClassLikeType.ts(7,18): error TS2304: Cannot find name 'Base'. +tests/cases/conformance/classes/classDeclarations/classExtendingClassLikeType.ts(45,18): error TS2508: No base constructor has the specified number of type arguments. +tests/cases/conformance/classes/classDeclarations/classExtendingClassLikeType.ts(56,18): error TS2510: Base constructors must all have the same return type. + + +==== tests/cases/conformance/classes/classDeclarations/classExtendingClassLikeType.ts (3 errors) ==== + interface Base { + x: T; + y: U; + } + + // Error, no Base constructor function + class D0 extends Base { + ~~~~ +!!! error TS2304: Cannot find name 'Base'. + } + + interface BaseConstructor { + new (x: string, y: string): Base; + new (x: T): Base; + new (x: T, y: T): Base; + new (x: T, y: U): Base; + } + + declare function getBase(): BaseConstructor; + + class D1 extends getBase() { + constructor() { + super("abc", "def"); + this.x = "x"; + this.y = "y"; + } + } + + class D2 extends getBase() { + constructor() { + super(10); + super(10, 20); + this.x = 1; + this.y = 2; + } + } + + class D3 extends getBase() { + constructor() { + super("abc", 42); + this.x = "x"; + this.y = 2; + } + } + + // Error, no constructors with three type arguments + class D4 extends getBase() { + ~~~~~~~~~ +!!! error TS2508: No base constructor has the specified number of type arguments. + } + + interface BadBaseConstructor { + new (x: string): Base; + new (x: number): Base; + } + + declare function getBadBase(): BadBaseConstructor; + + // Error, constructor return types differ + class D5 extends getBadBase() { + ~~~~~~~~~~~~ +!!! error TS2510: Base constructors must all have the same return type. + } + \ No newline at end of file diff --git a/tests/baselines/reference/classExtendingClassLikeType.js b/tests/baselines/reference/classExtendingClassLikeType.js new file mode 100644 index 00000000000..4634b22e493 --- /dev/null +++ b/tests/baselines/reference/classExtendingClassLikeType.js @@ -0,0 +1,118 @@ +//// [classExtendingClassLikeType.ts] +interface Base { + x: T; + y: U; +} + +// Error, no Base constructor function +class D0 extends Base { +} + +interface BaseConstructor { + new (x: string, y: string): Base; + new (x: T): Base; + new (x: T, y: T): Base; + new (x: T, y: U): Base; +} + +declare function getBase(): BaseConstructor; + +class D1 extends getBase() { + constructor() { + super("abc", "def"); + this.x = "x"; + this.y = "y"; + } +} + +class D2 extends getBase() { + constructor() { + super(10); + super(10, 20); + this.x = 1; + this.y = 2; + } +} + +class D3 extends getBase() { + constructor() { + super("abc", 42); + this.x = "x"; + this.y = 2; + } +} + +// Error, no constructors with three type arguments +class D4 extends getBase() { +} + +interface BadBaseConstructor { + new (x: string): Base; + new (x: number): Base; +} + +declare function getBadBase(): BadBaseConstructor; + +// Error, constructor return types differ +class D5 extends getBadBase() { +} + + +//// [classExtendingClassLikeType.js] +var __extends = (this && this.__extends) || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); +}; +// Error, no Base constructor function +var D0 = (function (_super) { + __extends(D0, _super); + function D0() { + _super.apply(this, arguments); + } + return D0; +})(Base); +var D1 = (function (_super) { + __extends(D1, _super); + function D1() { + _super.call(this, "abc", "def"); + this.x = "x"; + this.y = "y"; + } + return D1; +})(getBase()); +var D2 = (function (_super) { + __extends(D2, _super); + function D2() { + _super.call(this, 10); + _super.call(this, 10, 20); + this.x = 1; + this.y = 2; + } + return D2; +})(getBase()); +var D3 = (function (_super) { + __extends(D3, _super); + function D3() { + _super.call(this, "abc", 42); + this.x = "x"; + this.y = 2; + } + return D3; +})(getBase()); +// Error, no constructors with three type arguments +var D4 = (function (_super) { + __extends(D4, _super); + function D4() { + _super.apply(this, arguments); + } + return D4; +})(getBase()); +// Error, constructor return types differ +var D5 = (function (_super) { + __extends(D5, _super); + function D5() { + _super.apply(this, arguments); + } + return D5; +})(getBadBase()); diff --git a/tests/baselines/reference/classExtendingNonConstructor.errors.txt b/tests/baselines/reference/classExtendingNonConstructor.errors.txt new file mode 100644 index 00000000000..17b3610d252 --- /dev/null +++ b/tests/baselines/reference/classExtendingNonConstructor.errors.txt @@ -0,0 +1,38 @@ +tests/cases/conformance/classes/classDeclarations/classExtendingNonConstructor.ts(7,18): error TS2507: Type 'undefined' is not a constructor function type. +tests/cases/conformance/classes/classDeclarations/classExtendingNonConstructor.ts(8,18): error TS2507: Type 'boolean' is not a constructor function type. +tests/cases/conformance/classes/classDeclarations/classExtendingNonConstructor.ts(9,18): error TS2507: Type 'boolean' is not a constructor function type. +tests/cases/conformance/classes/classDeclarations/classExtendingNonConstructor.ts(10,18): error TS2507: Type 'number' is not a constructor function type. +tests/cases/conformance/classes/classDeclarations/classExtendingNonConstructor.ts(11,18): error TS2507: Type 'string' is not a constructor function type. +tests/cases/conformance/classes/classDeclarations/classExtendingNonConstructor.ts(12,18): error TS2507: Type '{}' is not a constructor function type. +tests/cases/conformance/classes/classDeclarations/classExtendingNonConstructor.ts(13,18): error TS2507: Type '() => void' is not a constructor function type. + + +==== tests/cases/conformance/classes/classDeclarations/classExtendingNonConstructor.ts (7 errors) ==== + var x: {}; + + function foo() { + this.x = 1; + } + + class C1 extends undefined { } + ~~~~~~~~~ +!!! error TS2507: Type 'undefined' is not a constructor function type. + class C2 extends true { } + ~~~~ +!!! error TS2507: Type 'boolean' is not a constructor function type. + class C3 extends false { } + ~~~~~ +!!! error TS2507: Type 'boolean' is not a constructor function type. + class C4 extends 42 { } + ~~ +!!! error TS2507: Type 'number' is not a constructor function type. + class C5 extends "hello" { } + ~~~~~~~ +!!! error TS2507: Type 'string' is not a constructor function type. + class C6 extends x { } + ~ +!!! error TS2507: Type '{}' is not a constructor function type. + class C7 extends foo { } + ~~~ +!!! error TS2507: Type '() => void' is not a constructor function type. + \ No newline at end of file diff --git a/tests/baselines/reference/classExtendingNonConstructor.js b/tests/baselines/reference/classExtendingNonConstructor.js new file mode 100644 index 00000000000..dff2fdf9ca9 --- /dev/null +++ b/tests/baselines/reference/classExtendingNonConstructor.js @@ -0,0 +1,75 @@ +//// [classExtendingNonConstructor.ts] +var x: {}; + +function foo() { + this.x = 1; +} + +class C1 extends undefined { } +class C2 extends true { } +class C3 extends false { } +class C4 extends 42 { } +class C5 extends "hello" { } +class C6 extends x { } +class C7 extends foo { } + + +//// [classExtendingNonConstructor.js] +var __extends = (this && this.__extends) || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); +}; +var x; +function foo() { + this.x = 1; +} +var C1 = (function (_super) { + __extends(C1, _super); + function C1() { + _super.apply(this, arguments); + } + return C1; +})(undefined); +var C2 = (function (_super) { + __extends(C2, _super); + function C2() { + _super.apply(this, arguments); + } + return C2; +})(true); +var C3 = (function (_super) { + __extends(C3, _super); + function C3() { + _super.apply(this, arguments); + } + return C3; +})(false); +var C4 = (function (_super) { + __extends(C4, _super); + function C4() { + _super.apply(this, arguments); + } + return C4; +})(42); +var C5 = (function (_super) { + __extends(C5, _super); + function C5() { + _super.apply(this, arguments); + } + return C5; +})("hello"); +var C6 = (function (_super) { + __extends(C6, _super); + function C6() { + _super.apply(this, arguments); + } + return C6; +})(x); +var C7 = (function (_super) { + __extends(C7, _super); + function C7() { + _super.apply(this, arguments); + } + return C7; +})(foo); diff --git a/tests/baselines/reference/classExtendingNull.js b/tests/baselines/reference/classExtendingNull.js new file mode 100644 index 00000000000..ac8009b9cd9 --- /dev/null +++ b/tests/baselines/reference/classExtendingNull.js @@ -0,0 +1,25 @@ +//// [classExtendingNull.ts] +class C1 extends null { } +class C2 extends (null) { } + + +//// [classExtendingNull.js] +var __extends = (this && this.__extends) || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); +}; +var C1 = (function (_super) { + __extends(C1, _super); + function C1() { + _super.apply(this, arguments); + } + return C1; +})(null); +var C2 = (function (_super) { + __extends(C2, _super); + function C2() { + _super.apply(this, arguments); + } + return C2; +})((null)); diff --git a/tests/baselines/reference/classExtendingNull.symbols b/tests/baselines/reference/classExtendingNull.symbols new file mode 100644 index 00000000000..37a6162f414 --- /dev/null +++ b/tests/baselines/reference/classExtendingNull.symbols @@ -0,0 +1,7 @@ +=== tests/cases/conformance/classes/classDeclarations/classExtendingNull.ts === +class C1 extends null { } +>C1 : Symbol(C1, Decl(classExtendingNull.ts, 0, 0)) + +class C2 extends (null) { } +>C2 : Symbol(C2, Decl(classExtendingNull.ts, 0, 25)) + diff --git a/tests/baselines/reference/classExtendingNull.types b/tests/baselines/reference/classExtendingNull.types new file mode 100644 index 00000000000..3c572a3406c --- /dev/null +++ b/tests/baselines/reference/classExtendingNull.types @@ -0,0 +1,10 @@ +=== tests/cases/conformance/classes/classDeclarations/classExtendingNull.ts === +class C1 extends null { } +>C1 : C1 +>null : null + +class C2 extends (null) { } +>C2 : C2 +>(null) : null +>null : null + diff --git a/tests/baselines/reference/classExtendingPrimitive.errors.txt b/tests/baselines/reference/classExtendingPrimitive.errors.txt index ae039640e99..554e0fbecbc 100644 --- a/tests/baselines/reference/classExtendingPrimitive.errors.txt +++ b/tests/baselines/reference/classExtendingPrimitive.errors.txt @@ -4,13 +4,12 @@ tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/cla tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendingPrimitive.ts(6,18): error TS2304: Cannot find name 'Void'. tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendingPrimitive.ts(7,19): error TS1109: Expression expected. tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendingPrimitive.ts(8,18): error TS2304: Cannot find name 'Null'. -tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendingPrimitive.ts(9,19): error TS9002: Only identifiers/qualified-names with optional type arguments are currently supported in a class 'extends' clauses. -tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendingPrimitive.ts(10,18): error TS2304: Cannot find name 'undefined'. +tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendingPrimitive.ts(10,18): error TS2507: Type 'undefined' is not a constructor function type. tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendingPrimitive.ts(11,18): error TS2304: Cannot find name 'Undefined'. -tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendingPrimitive.ts(14,18): error TS2311: A class may only extend another class. +tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendingPrimitive.ts(14,18): error TS2507: Type 'typeof E' is not a constructor function type. -==== tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendingPrimitive.ts (10 errors) ==== +==== tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendingPrimitive.ts (9 errors) ==== // classes cannot extend primitives class C extends number { } @@ -32,11 +31,9 @@ tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/cla ~~~~ !!! error TS2304: Cannot find name 'Null'. class C5a extends null { } - ~~~~ -!!! error TS9002: Only identifiers/qualified-names with optional type arguments are currently supported in a class 'extends' clauses. class C6 extends undefined { } ~~~~~~~~~ -!!! error TS2304: Cannot find name 'undefined'. +!!! error TS2507: Type 'undefined' is not a constructor function type. class C7 extends Undefined { } ~~~~~~~~~ !!! error TS2304: Cannot find name 'Undefined'. @@ -44,4 +41,4 @@ tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/cla enum E { A } class C8 extends E { } ~ -!!! error TS2311: A class may only extend another class. \ No newline at end of file +!!! error TS2507: Type 'typeof E' is not a constructor function type. \ No newline at end of file diff --git a/tests/baselines/reference/classExtendingPrimitive.js b/tests/baselines/reference/classExtendingPrimitive.js index b099ce763e8..cafa4eebcd1 100644 --- a/tests/baselines/reference/classExtendingPrimitive.js +++ b/tests/baselines/reference/classExtendingPrimitive.js @@ -19,8 +19,7 @@ class C8 extends E { } var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var C = (function (_super) { __extends(C, _super); diff --git a/tests/baselines/reference/classExtendingPrimitive2.errors.txt b/tests/baselines/reference/classExtendingPrimitive2.errors.txt index 3bba9b9e041..2303ca6323d 100644 --- a/tests/baselines/reference/classExtendingPrimitive2.errors.txt +++ b/tests/baselines/reference/classExtendingPrimitive2.errors.txt @@ -1,13 +1,10 @@ tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendingPrimitive2.ts(3,19): error TS1109: Expression expected. -tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendingPrimitive2.ts(4,19): error TS9002: Only identifiers/qualified-names with optional type arguments are currently supported in a class 'extends' clauses. -==== tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendingPrimitive2.ts (2 errors) ==== +==== tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendingPrimitive2.ts (1 errors) ==== // classes cannot extend primitives class C4a extends void {} ~~~~ !!! error TS1109: Expression expected. - class C5a extends null { } - ~~~~ -!!! error TS9002: Only identifiers/qualified-names with optional type arguments are currently supported in a class 'extends' clauses. \ No newline at end of file + class C5a extends null { } \ No newline at end of file diff --git a/tests/baselines/reference/classExtendingPrimitive2.js b/tests/baselines/reference/classExtendingPrimitive2.js index 3dcff0b44b9..4661ab961c9 100644 --- a/tests/baselines/reference/classExtendingPrimitive2.js +++ b/tests/baselines/reference/classExtendingPrimitive2.js @@ -9,8 +9,7 @@ class C5a extends null { } var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var C4a = (function () { function C4a() { diff --git a/tests/baselines/reference/classExtendingQualifiedName.errors.txt b/tests/baselines/reference/classExtendingQualifiedName.errors.txt index b63b3e23108..f04d07c89e6 100644 --- a/tests/baselines/reference/classExtendingQualifiedName.errors.txt +++ b/tests/baselines/reference/classExtendingQualifiedName.errors.txt @@ -1,4 +1,4 @@ -tests/cases/compiler/classExtendingQualifiedName.ts(5,23): error TS2305: Module 'M' has no exported member 'C'. +tests/cases/compiler/classExtendingQualifiedName.ts(5,23): error TS2339: Property 'C' does not exist on type 'typeof M'. ==== tests/cases/compiler/classExtendingQualifiedName.ts (1 errors) ==== @@ -8,6 +8,6 @@ tests/cases/compiler/classExtendingQualifiedName.ts(5,23): error TS2305: Module class D extends M.C { ~ -!!! error TS2305: Module 'M' has no exported member 'C'. +!!! error TS2339: Property 'C' does not exist on type 'typeof M'. } } \ No newline at end of file diff --git a/tests/baselines/reference/classExtendingQualifiedName.js b/tests/baselines/reference/classExtendingQualifiedName.js index 0289797d1e3..44a4fbe2bd6 100644 --- a/tests/baselines/reference/classExtendingQualifiedName.js +++ b/tests/baselines/reference/classExtendingQualifiedName.js @@ -11,8 +11,7 @@ module M { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var M; (function (M) { diff --git a/tests/baselines/reference/classExtendingQualifiedName2.js b/tests/baselines/reference/classExtendingQualifiedName2.js index 76065ccc577..afd432180d4 100644 --- a/tests/baselines/reference/classExtendingQualifiedName2.js +++ b/tests/baselines/reference/classExtendingQualifiedName2.js @@ -11,8 +11,7 @@ module M { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var M; (function (M) { diff --git a/tests/baselines/reference/classExtendingQualifiedName2.types b/tests/baselines/reference/classExtendingQualifiedName2.types index 9f0c03db17d..bd50fe3d2ce 100644 --- a/tests/baselines/reference/classExtendingQualifiedName2.types +++ b/tests/baselines/reference/classExtendingQualifiedName2.types @@ -8,8 +8,8 @@ module M { class D extends M.C { >D : D ->M.C : any +>M.C : C >M : typeof M ->C : C +>C : typeof C } } diff --git a/tests/baselines/reference/classExtendsClauseClassMergedWithModuleNotReferingConstructor.errors.txt b/tests/baselines/reference/classExtendsClauseClassMergedWithModuleNotReferingConstructor.errors.txt index 50c90389520..dfac4f68885 100644 --- a/tests/baselines/reference/classExtendsClauseClassMergedWithModuleNotReferingConstructor.errors.txt +++ b/tests/baselines/reference/classExtendsClauseClassMergedWithModuleNotReferingConstructor.errors.txt @@ -1,4 +1,4 @@ -tests/cases/compiler/classExtendsClauseClassMergedWithModuleNotReferingConstructor.ts(10,21): error TS2419: Type name 'A' in extends clause does not reference constructor function for 'A'. +tests/cases/compiler/classExtendsClauseClassMergedWithModuleNotReferingConstructor.ts(10,21): error TS2507: Type 'number' is not a constructor function type. ==== tests/cases/compiler/classExtendsClauseClassMergedWithModuleNotReferingConstructor.ts (1 errors) ==== @@ -13,7 +13,7 @@ tests/cases/compiler/classExtendsClauseClassMergedWithModuleNotReferingConstruct var A = 1; class B extends A { ~ -!!! error TS2419: Type name 'A' in extends clause does not reference constructor function for 'A'. +!!! error TS2507: Type 'number' is not a constructor function type. b: string; } } \ No newline at end of file diff --git a/tests/baselines/reference/classExtendsClauseClassMergedWithModuleNotReferingConstructor.js b/tests/baselines/reference/classExtendsClauseClassMergedWithModuleNotReferingConstructor.js index 726f918f4e8..fe8dc79b864 100644 --- a/tests/baselines/reference/classExtendsClauseClassMergedWithModuleNotReferingConstructor.js +++ b/tests/baselines/reference/classExtendsClauseClassMergedWithModuleNotReferingConstructor.js @@ -17,8 +17,7 @@ module Foo { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var A = (function () { function A() { diff --git a/tests/baselines/reference/classExtendsClauseClassNotReferringConstructor.errors.txt b/tests/baselines/reference/classExtendsClauseClassNotReferringConstructor.errors.txt index 7f8b6fb411b..ff355ec653c 100644 --- a/tests/baselines/reference/classExtendsClauseClassNotReferringConstructor.errors.txt +++ b/tests/baselines/reference/classExtendsClauseClassNotReferringConstructor.errors.txt @@ -1,4 +1,4 @@ -tests/cases/compiler/classExtendsClauseClassNotReferringConstructor.ts(4,21): error TS2419: Type name 'A' in extends clause does not reference constructor function for 'A'. +tests/cases/compiler/classExtendsClauseClassNotReferringConstructor.ts(4,21): error TS2507: Type 'number' is not a constructor function type. ==== tests/cases/compiler/classExtendsClauseClassNotReferringConstructor.ts (1 errors) ==== @@ -7,6 +7,6 @@ tests/cases/compiler/classExtendsClauseClassNotReferringConstructor.ts(4,21): er var A = 1; class B extends A { b: string; } ~ -!!! error TS2419: Type name 'A' in extends clause does not reference constructor function for 'A'. +!!! error TS2507: Type 'number' is not a constructor function type. } \ No newline at end of file diff --git a/tests/baselines/reference/classExtendsClauseClassNotReferringConstructor.js b/tests/baselines/reference/classExtendsClauseClassNotReferringConstructor.js index 8dc3410a179..94c50679151 100644 --- a/tests/baselines/reference/classExtendsClauseClassNotReferringConstructor.js +++ b/tests/baselines/reference/classExtendsClauseClassNotReferringConstructor.js @@ -10,8 +10,7 @@ module Foo { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var A = (function () { function A() { diff --git a/tests/baselines/reference/classExtendsEveryObjectType.errors.txt b/tests/baselines/reference/classExtendsEveryObjectType.errors.txt index 75eced53139..0339dfad13a 100644 --- a/tests/baselines/reference/classExtendsEveryObjectType.errors.txt +++ b/tests/baselines/reference/classExtendsEveryObjectType.errors.txt @@ -1,40 +1,43 @@ -tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendsEveryObjectType.ts(4,17): error TS2311: A class may only extend another class. -tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendsEveryObjectType.ts(6,18): error TS9002: Only identifiers/qualified-names with optional type arguments are currently supported in a class 'extends' clauses. +tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendsEveryObjectType.ts(4,17): error TS2304: Cannot find name 'I'. +tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendsEveryObjectType.ts(6,18): error TS2507: Type '{ foo: any; }' is not a constructor function type. +tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendsEveryObjectType.ts(6,25): error TS2304: Cannot find name 'string'. tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendsEveryObjectType.ts(6,31): error TS1005: ',' expected. -tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendsEveryObjectType.ts(8,18): error TS2304: Cannot find name 'x'. -tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendsEveryObjectType.ts(11,18): error TS2304: Cannot find name 'M'. -tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendsEveryObjectType.ts(14,18): error TS2304: Cannot find name 'foo'. -tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendsEveryObjectType.ts(16,18): error TS9002: Only identifiers/qualified-names with optional type arguments are currently supported in a class 'extends' clauses. +tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendsEveryObjectType.ts(8,18): error TS2507: Type '{ foo: string; }' is not a constructor function type. +tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendsEveryObjectType.ts(11,18): error TS2507: Type 'typeof M' is not a constructor function type. +tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendsEveryObjectType.ts(14,18): error TS2507: Type '() => void' is not a constructor function type. +tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendsEveryObjectType.ts(16,18): error TS2507: Type 'undefined[]' is not a constructor function type. -==== tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendsEveryObjectType.ts (7 errors) ==== +==== tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendsEveryObjectType.ts (8 errors) ==== interface I { foo: string; } class C extends I { } // error ~ -!!! error TS2311: A class may only extend another class. +!!! error TS2304: Cannot find name 'I'. class C2 extends { foo: string; } { } // error ~~~~~~~~~~~~~~~~ -!!! error TS9002: Only identifiers/qualified-names with optional type arguments are currently supported in a class 'extends' clauses. +!!! error TS2507: Type '{ foo: any; }' is not a constructor function type. + ~~~~~~ +!!! error TS2304: Cannot find name 'string'. ~ !!! error TS1005: ',' expected. var x: { foo: string; } class C3 extends x { } // error ~ -!!! error TS2304: Cannot find name 'x'. +!!! error TS2507: Type '{ foo: string; }' is not a constructor function type. module M { export var x = 1; } class C4 extends M { } // error ~ -!!! error TS2304: Cannot find name 'M'. +!!! error TS2507: Type 'typeof M' is not a constructor function type. function foo() { } class C5 extends foo { } // error ~~~ -!!! error TS2304: Cannot find name 'foo'. +!!! error TS2507: Type '() => void' is not a constructor function type. class C6 extends []{ } // error ~~ -!!! error TS9002: Only identifiers/qualified-names with optional type arguments are currently supported in a class 'extends' clauses. \ No newline at end of file +!!! error TS2507: Type 'undefined[]' is not a constructor function type. \ No newline at end of file diff --git a/tests/baselines/reference/classExtendsEveryObjectType.js b/tests/baselines/reference/classExtendsEveryObjectType.js index afbb4dab714..92414c7e6c3 100644 --- a/tests/baselines/reference/classExtendsEveryObjectType.js +++ b/tests/baselines/reference/classExtendsEveryObjectType.js @@ -20,8 +20,7 @@ class C6 extends []{ } // error var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var C = (function (_super) { __extends(C, _super); diff --git a/tests/baselines/reference/classExtendsEveryObjectType2.errors.txt b/tests/baselines/reference/classExtendsEveryObjectType2.errors.txt index 45a63030d00..af52a248b54 100644 --- a/tests/baselines/reference/classExtendsEveryObjectType2.errors.txt +++ b/tests/baselines/reference/classExtendsEveryObjectType2.errors.txt @@ -1,15 +1,18 @@ -tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendsEveryObjectType2.ts(1,18): error TS9002: Only identifiers/qualified-names with optional type arguments are currently supported in a class 'extends' clauses. +tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendsEveryObjectType2.ts(1,18): error TS2507: Type '{ foo: any; }' is not a constructor function type. +tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendsEveryObjectType2.ts(1,25): error TS2304: Cannot find name 'string'. tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendsEveryObjectType2.ts(1,31): error TS1005: ',' expected. -tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendsEveryObjectType2.ts(3,18): error TS9002: Only identifiers/qualified-names with optional type arguments are currently supported in a class 'extends' clauses. +tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendsEveryObjectType2.ts(3,18): error TS2507: Type 'undefined[]' is not a constructor function type. -==== tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendsEveryObjectType2.ts (3 errors) ==== +==== tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendsEveryObjectType2.ts (4 errors) ==== class C2 extends { foo: string; } { } // error ~~~~~~~~~~~~~~~~ -!!! error TS9002: Only identifiers/qualified-names with optional type arguments are currently supported in a class 'extends' clauses. +!!! error TS2507: Type '{ foo: any; }' is not a constructor function type. + ~~~~~~ +!!! error TS2304: Cannot find name 'string'. ~ !!! error TS1005: ',' expected. class C6 extends []{ } // error ~~ -!!! error TS9002: Only identifiers/qualified-names with optional type arguments are currently supported in a class 'extends' clauses. \ No newline at end of file +!!! error TS2507: Type 'undefined[]' is not a constructor function type. \ No newline at end of file diff --git a/tests/baselines/reference/classExtendsEveryObjectType2.js b/tests/baselines/reference/classExtendsEveryObjectType2.js index c41943072dd..2735032f3c4 100644 --- a/tests/baselines/reference/classExtendsEveryObjectType2.js +++ b/tests/baselines/reference/classExtendsEveryObjectType2.js @@ -7,8 +7,7 @@ class C6 extends []{ } // error var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var C2 = (function (_super) { __extends(C2, _super); diff --git a/tests/baselines/reference/classExtendsInterface.errors.txt b/tests/baselines/reference/classExtendsInterface.errors.txt index 746f3c4bea0..2ecca6cf2cf 100644 --- a/tests/baselines/reference/classExtendsInterface.errors.txt +++ b/tests/baselines/reference/classExtendsInterface.errors.txt @@ -1,17 +1,17 @@ -tests/cases/compiler/classExtendsInterface.ts(2,17): error TS2311: A class may only extend another class. -tests/cases/compiler/classExtendsInterface.ts(6,21): error TS2311: A class may only extend another class. +tests/cases/compiler/classExtendsInterface.ts(2,17): error TS2304: Cannot find name 'Comparable'. +tests/cases/compiler/classExtendsInterface.ts(6,21): error TS2304: Cannot find name 'Comparable2'. ==== tests/cases/compiler/classExtendsInterface.ts (2 errors) ==== interface Comparable {} class A extends Comparable {} ~~~~~~~~~~ -!!! error TS2311: A class may only extend another class. +!!! error TS2304: Cannot find name 'Comparable'. class B implements Comparable {} interface Comparable2 {} class A2 extends Comparable2 {} - ~~~~~~~~~~~~~~ -!!! error TS2311: A class may only extend another class. + ~~~~~~~~~~~ +!!! error TS2304: Cannot find name 'Comparable2'. class B2 implements Comparable2 {} \ No newline at end of file diff --git a/tests/baselines/reference/classExtendsInterface.js b/tests/baselines/reference/classExtendsInterface.js index a3e596299fa..9b78cde35e9 100644 --- a/tests/baselines/reference/classExtendsInterface.js +++ b/tests/baselines/reference/classExtendsInterface.js @@ -12,8 +12,7 @@ class B2 implements Comparable2 {} var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var A = (function (_super) { __extends(A, _super); diff --git a/tests/baselines/reference/classExtendsItself.errors.txt b/tests/baselines/reference/classExtendsItself.errors.txt index bd15ae22c12..9dd3bcc2202 100644 --- a/tests/baselines/reference/classExtendsItself.errors.txt +++ b/tests/baselines/reference/classExtendsItself.errors.txt @@ -1,17 +1,17 @@ -tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendsItself.ts(1,7): error TS2310: Type 'C' recursively references itself as a base type. -tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendsItself.ts(3,7): error TS2310: Type 'D' recursively references itself as a base type. -tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendsItself.ts(5,7): error TS2310: Type 'E' recursively references itself as a base type. +tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendsItself.ts(1,7): error TS2506: 'C' is referenced directly or indirectly in its own base expression. +tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendsItself.ts(3,7): error TS2506: 'D' is referenced directly or indirectly in its own base expression. +tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendsItself.ts(5,7): error TS2506: 'E' is referenced directly or indirectly in its own base expression. ==== tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendsItself.ts (3 errors) ==== class C extends C { } // error ~ -!!! error TS2310: Type 'C' recursively references itself as a base type. +!!! error TS2506: 'C' is referenced directly or indirectly in its own base expression. class D extends D { } // error ~ -!!! error TS2310: Type 'D' recursively references itself as a base type. +!!! error TS2506: 'D' is referenced directly or indirectly in its own base expression. class E extends E { } // error ~ -!!! error TS2310: Type 'E' recursively references itself as a base type. \ No newline at end of file +!!! error TS2506: 'E' is referenced directly or indirectly in its own base expression. \ No newline at end of file diff --git a/tests/baselines/reference/classExtendsItself.js b/tests/baselines/reference/classExtendsItself.js index 79a4226731f..c370e797a57 100644 --- a/tests/baselines/reference/classExtendsItself.js +++ b/tests/baselines/reference/classExtendsItself.js @@ -9,8 +9,7 @@ class E extends E { } // error var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var C = (function (_super) { __extends(C, _super); diff --git a/tests/baselines/reference/classExtendsItselfIndirectly.errors.txt b/tests/baselines/reference/classExtendsItselfIndirectly.errors.txt index b39ef5b905f..c0f35f0388f 100644 --- a/tests/baselines/reference/classExtendsItselfIndirectly.errors.txt +++ b/tests/baselines/reference/classExtendsItselfIndirectly.errors.txt @@ -1,20 +1,32 @@ -tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendsItselfIndirectly.ts(1,7): error TS2310: Type 'C' recursively references itself as a base type. -tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendsItselfIndirectly.ts(7,7): error TS2310: Type 'C2' recursively references itself as a base type. +tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendsItselfIndirectly.ts(1,7): error TS2506: 'C' is referenced directly or indirectly in its own base expression. +tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendsItselfIndirectly.ts(3,7): error TS2506: 'D' is referenced directly or indirectly in its own base expression. +tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendsItselfIndirectly.ts(5,7): error TS2506: 'E' is referenced directly or indirectly in its own base expression. +tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendsItselfIndirectly.ts(7,7): error TS2506: 'C2' is referenced directly or indirectly in its own base expression. +tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendsItselfIndirectly.ts(9,7): error TS2506: 'D2' is referenced directly or indirectly in its own base expression. +tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendsItselfIndirectly.ts(11,7): error TS2506: 'E2' is referenced directly or indirectly in its own base expression. -==== tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendsItselfIndirectly.ts (2 errors) ==== +==== tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendsItselfIndirectly.ts (6 errors) ==== class C extends E { foo: string; } // error ~ -!!! error TS2310: Type 'C' recursively references itself as a base type. +!!! error TS2506: 'C' is referenced directly or indirectly in its own base expression. class D extends C { bar: string; } + ~ +!!! error TS2506: 'D' is referenced directly or indirectly in its own base expression. class E extends D { baz: number; } + ~ +!!! error TS2506: 'E' is referenced directly or indirectly in its own base expression. class C2 extends E2 { foo: T; } // error ~~ -!!! error TS2310: Type 'C2' recursively references itself as a base type. +!!! error TS2506: 'C2' is referenced directly or indirectly in its own base expression. class D2 extends C2 { bar: T; } + ~~ +!!! error TS2506: 'D2' is referenced directly or indirectly in its own base expression. - class E2 extends D2 { baz: T; } \ No newline at end of file + class E2 extends D2 { baz: T; } + ~~ +!!! error TS2506: 'E2' is referenced directly or indirectly in its own base expression. \ No newline at end of file diff --git a/tests/baselines/reference/classExtendsItselfIndirectly.js b/tests/baselines/reference/classExtendsItselfIndirectly.js index eee52b877e3..65cd72ce3c8 100644 --- a/tests/baselines/reference/classExtendsItselfIndirectly.js +++ b/tests/baselines/reference/classExtendsItselfIndirectly.js @@ -15,8 +15,7 @@ class E2 extends D2 { baz: T; } var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var C = (function (_super) { __extends(C, _super); diff --git a/tests/baselines/reference/classExtendsItselfIndirectly2.errors.txt b/tests/baselines/reference/classExtendsItselfIndirectly2.errors.txt index a61291b5aa9..061770f9b79 100644 --- a/tests/baselines/reference/classExtendsItselfIndirectly2.errors.txt +++ b/tests/baselines/reference/classExtendsItselfIndirectly2.errors.txt @@ -1,31 +1,43 @@ -tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendsItselfIndirectly2.ts(1,7): error TS2310: Type 'C' recursively references itself as a base type. -tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendsItselfIndirectly2.ts(13,11): error TS2310: Type 'C2' recursively references itself as a base type. +tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendsItselfIndirectly2.ts(1,7): error TS2506: 'C' is referenced directly or indirectly in its own base expression. +tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendsItselfIndirectly2.ts(4,18): error TS2506: 'D' is referenced directly or indirectly in its own base expression. +tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendsItselfIndirectly2.ts(9,18): error TS2506: 'E' is referenced directly or indirectly in its own base expression. +tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendsItselfIndirectly2.ts(13,11): error TS2506: 'C2' is referenced directly or indirectly in its own base expression. +tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendsItselfIndirectly2.ts(16,22): error TS2506: 'D2' is referenced directly or indirectly in its own base expression. +tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendsItselfIndirectly2.ts(20,22): error TS2506: 'E2' is referenced directly or indirectly in its own base expression. -==== tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendsItselfIndirectly2.ts (2 errors) ==== +==== tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendsItselfIndirectly2.ts (6 errors) ==== class C extends N.E { foo: string; } // error ~ -!!! error TS2310: Type 'C' recursively references itself as a base type. +!!! error TS2506: 'C' is referenced directly or indirectly in its own base expression. module M { export class D extends C { bar: string; } + ~ +!!! error TS2506: 'D' is referenced directly or indirectly in its own base expression. } module N { export class E extends M.D { baz: number; } + ~ +!!! error TS2506: 'E' is referenced directly or indirectly in its own base expression. } module O { class C2 extends Q.E2 { foo: T; } // error ~~ -!!! error TS2310: Type 'C2' recursively references itself as a base type. +!!! error TS2506: 'C2' is referenced directly or indirectly in its own base expression. module P { export class D2 extends C2 { bar: T; } + ~~ +!!! error TS2506: 'D2' is referenced directly or indirectly in its own base expression. } module Q { export class E2 extends P.D2 { baz: T; } + ~~ +!!! error TS2506: 'E2' is referenced directly or indirectly in its own base expression. } } \ No newline at end of file diff --git a/tests/baselines/reference/classExtendsItselfIndirectly2.js b/tests/baselines/reference/classExtendsItselfIndirectly2.js index 02201425cba..c0b46e6cbb6 100644 --- a/tests/baselines/reference/classExtendsItselfIndirectly2.js +++ b/tests/baselines/reference/classExtendsItselfIndirectly2.js @@ -26,8 +26,7 @@ module O { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var C = (function (_super) { __extends(C, _super); diff --git a/tests/baselines/reference/classExtendsItselfIndirectly3.errors.txt b/tests/baselines/reference/classExtendsItselfIndirectly3.errors.txt index 8430ec887b5..411ea4cb580 100644 --- a/tests/baselines/reference/classExtendsItselfIndirectly3.errors.txt +++ b/tests/baselines/reference/classExtendsItselfIndirectly3.errors.txt @@ -1,25 +1,37 @@ -tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendsItselfIndirectly_file1.ts(1,7): error TS2310: Type 'C' recursively references itself as a base type. -tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendsItselfIndirectly_file4.ts(1,7): error TS2310: Type 'C2' recursively references itself as a base type. +tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendsItselfIndirectly_file1.ts(1,7): error TS2506: 'C' is referenced directly or indirectly in its own base expression. +tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendsItselfIndirectly_file2.ts(1,7): error TS2506: 'D' is referenced directly or indirectly in its own base expression. +tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendsItselfIndirectly_file3.ts(1,7): error TS2506: 'E' is referenced directly or indirectly in its own base expression. +tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendsItselfIndirectly_file4.ts(1,7): error TS2506: 'C2' is referenced directly or indirectly in its own base expression. +tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendsItselfIndirectly_file5.ts(1,7): error TS2506: 'D2' is referenced directly or indirectly in its own base expression. +tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendsItselfIndirectly_file6.ts(1,7): error TS2506: 'E2' is referenced directly or indirectly in its own base expression. ==== tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendsItselfIndirectly_file1.ts (1 errors) ==== class C extends E { foo: string; } // error ~ -!!! error TS2310: Type 'C' recursively references itself as a base type. +!!! error TS2506: 'C' is referenced directly or indirectly in its own base expression. -==== tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendsItselfIndirectly_file2.ts (0 errors) ==== +==== tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendsItselfIndirectly_file2.ts (1 errors) ==== class D extends C { bar: string; } + ~ +!!! error TS2506: 'D' is referenced directly or indirectly in its own base expression. -==== tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendsItselfIndirectly_file3.ts (0 errors) ==== +==== tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendsItselfIndirectly_file3.ts (1 errors) ==== class E extends D { baz: number; } + ~ +!!! error TS2506: 'E' is referenced directly or indirectly in its own base expression. ==== tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendsItselfIndirectly_file4.ts (1 errors) ==== class C2 extends E2 { foo: T; } // error ~~ -!!! error TS2310: Type 'C2' recursively references itself as a base type. +!!! error TS2506: 'C2' is referenced directly or indirectly in its own base expression. -==== tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendsItselfIndirectly_file5.ts (0 errors) ==== +==== tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendsItselfIndirectly_file5.ts (1 errors) ==== class D2 extends C2 { bar: T; } + ~~ +!!! error TS2506: 'D2' is referenced directly or indirectly in its own base expression. -==== tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendsItselfIndirectly_file6.ts (0 errors) ==== - class E2 extends D2 { baz: T; } \ No newline at end of file +==== tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendsItselfIndirectly_file6.ts (1 errors) ==== + class E2 extends D2 { baz: T; } + ~~ +!!! error TS2506: 'E2' is referenced directly or indirectly in its own base expression. \ No newline at end of file diff --git a/tests/baselines/reference/classExtendsItselfIndirectly3.js b/tests/baselines/reference/classExtendsItselfIndirectly3.js index bff6dd92bc9..9241403a7ce 100644 --- a/tests/baselines/reference/classExtendsItselfIndirectly3.js +++ b/tests/baselines/reference/classExtendsItselfIndirectly3.js @@ -22,8 +22,7 @@ class E2 extends D2 { baz: T; } var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var C = (function (_super) { __extends(C, _super); @@ -36,8 +35,7 @@ var C = (function (_super) { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var D = (function (_super) { __extends(D, _super); @@ -50,8 +48,7 @@ var D = (function (_super) { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var E = (function (_super) { __extends(E, _super); @@ -64,8 +61,7 @@ var E = (function (_super) { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var C2 = (function (_super) { __extends(C2, _super); @@ -78,8 +74,7 @@ var C2 = (function (_super) { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var D2 = (function (_super) { __extends(D2, _super); @@ -92,8 +87,7 @@ var D2 = (function (_super) { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var E2 = (function (_super) { __extends(E2, _super); diff --git a/tests/baselines/reference/classExtendsMultipleBaseClasses.js b/tests/baselines/reference/classExtendsMultipleBaseClasses.js index 7027e85450d..d1ffee30415 100644 --- a/tests/baselines/reference/classExtendsMultipleBaseClasses.js +++ b/tests/baselines/reference/classExtendsMultipleBaseClasses.js @@ -7,8 +7,7 @@ class C extends A,B { } var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var A = (function () { function A() { diff --git a/tests/baselines/reference/classExtendsShadowedConstructorFunction.errors.txt b/tests/baselines/reference/classExtendsShadowedConstructorFunction.errors.txt index 782dd2a2dbc..3d8c7454255 100644 --- a/tests/baselines/reference/classExtendsShadowedConstructorFunction.errors.txt +++ b/tests/baselines/reference/classExtendsShadowedConstructorFunction.errors.txt @@ -1,4 +1,4 @@ -tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendsShadowedConstructorFunction.ts(5,21): error TS2419: Type name 'C' in extends clause does not reference constructor function for 'C'. +tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendsShadowedConstructorFunction.ts(5,21): error TS2507: Type 'number' is not a constructor function type. ==== tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendsShadowedConstructorFunction.ts (1 errors) ==== @@ -8,7 +8,7 @@ tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/cla var C = 1; class D extends C { // error, C must evaluate to constructor function ~ -!!! error TS2419: Type name 'C' in extends clause does not reference constructor function for 'C'. +!!! error TS2507: Type 'number' is not a constructor function type. bar: string; } } \ No newline at end of file diff --git a/tests/baselines/reference/classExtendsShadowedConstructorFunction.js b/tests/baselines/reference/classExtendsShadowedConstructorFunction.js index 48f2e791139..164ffdc8493 100644 --- a/tests/baselines/reference/classExtendsShadowedConstructorFunction.js +++ b/tests/baselines/reference/classExtendsShadowedConstructorFunction.js @@ -12,8 +12,7 @@ module M { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var C = (function () { function C() { diff --git a/tests/baselines/reference/classExtendsValidConstructorFunction.errors.txt b/tests/baselines/reference/classExtendsValidConstructorFunction.errors.txt index ad2262819ed..fdfd9110ce6 100644 --- a/tests/baselines/reference/classExtendsValidConstructorFunction.errors.txt +++ b/tests/baselines/reference/classExtendsValidConstructorFunction.errors.txt @@ -1,4 +1,4 @@ -tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendsValidConstructorFunction.ts(5,17): error TS2304: Cannot find name 'foo'. +tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendsValidConstructorFunction.ts(5,17): error TS2507: Type '() => void' is not a constructor function type. ==== tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/classExtendsValidConstructorFunction.ts (1 errors) ==== @@ -8,4 +8,4 @@ tests/cases/conformance/classes/classDeclarations/classHeritageSpecification/cla class C extends foo { } // error, cannot extend it though ~~~ -!!! error TS2304: Cannot find name 'foo'. \ No newline at end of file +!!! error TS2507: Type '() => void' is not a constructor function type. \ No newline at end of file diff --git a/tests/baselines/reference/classExtendsValidConstructorFunction.js b/tests/baselines/reference/classExtendsValidConstructorFunction.js index 411bd3c2fba..448db68db9f 100644 --- a/tests/baselines/reference/classExtendsValidConstructorFunction.js +++ b/tests/baselines/reference/classExtendsValidConstructorFunction.js @@ -9,8 +9,7 @@ class C extends foo { } // error, cannot extend it though var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; function foo() { } var x = new foo(); // can be used as a constructor function diff --git a/tests/baselines/reference/classHeritageWithTrailingSeparator.js b/tests/baselines/reference/classHeritageWithTrailingSeparator.js index 6d33f79a4d5..2d5b12d5201 100644 --- a/tests/baselines/reference/classHeritageWithTrailingSeparator.js +++ b/tests/baselines/reference/classHeritageWithTrailingSeparator.js @@ -7,8 +7,7 @@ class D extends C, { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var C = (function () { function C() { diff --git a/tests/baselines/reference/classImplementsClass2.js b/tests/baselines/reference/classImplementsClass2.js index 49b73bfdb18..490d2706b48 100644 --- a/tests/baselines/reference/classImplementsClass2.js +++ b/tests/baselines/reference/classImplementsClass2.js @@ -17,8 +17,7 @@ c2 = c; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var A = (function () { function A() { diff --git a/tests/baselines/reference/classImplementsClass3.js b/tests/baselines/reference/classImplementsClass3.js index f8773b435bd..00cb49e2da3 100644 --- a/tests/baselines/reference/classImplementsClass3.js +++ b/tests/baselines/reference/classImplementsClass3.js @@ -18,8 +18,7 @@ c2 = c; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var A = (function () { function A() { diff --git a/tests/baselines/reference/classImplementsClass4.js b/tests/baselines/reference/classImplementsClass4.js index cf442b0ad24..0d7508b723b 100644 --- a/tests/baselines/reference/classImplementsClass4.js +++ b/tests/baselines/reference/classImplementsClass4.js @@ -20,8 +20,7 @@ c2 = c; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var A = (function () { function A() { diff --git a/tests/baselines/reference/classImplementsClass5.js b/tests/baselines/reference/classImplementsClass5.js index a648f6bd63f..caacb7b3044 100644 --- a/tests/baselines/reference/classImplementsClass5.js +++ b/tests/baselines/reference/classImplementsClass5.js @@ -21,8 +21,7 @@ c2 = c; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var A = (function () { function A() { diff --git a/tests/baselines/reference/classImplementsClass6.js b/tests/baselines/reference/classImplementsClass6.js index af6f0844d28..2e8d765be89 100644 --- a/tests/baselines/reference/classImplementsClass6.js +++ b/tests/baselines/reference/classImplementsClass6.js @@ -25,8 +25,7 @@ c2.bar(); // should error var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var A = (function () { function A() { diff --git a/tests/baselines/reference/classIndexer3.js b/tests/baselines/reference/classIndexer3.js index 9f630b96306..e962c7295f2 100644 --- a/tests/baselines/reference/classIndexer3.js +++ b/tests/baselines/reference/classIndexer3.js @@ -14,8 +14,7 @@ class D123 extends C123 { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var C123 = (function () { function C123() { diff --git a/tests/baselines/reference/classInheritence.errors.txt b/tests/baselines/reference/classInheritence.errors.txt index 483812c6b5f..cba8c040d6e 100644 --- a/tests/baselines/reference/classInheritence.errors.txt +++ b/tests/baselines/reference/classInheritence.errors.txt @@ -1,8 +1,8 @@ -tests/cases/compiler/classInheritence.ts(2,7): error TS2310: Type 'A' recursively references itself as a base type. +tests/cases/compiler/classInheritence.ts(2,7): error TS2506: 'A' is referenced directly or indirectly in its own base expression. ==== tests/cases/compiler/classInheritence.ts (1 errors) ==== class B extends A { } class A extends A { } ~ -!!! error TS2310: Type 'A' recursively references itself as a base type. \ No newline at end of file +!!! error TS2506: 'A' is referenced directly or indirectly in its own base expression. \ No newline at end of file diff --git a/tests/baselines/reference/classInheritence.js b/tests/baselines/reference/classInheritence.js index 374248c3a2c..1e463dd195d 100644 --- a/tests/baselines/reference/classInheritence.js +++ b/tests/baselines/reference/classInheritence.js @@ -6,8 +6,7 @@ class A extends A { } var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var B = (function (_super) { __extends(B, _super); diff --git a/tests/baselines/reference/classInsideBlock.errors.txt b/tests/baselines/reference/classInsideBlock.errors.txt deleted file mode 100644 index 369e77735e2..00000000000 --- a/tests/baselines/reference/classInsideBlock.errors.txt +++ /dev/null @@ -1,9 +0,0 @@ -tests/cases/conformance/classes/classDeclarations/classInsideBlock.ts(2,11): error TS9004: 'class' declarations are only supported directly inside a module or as a top level declaration. - - -==== tests/cases/conformance/classes/classDeclarations/classInsideBlock.ts (1 errors) ==== - function foo() { - class C { } - ~ -!!! error TS9004: 'class' declarations are only supported directly inside a module or as a top level declaration. - } \ No newline at end of file diff --git a/tests/baselines/reference/classInsideBlock.symbols b/tests/baselines/reference/classInsideBlock.symbols new file mode 100644 index 00000000000..5f96dd1b751 --- /dev/null +++ b/tests/baselines/reference/classInsideBlock.symbols @@ -0,0 +1,7 @@ +=== tests/cases/conformance/classes/classDeclarations/classInsideBlock.ts === +function foo() { +>foo : Symbol(foo, Decl(classInsideBlock.ts, 0, 0)) + + class C { } +>C : Symbol(C, Decl(classInsideBlock.ts, 0, 16)) +} diff --git a/tests/baselines/reference/classInsideBlock.types b/tests/baselines/reference/classInsideBlock.types new file mode 100644 index 00000000000..7db5653c475 --- /dev/null +++ b/tests/baselines/reference/classInsideBlock.types @@ -0,0 +1,7 @@ +=== tests/cases/conformance/classes/classDeclarations/classInsideBlock.ts === +function foo() { +>foo : () => void + + class C { } +>C : C +} diff --git a/tests/baselines/reference/classIsSubtypeOfBaseType.js b/tests/baselines/reference/classIsSubtypeOfBaseType.js index a33bf5499be..a92cfb430bf 100644 --- a/tests/baselines/reference/classIsSubtypeOfBaseType.js +++ b/tests/baselines/reference/classIsSubtypeOfBaseType.js @@ -19,8 +19,7 @@ class Derived2 extends Base<{ bar: string; }> { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var Base = (function () { function Base() { diff --git a/tests/baselines/reference/classMemberWithMissingIdentifier.errors.txt b/tests/baselines/reference/classMemberWithMissingIdentifier.errors.txt new file mode 100644 index 00000000000..4bbc2d8167d --- /dev/null +++ b/tests/baselines/reference/classMemberWithMissingIdentifier.errors.txt @@ -0,0 +1,12 @@ +tests/cases/compiler/classMemberWithMissingIdentifier.ts(2,11): error TS1146: Declaration expected. +tests/cases/compiler/classMemberWithMissingIdentifier.ts(2,12): error TS1005: '=' expected. + + +==== tests/cases/compiler/classMemberWithMissingIdentifier.ts (2 errors) ==== + class C { + public {}; + +!!! error TS1146: Declaration expected. + ~ +!!! error TS1005: '=' expected. + } \ No newline at end of file diff --git a/tests/baselines/reference/classMemberWithMissingIdentifier.js b/tests/baselines/reference/classMemberWithMissingIdentifier.js new file mode 100644 index 00000000000..cd1825d0da0 --- /dev/null +++ b/tests/baselines/reference/classMemberWithMissingIdentifier.js @@ -0,0 +1,12 @@ +//// [classMemberWithMissingIdentifier.ts] +class C { + public {}; +} + +//// [classMemberWithMissingIdentifier.js] +var C = (function () { + function C() { + this. = {}; + } + return C; +})(); diff --git a/tests/baselines/reference/classMemberWithMissingIdentifier2.errors.txt b/tests/baselines/reference/classMemberWithMissingIdentifier2.errors.txt new file mode 100644 index 00000000000..b21e062e3b0 --- /dev/null +++ b/tests/baselines/reference/classMemberWithMissingIdentifier2.errors.txt @@ -0,0 +1,30 @@ +tests/cases/compiler/classMemberWithMissingIdentifier2.ts(2,11): error TS1146: Declaration expected. +tests/cases/compiler/classMemberWithMissingIdentifier2.ts(2,12): error TS1005: '=' expected. +tests/cases/compiler/classMemberWithMissingIdentifier2.ts(2,14): error TS2304: Cannot find name 'name'. +tests/cases/compiler/classMemberWithMissingIdentifier2.ts(2,18): error TS1005: ']' expected. +tests/cases/compiler/classMemberWithMissingIdentifier2.ts(2,19): error TS2304: Cannot find name 'string'. +tests/cases/compiler/classMemberWithMissingIdentifier2.ts(2,25): error TS1005: ',' expected. +tests/cases/compiler/classMemberWithMissingIdentifier2.ts(2,26): error TS1136: Property assignment expected. +tests/cases/compiler/classMemberWithMissingIdentifier2.ts(2,27): error TS2304: Cannot find name 'VariableDeclaration'. + + +==== tests/cases/compiler/classMemberWithMissingIdentifier2.ts (8 errors) ==== + class C { + public {[name:string]:VariableDeclaration}; + +!!! error TS1146: Declaration expected. + ~ +!!! error TS1005: '=' expected. + ~~~~ +!!! error TS2304: Cannot find name 'name'. + ~ +!!! error TS1005: ']' expected. + ~~~~~~ +!!! error TS2304: Cannot find name 'string'. + ~ +!!! error TS1005: ',' expected. + ~ +!!! error TS1136: Property assignment expected. + ~~~~~~~~~~~~~~~~~~~ +!!! error TS2304: Cannot find name 'VariableDeclaration'. + } \ No newline at end of file diff --git a/tests/baselines/reference/classMemberWithMissingIdentifier2.js b/tests/baselines/reference/classMemberWithMissingIdentifier2.js new file mode 100644 index 00000000000..e8494755b22 --- /dev/null +++ b/tests/baselines/reference/classMemberWithMissingIdentifier2.js @@ -0,0 +1,13 @@ +//// [classMemberWithMissingIdentifier2.ts] +class C { + public {[name:string]:VariableDeclaration}; +} + +//// [classMemberWithMissingIdentifier2.js] +var C = (function () { + function C() { + this. = (_a = {}, _a[name] = string, _a.VariableDeclaration = VariableDeclaration, _a); + var _a; + } + return C; +})(); diff --git a/tests/baselines/reference/classOrder2.js b/tests/baselines/reference/classOrder2.js index 8eed39bddeb..fd3fee2e037 100644 --- a/tests/baselines/reference/classOrder2.js +++ b/tests/baselines/reference/classOrder2.js @@ -23,8 +23,7 @@ a.foo(); var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var A = (function (_super) { __extends(A, _super); diff --git a/tests/baselines/reference/classOrderBug.js b/tests/baselines/reference/classOrderBug.js index ae50152d608..bc3f0e739c4 100644 --- a/tests/baselines/reference/classOrderBug.js +++ b/tests/baselines/reference/classOrderBug.js @@ -19,8 +19,7 @@ class foo extends baz {} var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var bar = (function () { function bar() { diff --git a/tests/baselines/reference/classSideInheritance1.js b/tests/baselines/reference/classSideInheritance1.js index 66cbc0c25c7..6d217149b83 100644 --- a/tests/baselines/reference/classSideInheritance1.js +++ b/tests/baselines/reference/classSideInheritance1.js @@ -19,8 +19,7 @@ C2.bar(); // valid var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var A = (function () { function A() { diff --git a/tests/baselines/reference/classSideInheritance2.js b/tests/baselines/reference/classSideInheritance2.js index e09301fe85f..fb6f0d8cbb9 100644 --- a/tests/baselines/reference/classSideInheritance2.js +++ b/tests/baselines/reference/classSideInheritance2.js @@ -24,8 +24,7 @@ class TextBase implements IText { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var SubText = (function (_super) { __extends(SubText, _super); diff --git a/tests/baselines/reference/classSideInheritance3.js b/tests/baselines/reference/classSideInheritance3.js index a69b6ff0345..0891a7c9e74 100644 --- a/tests/baselines/reference/classSideInheritance3.js +++ b/tests/baselines/reference/classSideInheritance3.js @@ -22,8 +22,7 @@ var r3: typeof A = C; // ok var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var A = (function () { function A(x) { diff --git a/tests/baselines/reference/classUpdateTests.errors.txt b/tests/baselines/reference/classUpdateTests.errors.txt index e7f34fec546..59e9bc9ced1 100644 --- a/tests/baselines/reference/classUpdateTests.errors.txt +++ b/tests/baselines/reference/classUpdateTests.errors.txt @@ -1,26 +1,24 @@ tests/cases/compiler/classUpdateTests.ts(34,2): error TS2377: Constructors for derived classes must contain a 'super' call. tests/cases/compiler/classUpdateTests.ts(43,18): error TS2335: 'super' can only be referenced in a derived class. -tests/cases/compiler/classUpdateTests.ts(46,17): error TS2311: A class may only extend another class. -tests/cases/compiler/classUpdateTests.ts(47,18): error TS2335: 'super' can only be referenced in a derived class. tests/cases/compiler/classUpdateTests.ts(57,2): error TS2376: A 'super' call must be the first statement in the constructor when a class contains initialized properties or has parameter properties. tests/cases/compiler/classUpdateTests.ts(63,7): error TS2415: Class 'L' incorrectly extends base class 'G'. Property 'p1' is private in type 'L' but not in type 'G'. tests/cases/compiler/classUpdateTests.ts(69,7): error TS2415: Class 'M' incorrectly extends base class 'G'. Property 'p1' is private in type 'M' but not in type 'G'. tests/cases/compiler/classUpdateTests.ts(70,2): error TS2376: A 'super' call must be the first statement in the constructor when a class contains initialized properties or has parameter properties. -tests/cases/compiler/classUpdateTests.ts(93,3): error TS1129: Statement expected. +tests/cases/compiler/classUpdateTests.ts(93,3): error TS1128: Declaration or statement expected. tests/cases/compiler/classUpdateTests.ts(95,1): error TS1128: Declaration or statement expected. -tests/cases/compiler/classUpdateTests.ts(99,3): error TS1129: Statement expected. +tests/cases/compiler/classUpdateTests.ts(99,3): error TS1128: Declaration or statement expected. tests/cases/compiler/classUpdateTests.ts(101,1): error TS1128: Declaration or statement expected. -tests/cases/compiler/classUpdateTests.ts(105,3): error TS1129: Statement expected. +tests/cases/compiler/classUpdateTests.ts(105,3): error TS1128: Declaration or statement expected. tests/cases/compiler/classUpdateTests.ts(105,14): error TS1005: ';' expected. tests/cases/compiler/classUpdateTests.ts(107,1): error TS1128: Declaration or statement expected. -tests/cases/compiler/classUpdateTests.ts(111,3): error TS1129: Statement expected. +tests/cases/compiler/classUpdateTests.ts(111,3): error TS1128: Declaration or statement expected. tests/cases/compiler/classUpdateTests.ts(111,15): error TS1005: ';' expected. tests/cases/compiler/classUpdateTests.ts(113,1): error TS1128: Declaration or statement expected. -==== tests/cases/compiler/classUpdateTests.ts (18 errors) ==== +==== tests/cases/compiler/classUpdateTests.ts (16 errors) ==== // // test codegen for instance properties // @@ -71,11 +69,7 @@ tests/cases/compiler/classUpdateTests.ts(113,1): error TS1128: Declaration or st } class I extends Object { - ~~~~~~ -!!! error TS2311: A class may only extend another class. constructor() { super(); } // ERROR - no super call allowed - ~~~~~ -!!! error TS2335: 'super' can only be referenced in a derived class. } class J extends G { @@ -139,7 +133,7 @@ tests/cases/compiler/classUpdateTests.ts(113,1): error TS1128: Declaration or st constructor() { public p1 = 0; // ERROR ~~~~~~ -!!! error TS1129: Statement expected. +!!! error TS1128: Declaration or statement expected. } } ~ @@ -149,7 +143,7 @@ tests/cases/compiler/classUpdateTests.ts(113,1): error TS1128: Declaration or st constructor() { private p1 = 0; // ERROR ~~~~~~~ -!!! error TS1129: Statement expected. +!!! error TS1128: Declaration or statement expected. } } ~ @@ -159,7 +153,7 @@ tests/cases/compiler/classUpdateTests.ts(113,1): error TS1128: Declaration or st constructor() { public this.p1 = 0; // ERROR ~~~~~~ -!!! error TS1129: Statement expected. +!!! error TS1128: Declaration or statement expected. ~ !!! error TS1005: ';' expected. } @@ -171,7 +165,7 @@ tests/cases/compiler/classUpdateTests.ts(113,1): error TS1128: Declaration or st constructor() { private this.p1 = 0; // ERROR ~~~~~~~ -!!! error TS1129: Statement expected. +!!! error TS1128: Declaration or statement expected. ~ !!! error TS1005: ';' expected. } diff --git a/tests/baselines/reference/classUpdateTests.js b/tests/baselines/reference/classUpdateTests.js index 90149d88d9d..95db2680a1c 100644 --- a/tests/baselines/reference/classUpdateTests.js +++ b/tests/baselines/reference/classUpdateTests.js @@ -117,8 +117,7 @@ class R { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; // // test codegen for instance properties diff --git a/tests/baselines/reference/classWithBaseClassButNoConstructor.js b/tests/baselines/reference/classWithBaseClassButNoConstructor.js index f1a10b317a1..44e5d39c376 100644 --- a/tests/baselines/reference/classWithBaseClassButNoConstructor.js +++ b/tests/baselines/reference/classWithBaseClassButNoConstructor.js @@ -44,8 +44,7 @@ var d6 = new D(1); // ok var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var Base = (function () { function Base(x) { diff --git a/tests/baselines/reference/classWithConstructors.js b/tests/baselines/reference/classWithConstructors.js index 467738e0966..a36db6ee745 100644 --- a/tests/baselines/reference/classWithConstructors.js +++ b/tests/baselines/reference/classWithConstructors.js @@ -53,8 +53,7 @@ module Generics { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var NonGeneric; (function (NonGeneric) { diff --git a/tests/baselines/reference/classWithProtectedProperty.js b/tests/baselines/reference/classWithProtectedProperty.js index 7d86e1c7229..ec8a203d200 100644 --- a/tests/baselines/reference/classWithProtectedProperty.js +++ b/tests/baselines/reference/classWithProtectedProperty.js @@ -32,8 +32,7 @@ class D extends C { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var C = (function () { function C() { diff --git a/tests/baselines/reference/classWithStaticMembers.js b/tests/baselines/reference/classWithStaticMembers.js index edad6c22c70..34928c37abd 100644 --- a/tests/baselines/reference/classWithStaticMembers.js +++ b/tests/baselines/reference/classWithStaticMembers.js @@ -23,8 +23,7 @@ var r3 = r.foo; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var C = (function () { function C(a, b) { diff --git a/tests/baselines/reference/classdecl.js b/tests/baselines/reference/classdecl.js index 127e0e9f32b..2af85da5b57 100644 --- a/tests/baselines/reference/classdecl.js +++ b/tests/baselines/reference/classdecl.js @@ -97,8 +97,7 @@ class e { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var a = (function () { function a(ns) { diff --git a/tests/baselines/reference/clodulesDerivedClasses.js b/tests/baselines/reference/clodulesDerivedClasses.js index c37b9f0e96a..652b3f7bac6 100644 --- a/tests/baselines/reference/clodulesDerivedClasses.js +++ b/tests/baselines/reference/clodulesDerivedClasses.js @@ -26,8 +26,7 @@ module Path.Utils { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var Shape = (function () { function Shape() { diff --git a/tests/baselines/reference/collisionSuperAndLocalFunctionInAccessors.js b/tests/baselines/reference/collisionSuperAndLocalFunctionInAccessors.js index a58f4aa9f94..731f3d4f064 100644 --- a/tests/baselines/reference/collisionSuperAndLocalFunctionInAccessors.js +++ b/tests/baselines/reference/collisionSuperAndLocalFunctionInAccessors.js @@ -43,8 +43,7 @@ class c extends Foo { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; function _super() { } diff --git a/tests/baselines/reference/collisionSuperAndLocalFunctionInConstructor.js b/tests/baselines/reference/collisionSuperAndLocalFunctionInConstructor.js index b89a8753acd..06acaa0e02a 100644 --- a/tests/baselines/reference/collisionSuperAndLocalFunctionInConstructor.js +++ b/tests/baselines/reference/collisionSuperAndLocalFunctionInConstructor.js @@ -28,8 +28,7 @@ class c extends Foo { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; function _super() { } diff --git a/tests/baselines/reference/collisionSuperAndLocalFunctionInMethod.js b/tests/baselines/reference/collisionSuperAndLocalFunctionInMethod.js index efa9c1d9f03..6702ba8ac3d 100644 --- a/tests/baselines/reference/collisionSuperAndLocalFunctionInMethod.js +++ b/tests/baselines/reference/collisionSuperAndLocalFunctionInMethod.js @@ -32,8 +32,7 @@ class c extends Foo { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; function _super() { } diff --git a/tests/baselines/reference/collisionSuperAndLocalFunctionInProperty.js b/tests/baselines/reference/collisionSuperAndLocalFunctionInProperty.js index 228b7243d4f..8d13eed617b 100644 --- a/tests/baselines/reference/collisionSuperAndLocalFunctionInProperty.js +++ b/tests/baselines/reference/collisionSuperAndLocalFunctionInProperty.js @@ -22,8 +22,7 @@ class b extends Foo { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; function _super() { } diff --git a/tests/baselines/reference/collisionSuperAndLocalVarInAccessors.js b/tests/baselines/reference/collisionSuperAndLocalVarInAccessors.js index d2392f4df38..12685727795 100644 --- a/tests/baselines/reference/collisionSuperAndLocalVarInAccessors.js +++ b/tests/baselines/reference/collisionSuperAndLocalVarInAccessors.js @@ -36,8 +36,7 @@ class c extends Foo { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var _super = 10; // No Error var Foo = (function () { diff --git a/tests/baselines/reference/collisionSuperAndLocalVarInConstructor.js b/tests/baselines/reference/collisionSuperAndLocalVarInConstructor.js index dc3210c1f8e..6f543492898 100644 --- a/tests/baselines/reference/collisionSuperAndLocalVarInConstructor.js +++ b/tests/baselines/reference/collisionSuperAndLocalVarInConstructor.js @@ -24,8 +24,7 @@ class c extends Foo { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var _super = 10; // No Error var Foo = (function () { diff --git a/tests/baselines/reference/collisionSuperAndLocalVarInMethod.js b/tests/baselines/reference/collisionSuperAndLocalVarInMethod.js index 7a6ee0c45c5..373ee270014 100644 --- a/tests/baselines/reference/collisionSuperAndLocalVarInMethod.js +++ b/tests/baselines/reference/collisionSuperAndLocalVarInMethod.js @@ -22,8 +22,7 @@ class c extends Foo { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var _super = 10; // No Error var Foo = (function () { diff --git a/tests/baselines/reference/collisionSuperAndLocalVarInProperty.js b/tests/baselines/reference/collisionSuperAndLocalVarInProperty.js index f678c7cf6ca..7ba9b407858 100644 --- a/tests/baselines/reference/collisionSuperAndLocalVarInProperty.js +++ b/tests/baselines/reference/collisionSuperAndLocalVarInProperty.js @@ -21,8 +21,7 @@ class b extends Foo { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var _super = 10; // No Error var Foo = (function () { diff --git a/tests/baselines/reference/collisionSuperAndNameResolution.js b/tests/baselines/reference/collisionSuperAndNameResolution.js index 540a2b659d9..5cddcc01845 100644 --- a/tests/baselines/reference/collisionSuperAndNameResolution.js +++ b/tests/baselines/reference/collisionSuperAndNameResolution.js @@ -15,8 +15,7 @@ class Foo extends base { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var console; var _super = 10; // No error diff --git a/tests/baselines/reference/collisionSuperAndParameter.js b/tests/baselines/reference/collisionSuperAndParameter.js index ac8947e00d3..965887d6d1b 100644 --- a/tests/baselines/reference/collisionSuperAndParameter.js +++ b/tests/baselines/reference/collisionSuperAndParameter.js @@ -66,8 +66,7 @@ class Foo4 extends Foo { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var Foo = (function () { function Foo() { diff --git a/tests/baselines/reference/collisionSuperAndParameter1.js b/tests/baselines/reference/collisionSuperAndParameter1.js index b072667396d..f6d1f23947d 100644 --- a/tests/baselines/reference/collisionSuperAndParameter1.js +++ b/tests/baselines/reference/collisionSuperAndParameter1.js @@ -13,8 +13,7 @@ class Foo2 extends Foo { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var Foo = (function () { function Foo() { diff --git a/tests/baselines/reference/collisionSuperAndPropertyNameAsConstuctorParameter.js b/tests/baselines/reference/collisionSuperAndPropertyNameAsConstuctorParameter.js index e96ae7d8928..f54bbef28a8 100644 --- a/tests/baselines/reference/collisionSuperAndPropertyNameAsConstuctorParameter.js +++ b/tests/baselines/reference/collisionSuperAndPropertyNameAsConstuctorParameter.js @@ -34,8 +34,7 @@ class b4 extends a { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var a = (function () { function a() { diff --git a/tests/baselines/reference/collisionThisExpressionAndLocalVarWithSuperExperssion.js b/tests/baselines/reference/collisionThisExpressionAndLocalVarWithSuperExperssion.js index dbf36111dfb..eb2ddd825fb 100644 --- a/tests/baselines/reference/collisionThisExpressionAndLocalVarWithSuperExperssion.js +++ b/tests/baselines/reference/collisionThisExpressionAndLocalVarWithSuperExperssion.js @@ -22,8 +22,7 @@ class b2 extends a { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var a = (function () { function a() { diff --git a/tests/baselines/reference/commentOnAmbientModule.types b/tests/baselines/reference/commentOnAmbientModule.types index 13d35cddcea..629395a4e80 100644 --- a/tests/baselines/reference/commentOnAmbientModule.types +++ b/tests/baselines/reference/commentOnAmbientModule.types @@ -5,9 +5,9 @@ declare module E { class foobar extends D.bar { >foobar : foobar ->D.bar : any +>D.bar : D.bar >D : typeof D ->bar : D.bar +>bar : typeof D.bar foo(); >foo : () => any diff --git a/tests/baselines/reference/commentsInheritance.js b/tests/baselines/reference/commentsInheritance.js index 4fe5a30cb8b..33726436189 100644 --- a/tests/baselines/reference/commentsInheritance.js +++ b/tests/baselines/reference/commentsInheritance.js @@ -155,8 +155,7 @@ i2_i = i3_i; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var c1 = (function () { function c1() { diff --git a/tests/baselines/reference/comparisonOperatorWithIdenticalObjects.js b/tests/baselines/reference/comparisonOperatorWithIdenticalObjects.js index aebb486a1b5..d59ec764680 100644 --- a/tests/baselines/reference/comparisonOperatorWithIdenticalObjects.js +++ b/tests/baselines/reference/comparisonOperatorWithIdenticalObjects.js @@ -198,8 +198,7 @@ var r8b7 = b6 !== a6; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var A1 = (function () { function A1() { diff --git a/tests/baselines/reference/comparisonOperatorWithNoRelationshipObjectsOnCallSignature.js b/tests/baselines/reference/comparisonOperatorWithNoRelationshipObjectsOnCallSignature.js index 3d7e96be633..4bbc7675a31 100644 --- a/tests/baselines/reference/comparisonOperatorWithNoRelationshipObjectsOnCallSignature.js +++ b/tests/baselines/reference/comparisonOperatorWithNoRelationshipObjectsOnCallSignature.js @@ -172,8 +172,7 @@ var r8b7 = b7 !== a7; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var Base = (function () { function Base() { diff --git a/tests/baselines/reference/comparisonOperatorWithNoRelationshipObjectsOnConstructorSignature.js b/tests/baselines/reference/comparisonOperatorWithNoRelationshipObjectsOnConstructorSignature.js index 097246f183b..397c7e9d8e4 100644 --- a/tests/baselines/reference/comparisonOperatorWithNoRelationshipObjectsOnConstructorSignature.js +++ b/tests/baselines/reference/comparisonOperatorWithNoRelationshipObjectsOnConstructorSignature.js @@ -172,8 +172,7 @@ var r8b7 = b7 !== a7; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var Base = (function () { function Base() { diff --git a/tests/baselines/reference/comparisonOperatorWithNoRelationshipObjectsOnIndexSignature.js b/tests/baselines/reference/comparisonOperatorWithNoRelationshipObjectsOnIndexSignature.js index 6bb3cddc8a7..9f3c037538d 100644 --- a/tests/baselines/reference/comparisonOperatorWithNoRelationshipObjectsOnIndexSignature.js +++ b/tests/baselines/reference/comparisonOperatorWithNoRelationshipObjectsOnIndexSignature.js @@ -115,8 +115,7 @@ var r8b4 = b4 !== a4; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var Base = (function () { function Base() { diff --git a/tests/baselines/reference/comparisonOperatorWithNoRelationshipObjectsOnInstantiatedCallSignature.js b/tests/baselines/reference/comparisonOperatorWithNoRelationshipObjectsOnInstantiatedCallSignature.js index dee8fb5ed5a..68ebcb9d596 100644 --- a/tests/baselines/reference/comparisonOperatorWithNoRelationshipObjectsOnInstantiatedCallSignature.js +++ b/tests/baselines/reference/comparisonOperatorWithNoRelationshipObjectsOnInstantiatedCallSignature.js @@ -153,8 +153,7 @@ var r8b6 = b6 !== a6; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var Base = (function () { function Base() { diff --git a/tests/baselines/reference/comparisonOperatorWithNoRelationshipObjectsOnInstantiatedConstructorSignature.js b/tests/baselines/reference/comparisonOperatorWithNoRelationshipObjectsOnInstantiatedConstructorSignature.js index bc7db12ebf2..60177f0ea22 100644 --- a/tests/baselines/reference/comparisonOperatorWithNoRelationshipObjectsOnInstantiatedConstructorSignature.js +++ b/tests/baselines/reference/comparisonOperatorWithNoRelationshipObjectsOnInstantiatedConstructorSignature.js @@ -153,8 +153,7 @@ var r8b6 = b6 !== a6; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var Base = (function () { function Base() { diff --git a/tests/baselines/reference/comparisonOperatorWithSubtypeObjectOnCallSignature.js b/tests/baselines/reference/comparisonOperatorWithSubtypeObjectOnCallSignature.js index a35ece1b617..27d1b68c85d 100644 --- a/tests/baselines/reference/comparisonOperatorWithSubtypeObjectOnCallSignature.js +++ b/tests/baselines/reference/comparisonOperatorWithSubtypeObjectOnCallSignature.js @@ -263,8 +263,7 @@ var r8b11 = b11 !== a11; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var Base = (function () { function Base() { diff --git a/tests/baselines/reference/comparisonOperatorWithSubtypeObjectOnConstructorSignature.js b/tests/baselines/reference/comparisonOperatorWithSubtypeObjectOnConstructorSignature.js index 8ade79daa20..5a98e12b001 100644 --- a/tests/baselines/reference/comparisonOperatorWithSubtypeObjectOnConstructorSignature.js +++ b/tests/baselines/reference/comparisonOperatorWithSubtypeObjectOnConstructorSignature.js @@ -225,8 +225,7 @@ var r8b9 = b9 !== a9; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var Base = (function () { function Base() { diff --git a/tests/baselines/reference/comparisonOperatorWithSubtypeObjectOnIndexSignature.js b/tests/baselines/reference/comparisonOperatorWithSubtypeObjectOnIndexSignature.js index 080c7990c04..24069615e0a 100644 --- a/tests/baselines/reference/comparisonOperatorWithSubtypeObjectOnIndexSignature.js +++ b/tests/baselines/reference/comparisonOperatorWithSubtypeObjectOnIndexSignature.js @@ -111,8 +111,7 @@ var r8b1 = b4 !== a4; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var Base = (function () { function Base() { diff --git a/tests/baselines/reference/comparisonOperatorWithSubtypeObjectOnInstantiatedCallSignature.js b/tests/baselines/reference/comparisonOperatorWithSubtypeObjectOnInstantiatedCallSignature.js index f01b18496d5..f0dac057ca3 100644 --- a/tests/baselines/reference/comparisonOperatorWithSubtypeObjectOnInstantiatedCallSignature.js +++ b/tests/baselines/reference/comparisonOperatorWithSubtypeObjectOnInstantiatedCallSignature.js @@ -168,8 +168,7 @@ var r8b6 = b6 !== a6; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var Base = (function () { function Base() { diff --git a/tests/baselines/reference/comparisonOperatorWithSubtypeObjectOnInstantiatedConstructorSignature.js b/tests/baselines/reference/comparisonOperatorWithSubtypeObjectOnInstantiatedConstructorSignature.js index bd4525e5c7b..eaf1aca728d 100644 --- a/tests/baselines/reference/comparisonOperatorWithSubtypeObjectOnInstantiatedConstructorSignature.js +++ b/tests/baselines/reference/comparisonOperatorWithSubtypeObjectOnInstantiatedConstructorSignature.js @@ -168,8 +168,7 @@ var r8b6 = b6 !== a6; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var Base = (function () { function Base() { diff --git a/tests/baselines/reference/comparisonOperatorWithSubtypeObjectOnProperty.js b/tests/baselines/reference/comparisonOperatorWithSubtypeObjectOnProperty.js index cbd31f56b30..822d4b7520a 100644 --- a/tests/baselines/reference/comparisonOperatorWithSubtypeObjectOnProperty.js +++ b/tests/baselines/reference/comparisonOperatorWithSubtypeObjectOnProperty.js @@ -82,8 +82,7 @@ var rh4 = b2 !== a2; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var Base = (function () { function Base() { diff --git a/tests/baselines/reference/complexClassRelationships.js b/tests/baselines/reference/complexClassRelationships.js index 2d750b77f71..ca2b31a805c 100644 --- a/tests/baselines/reference/complexClassRelationships.js +++ b/tests/baselines/reference/complexClassRelationships.js @@ -51,8 +51,7 @@ class FooBase { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; // There should be no errors in this file var Derived = (function (_super) { diff --git a/tests/baselines/reference/complicatedGenericRecursiveBaseClassReference.errors.txt b/tests/baselines/reference/complicatedGenericRecursiveBaseClassReference.errors.txt index 204a7d4c21a..a70eb0e5e2c 100644 --- a/tests/baselines/reference/complicatedGenericRecursiveBaseClassReference.errors.txt +++ b/tests/baselines/reference/complicatedGenericRecursiveBaseClassReference.errors.txt @@ -1,11 +1,11 @@ -tests/cases/compiler/complicatedGenericRecursiveBaseClassReference.ts(1,7): error TS2310: Type 'S18' recursively references itself as a base type. +tests/cases/compiler/complicatedGenericRecursiveBaseClassReference.ts(1,7): error TS2506: 'S18' is referenced directly or indirectly in its own base expression. tests/cases/compiler/complicatedGenericRecursiveBaseClassReference.ts(4,2): error TS2346: Supplied parameters do not match any signature of call target. ==== tests/cases/compiler/complicatedGenericRecursiveBaseClassReference.ts (2 errors) ==== class S18 extends S18 ~~~ -!!! error TS2310: Type 'S18' recursively references itself as a base type. +!!! error TS2506: 'S18' is referenced directly or indirectly in its own base expression. { } (new S18(123)).S18 = 0; diff --git a/tests/baselines/reference/complicatedGenericRecursiveBaseClassReference.js b/tests/baselines/reference/complicatedGenericRecursiveBaseClassReference.js index 920172b206d..71c1cee164f 100644 --- a/tests/baselines/reference/complicatedGenericRecursiveBaseClassReference.js +++ b/tests/baselines/reference/complicatedGenericRecursiveBaseClassReference.js @@ -9,8 +9,7 @@ class S18 extends S18 var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var S18 = (function (_super) { __extends(S18, _super); diff --git a/tests/baselines/reference/compoundAssignmentLHSIsValue.js b/tests/baselines/reference/compoundAssignmentLHSIsValue.js index 4c5c050dc83..833c1e1ea7c 100644 --- a/tests/baselines/reference/compoundAssignmentLHSIsValue.js +++ b/tests/baselines/reference/compoundAssignmentLHSIsValue.js @@ -126,8 +126,7 @@ foo() += value; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; // expected error for all the LHS of compound assignments (arithmetic and addition) var value; diff --git a/tests/baselines/reference/computedPropertyNames24_ES5.js b/tests/baselines/reference/computedPropertyNames24_ES5.js index e433383eb5c..5a4b79cf44a 100644 --- a/tests/baselines/reference/computedPropertyNames24_ES5.js +++ b/tests/baselines/reference/computedPropertyNames24_ES5.js @@ -12,8 +12,7 @@ class C extends Base { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var Base = (function () { function Base() { diff --git a/tests/baselines/reference/computedPropertyNames25_ES5.js b/tests/baselines/reference/computedPropertyNames25_ES5.js index eca2485ab7d..832fad174d8 100644 --- a/tests/baselines/reference/computedPropertyNames25_ES5.js +++ b/tests/baselines/reference/computedPropertyNames25_ES5.js @@ -17,8 +17,7 @@ class C extends Base { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var Base = (function () { function Base() { diff --git a/tests/baselines/reference/computedPropertyNames26_ES5.js b/tests/baselines/reference/computedPropertyNames26_ES5.js index 0e3b6c126bc..09a95419480 100644 --- a/tests/baselines/reference/computedPropertyNames26_ES5.js +++ b/tests/baselines/reference/computedPropertyNames26_ES5.js @@ -14,8 +14,7 @@ class C extends Base { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var Base = (function () { function Base() { diff --git a/tests/baselines/reference/computedPropertyNames27_ES5.js b/tests/baselines/reference/computedPropertyNames27_ES5.js index 12f02fbefa9..53e2c2988c8 100644 --- a/tests/baselines/reference/computedPropertyNames27_ES5.js +++ b/tests/baselines/reference/computedPropertyNames27_ES5.js @@ -9,8 +9,7 @@ class C extends Base { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var Base = (function () { function Base() { diff --git a/tests/baselines/reference/computedPropertyNames28_ES5.js b/tests/baselines/reference/computedPropertyNames28_ES5.js index b2be5f120a5..be79f22c2da 100644 --- a/tests/baselines/reference/computedPropertyNames28_ES5.js +++ b/tests/baselines/reference/computedPropertyNames28_ES5.js @@ -14,8 +14,7 @@ class C extends Base { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var Base = (function () { function Base() { diff --git a/tests/baselines/reference/computedPropertyNames30_ES5.js b/tests/baselines/reference/computedPropertyNames30_ES5.js index 6bbca3da056..de60b5daf53 100644 --- a/tests/baselines/reference/computedPropertyNames30_ES5.js +++ b/tests/baselines/reference/computedPropertyNames30_ES5.js @@ -19,8 +19,7 @@ class C extends Base { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var Base = (function () { function Base() { diff --git a/tests/baselines/reference/computedPropertyNames31_ES5.js b/tests/baselines/reference/computedPropertyNames31_ES5.js index fb7d651364b..f8e34603305 100644 --- a/tests/baselines/reference/computedPropertyNames31_ES5.js +++ b/tests/baselines/reference/computedPropertyNames31_ES5.js @@ -19,8 +19,7 @@ class C extends Base { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var Base = (function () { function Base() { diff --git a/tests/baselines/reference/computedPropertyNames43_ES5.js b/tests/baselines/reference/computedPropertyNames43_ES5.js index e51df61a8c1..c3b7f6a71d0 100644 --- a/tests/baselines/reference/computedPropertyNames43_ES5.js +++ b/tests/baselines/reference/computedPropertyNames43_ES5.js @@ -16,8 +16,7 @@ class D extends C { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var Foo = (function () { function Foo() { diff --git a/tests/baselines/reference/computedPropertyNames44_ES5.js b/tests/baselines/reference/computedPropertyNames44_ES5.js index 5efc5a11496..1186f0caef7 100644 --- a/tests/baselines/reference/computedPropertyNames44_ES5.js +++ b/tests/baselines/reference/computedPropertyNames44_ES5.js @@ -15,8 +15,7 @@ class D extends C { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var Foo = (function () { function Foo() { diff --git a/tests/baselines/reference/computedPropertyNames45_ES5.js b/tests/baselines/reference/computedPropertyNames45_ES5.js index d7fb6f35407..ce948e58208 100644 --- a/tests/baselines/reference/computedPropertyNames45_ES5.js +++ b/tests/baselines/reference/computedPropertyNames45_ES5.js @@ -16,8 +16,7 @@ class D extends C { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var Foo = (function () { function Foo() { diff --git a/tests/baselines/reference/computedPropertyNamesContextualType6_ES5.types b/tests/baselines/reference/computedPropertyNamesContextualType6_ES5.types index 52ff0c1001d..d6c97b5db81 100644 --- a/tests/baselines/reference/computedPropertyNamesContextualType6_ES5.types +++ b/tests/baselines/reference/computedPropertyNamesContextualType6_ES5.types @@ -17,9 +17,9 @@ declare function foo(obj: I): T >T : T foo({ ->foo({ p: "", 0: () => { }, ["hi" + "bye"]: true, [0 + 1]: 0, [+"hi"]: [0]}) : string | number | boolean | number[] | (() => void) +>foo({ p: "", 0: () => { }, ["hi" + "bye"]: true, [0 + 1]: 0, [+"hi"]: [0]}) : string | number | boolean | (() => void) | number[] >foo : (obj: I) => T ->{ p: "", 0: () => { }, ["hi" + "bye"]: true, [0 + 1]: 0, [+"hi"]: [0]} : { [x: string]: string | number | boolean | number[] | (() => void); 0: () => void; p: string; } +>{ p: "", 0: () => { }, ["hi" + "bye"]: true, [0 + 1]: 0, [+"hi"]: [0]} : { [x: string]: string | number | boolean | (() => void) | number[]; 0: () => void; p: string; } p: "", >p : string diff --git a/tests/baselines/reference/computedPropertyNamesContextualType6_ES6.types b/tests/baselines/reference/computedPropertyNamesContextualType6_ES6.types index 6998c9523cc..72a1d5ba04f 100644 --- a/tests/baselines/reference/computedPropertyNamesContextualType6_ES6.types +++ b/tests/baselines/reference/computedPropertyNamesContextualType6_ES6.types @@ -17,9 +17,9 @@ declare function foo(obj: I): T >T : T foo({ ->foo({ p: "", 0: () => { }, ["hi" + "bye"]: true, [0 + 1]: 0, [+"hi"]: [0]}) : string | number | boolean | number[] | (() => void) +>foo({ p: "", 0: () => { }, ["hi" + "bye"]: true, [0 + 1]: 0, [+"hi"]: [0]}) : string | number | boolean | (() => void) | number[] >foo : (obj: I) => T ->{ p: "", 0: () => { }, ["hi" + "bye"]: true, [0 + 1]: 0, [+"hi"]: [0]} : { [x: string]: string | number | boolean | number[] | (() => void); 0: () => void; p: string; } +>{ p: "", 0: () => { }, ["hi" + "bye"]: true, [0 + 1]: 0, [+"hi"]: [0]} : { [x: string]: string | number | boolean | (() => void) | number[]; 0: () => void; p: string; } p: "", >p : string diff --git a/tests/baselines/reference/computedPropertyNamesContextualType7_ES5.types b/tests/baselines/reference/computedPropertyNamesContextualType7_ES5.types index 1845d145966..5674f6aa393 100644 --- a/tests/baselines/reference/computedPropertyNamesContextualType7_ES5.types +++ b/tests/baselines/reference/computedPropertyNamesContextualType7_ES5.types @@ -17,9 +17,9 @@ declare function foo(obj: I): T >T : T foo({ ->foo({ p: "", 0: () => { }, ["hi" + "bye"]: true, [0 + 1]: 0, [+"hi"]: [0]}) : number | number[] | (() => void) +>foo({ p: "", 0: () => { }, ["hi" + "bye"]: true, [0 + 1]: 0, [+"hi"]: [0]}) : number | (() => void) | number[] >foo : (obj: I) => T ->{ p: "", 0: () => { }, ["hi" + "bye"]: true, [0 + 1]: 0, [+"hi"]: [0]} : { [x: number]: number | number[] | (() => void); 0: () => void; p: string; } +>{ p: "", 0: () => { }, ["hi" + "bye"]: true, [0 + 1]: 0, [+"hi"]: [0]} : { [x: number]: number | (() => void) | number[]; 0: () => void; p: string; } p: "", >p : string diff --git a/tests/baselines/reference/computedPropertyNamesContextualType7_ES6.types b/tests/baselines/reference/computedPropertyNamesContextualType7_ES6.types index 54d2afe4f61..93558c075e7 100644 --- a/tests/baselines/reference/computedPropertyNamesContextualType7_ES6.types +++ b/tests/baselines/reference/computedPropertyNamesContextualType7_ES6.types @@ -17,9 +17,9 @@ declare function foo(obj: I): T >T : T foo({ ->foo({ p: "", 0: () => { }, ["hi" + "bye"]: true, [0 + 1]: 0, [+"hi"]: [0]}) : number | number[] | (() => void) +>foo({ p: "", 0: () => { }, ["hi" + "bye"]: true, [0 + 1]: 0, [+"hi"]: [0]}) : number | (() => void) | number[] >foo : (obj: I) => T ->{ p: "", 0: () => { }, ["hi" + "bye"]: true, [0 + 1]: 0, [+"hi"]: [0]} : { [x: number]: number | number[] | (() => void); 0: () => void; p: string; } +>{ p: "", 0: () => { }, ["hi" + "bye"]: true, [0 + 1]: 0, [+"hi"]: [0]} : { [x: number]: number | (() => void) | number[]; 0: () => void; p: string; } p: "", >p : string diff --git a/tests/baselines/reference/conditionalOperatorWithIdenticalBCT.js b/tests/baselines/reference/conditionalOperatorWithIdenticalBCT.js index 18c09a500a6..a493a5cfab0 100644 --- a/tests/baselines/reference/conditionalOperatorWithIdenticalBCT.js +++ b/tests/baselines/reference/conditionalOperatorWithIdenticalBCT.js @@ -51,8 +51,7 @@ var result11: any = true ? 1 : 'string'; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; //Cond ? Expr1 : Expr2, Expr1 and Expr2 have identical best common type var X = (function () { diff --git a/tests/baselines/reference/conditionalOperatorWithoutIdenticalBCT.js b/tests/baselines/reference/conditionalOperatorWithoutIdenticalBCT.js index 62b887d7e60..3d75eb0507a 100644 --- a/tests/baselines/reference/conditionalOperatorWithoutIdenticalBCT.js +++ b/tests/baselines/reference/conditionalOperatorWithoutIdenticalBCT.js @@ -27,8 +27,7 @@ var result61: (t: X) => number| string = true ? (m) => m.propertyX1 : (n) => n.p var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; //Cond ? Expr1 : Expr2, Expr1 and Expr2 have no identical best common type var X = (function () { diff --git a/tests/baselines/reference/constantOverloadFunction.js b/tests/baselines/reference/constantOverloadFunction.js index aa89c619e7e..45c0fe9ff0a 100644 --- a/tests/baselines/reference/constantOverloadFunction.js +++ b/tests/baselines/reference/constantOverloadFunction.js @@ -17,8 +17,7 @@ function foo(tagName: any): Base { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var Base = (function () { function Base() { diff --git a/tests/baselines/reference/constantOverloadFunctionNoSubtypeError.js b/tests/baselines/reference/constantOverloadFunctionNoSubtypeError.js index 529f888bfc9..946f8196372 100644 --- a/tests/baselines/reference/constantOverloadFunctionNoSubtypeError.js +++ b/tests/baselines/reference/constantOverloadFunctionNoSubtypeError.js @@ -18,8 +18,7 @@ function foo(tagName: any): Base { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var Base = (function () { function Base() { diff --git a/tests/baselines/reference/constraintCheckInGenericBaseTypeReference.js b/tests/baselines/reference/constraintCheckInGenericBaseTypeReference.js index 22b77ba6816..9cf9d71f7a2 100644 --- a/tests/baselines/reference/constraintCheckInGenericBaseTypeReference.js +++ b/tests/baselines/reference/constraintCheckInGenericBaseTypeReference.js @@ -23,8 +23,7 @@ class Container { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; // No errors var Constraint = (function () { diff --git a/tests/baselines/reference/constraintCheckInGenericBaseTypeReference.types b/tests/baselines/reference/constraintCheckInGenericBaseTypeReference.types index 1d94a5e464c..6fd80b779c5 100644 --- a/tests/baselines/reference/constraintCheckInGenericBaseTypeReference.types +++ b/tests/baselines/reference/constraintCheckInGenericBaseTypeReference.types @@ -16,7 +16,7 @@ class GenericBase { } class Derived extends GenericBase { >Derived : Derived ->GenericBase : GenericBase +>GenericBase : GenericBase >TypeArg : TypeArg } diff --git a/tests/baselines/reference/constraints0.errors.txt b/tests/baselines/reference/constraints0.errors.txt index 217a7408fbd..39cc7654e01 100644 --- a/tests/baselines/reference/constraints0.errors.txt +++ b/tests/baselines/reference/constraints0.errors.txt @@ -1,4 +1,4 @@ -tests/cases/compiler/constraints0.ts(14,9): error TS2344: Type 'B' does not satisfy the constraint 'A'. +tests/cases/compiler/constraints0.ts(14,11): error TS2344: Type 'B' does not satisfy the constraint 'A'. Property 'a' is missing in type 'B'. @@ -17,7 +17,7 @@ tests/cases/compiler/constraints0.ts(14,9): error TS2344: Type 'B' does not sati var v1: C; // should work var v2: C; // should not work - ~~~~ + ~ !!! error TS2344: Type 'B' does not satisfy the constraint 'A'. !!! error TS2344: Property 'a' is missing in type 'B'. diff --git a/tests/baselines/reference/constructSignatureAssignabilityInInheritance2.js b/tests/baselines/reference/constructSignatureAssignabilityInInheritance2.js index c1c10ead1e3..38b7b7fc194 100644 --- a/tests/baselines/reference/constructSignatureAssignabilityInInheritance2.js +++ b/tests/baselines/reference/constructSignatureAssignabilityInInheritance2.js @@ -74,8 +74,7 @@ interface I extends A { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var Base = (function () { function Base() { diff --git a/tests/baselines/reference/constructSignatureAssignabilityInInheritance3.js b/tests/baselines/reference/constructSignatureAssignabilityInInheritance3.js index 12907c6d032..7d07c1a1712 100644 --- a/tests/baselines/reference/constructSignatureAssignabilityInInheritance3.js +++ b/tests/baselines/reference/constructSignatureAssignabilityInInheritance3.js @@ -117,8 +117,7 @@ module Errors { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var Errors; (function (Errors) { diff --git a/tests/baselines/reference/constructSignatureAssignabilityInInheritance4.js b/tests/baselines/reference/constructSignatureAssignabilityInInheritance4.js index ef03802a17e..ba341eec61f 100644 --- a/tests/baselines/reference/constructSignatureAssignabilityInInheritance4.js +++ b/tests/baselines/reference/constructSignatureAssignabilityInInheritance4.js @@ -64,8 +64,7 @@ interface I extends A { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var Base = (function () { function Base() { diff --git a/tests/baselines/reference/constructSignatureAssignabilityInInheritance5.js b/tests/baselines/reference/constructSignatureAssignabilityInInheritance5.js index 9964a3464a1..304b5cafd66 100644 --- a/tests/baselines/reference/constructSignatureAssignabilityInInheritance5.js +++ b/tests/baselines/reference/constructSignatureAssignabilityInInheritance5.js @@ -54,8 +54,7 @@ interface I extends B { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var Base = (function () { function Base() { diff --git a/tests/baselines/reference/constructSignatureAssignabilityInInheritance6.js b/tests/baselines/reference/constructSignatureAssignabilityInInheritance6.js index 4cf9b7d71f5..99c885f9716 100644 --- a/tests/baselines/reference/constructSignatureAssignabilityInInheritance6.js +++ b/tests/baselines/reference/constructSignatureAssignabilityInInheritance6.js @@ -57,8 +57,7 @@ interface I9 extends A { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var Base = (function () { function Base() { diff --git a/tests/baselines/reference/constructorArgs.js b/tests/baselines/reference/constructorArgs.js index 93a47178d52..6fc3511b70e 100644 --- a/tests/baselines/reference/constructorArgs.js +++ b/tests/baselines/reference/constructorArgs.js @@ -19,8 +19,7 @@ class Sub extends Super { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var Super = (function () { function Super(value) { diff --git a/tests/baselines/reference/constructorFunctionTypeIsAssignableToBaseType.js b/tests/baselines/reference/constructorFunctionTypeIsAssignableToBaseType.js index 9c92f31ce97..305b3e54ead 100644 --- a/tests/baselines/reference/constructorFunctionTypeIsAssignableToBaseType.js +++ b/tests/baselines/reference/constructorFunctionTypeIsAssignableToBaseType.js @@ -23,8 +23,7 @@ class Derived2 extends Base { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var Base = (function () { function Base() { diff --git a/tests/baselines/reference/constructorFunctionTypeIsAssignableToBaseType2.js b/tests/baselines/reference/constructorFunctionTypeIsAssignableToBaseType2.js index 61cf399f613..b2bf377f0cc 100644 --- a/tests/baselines/reference/constructorFunctionTypeIsAssignableToBaseType2.js +++ b/tests/baselines/reference/constructorFunctionTypeIsAssignableToBaseType2.js @@ -37,8 +37,7 @@ class Derived2 extends Base { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var Base = (function () { function Base(x) { diff --git a/tests/baselines/reference/constructorHasPrototypeProperty.js b/tests/baselines/reference/constructorHasPrototypeProperty.js index 47020120f9f..a1bdee8e7d4 100644 --- a/tests/baselines/reference/constructorHasPrototypeProperty.js +++ b/tests/baselines/reference/constructorHasPrototypeProperty.js @@ -35,8 +35,7 @@ module Generic { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var NonGeneric; (function (NonGeneric) { diff --git a/tests/baselines/reference/constructorOverloads2.js b/tests/baselines/reference/constructorOverloads2.js index 16da3f0fa0a..d95477d84f6 100644 --- a/tests/baselines/reference/constructorOverloads2.js +++ b/tests/baselines/reference/constructorOverloads2.js @@ -29,8 +29,7 @@ f1.bar1(); var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var FooBase = (function () { function FooBase(x) { diff --git a/tests/baselines/reference/constructorOverloads3.js b/tests/baselines/reference/constructorOverloads3.js index f4299466aa1..c7e4e411319 100644 --- a/tests/baselines/reference/constructorOverloads3.js +++ b/tests/baselines/reference/constructorOverloads3.js @@ -26,8 +26,7 @@ f1.bar1(); var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var Foo = (function (_super) { __extends(Foo, _super); diff --git a/tests/baselines/reference/constructorWithIncompleteTypeAnnotation.errors.txt b/tests/baselines/reference/constructorWithIncompleteTypeAnnotation.errors.txt index 2818793948f..12f397ff06c 100644 --- a/tests/baselines/reference/constructorWithIncompleteTypeAnnotation.errors.txt +++ b/tests/baselines/reference/constructorWithIncompleteTypeAnnotation.errors.txt @@ -5,7 +5,7 @@ tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(22,35): error TS tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(22,39): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(24,28): error TS1005: ':' expected. tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(24,29): error TS1005: ',' expected. -tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(27,18): error TS1129: Statement expected. +tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(27,18): error TS1128: Declaration or statement expected. tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(27,26): error TS2304: Cannot find name 'bfs'. tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(28,30): error TS1005: '=' expected. tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(31,18): error TS1109: Expression expected. @@ -129,7 +129,7 @@ tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(261,1): error TS case = bfs.STATEMENTS(4); ~~~~ -!!! error TS1129: Statement expected. +!!! error TS1128: Declaration or statement expected. ~~~ !!! error TS2304: Cannot find name 'bfs'. if (retValue != 0) { diff --git a/tests/baselines/reference/constructorWithIncompleteTypeAnnotation.js b/tests/baselines/reference/constructorWithIncompleteTypeAnnotation.js index 01a1880ffd5..5a61d4d5d7e 100644 --- a/tests/baselines/reference/constructorWithIncompleteTypeAnnotation.js +++ b/tests/baselines/reference/constructorWithIncompleteTypeAnnotation.js @@ -283,8 +283,7 @@ TypeScriptAllInOne.Program.Main(); var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var fs = module; ("fs"); diff --git a/tests/baselines/reference/contextualSignatureInstantiation.types b/tests/baselines/reference/contextualSignatureInstantiation.types index e7be6da51c5..49d6871804c 100644 --- a/tests/baselines/reference/contextualSignatureInstantiation.types +++ b/tests/baselines/reference/contextualSignatureInstantiation.types @@ -120,35 +120,35 @@ var b = baz(b, b, g); // Should be number | string >g : (x: T, y: T) => T var d: number[] | string[]; ->d : string[] | number[] +>d : number[] | string[] var d = foo(h); // Should be number[] | string[] ->d : string[] | number[] ->foo(h) : string[] | number[] +>d : number[] | string[] +>foo(h) : number[] | string[] >foo : (cb: (x: number, y: string) => T) => T >h : (x: T, y: U) => T[] | U[] var d = bar(1, "one", h); // Should be number[] | string[] ->d : string[] | number[] ->bar(1, "one", h) : string[] | number[] +>d : number[] | string[] +>bar(1, "one", h) : number[] | string[] >bar : (x: T, y: U, cb: (x: T, y: U) => V) => V >1 : number >"one" : string >h : (x: T, y: U) => T[] | U[] var d = bar("one", 1, h); // Should be number[] | string[] ->d : string[] | number[] ->bar("one", 1, h) : string[] | number[] +>d : number[] | string[] +>bar("one", 1, h) : number[] | string[] >bar : (x: T, y: U, cb: (x: T, y: U) => V) => V >"one" : string >1 : number >h : (x: T, y: U) => T[] | U[] var d = baz(d, d, g); // Should be number[] | string[] ->d : string[] | number[] ->baz(d, d, g) : string[] | number[] +>d : number[] | string[] +>baz(d, d, g) : number[] | string[] >baz : (x: T, y: T, cb: (x: T, y: T) => U) => U ->d : string[] | number[] ->d : string[] | number[] +>d : number[] | string[] +>d : number[] | string[] >g : (x: T, y: T) => T diff --git a/tests/baselines/reference/contextualTyping.errors.txt b/tests/baselines/reference/contextualTyping.errors.txt index f6941b7b92d..2e050777bfd 100644 --- a/tests/baselines/reference/contextualTyping.errors.txt +++ b/tests/baselines/reference/contextualTyping.errors.txt @@ -1,5 +1,11 @@ -tests/cases/compiler/contextualTyping.ts(189,18): error TS2384: Overload signatures must all be ambient or non-ambient.\ntests/cases/compiler/contextualTyping.ts(197,15): error TS2300: Duplicate identifier 'Point'.\ntests/cases/compiler/contextualTyping.ts(207,10): error TS2300: Duplicate identifier 'Point'.\ntests/cases/compiler/contextualTyping.ts(230,5): error TS2322: Type '{}' is not assignable to type 'B'. - Property 'x' is missing in type '{}'.\n\n\n==== tests/cases/compiler/contextualTyping.ts (4 errors) ==== +tests/cases/compiler/contextualTyping.ts(189,18): error TS2384: Overload signatures must all be ambient or non-ambient. +tests/cases/compiler/contextualTyping.ts(197,15): error TS2300: Duplicate identifier 'Point'. +tests/cases/compiler/contextualTyping.ts(207,10): error TS2300: Duplicate identifier 'Point'. +tests/cases/compiler/contextualTyping.ts(230,5): error TS2322: Type '{}' is not assignable to type 'B'. + Property 'x' is missing in type '{}'. + + +==== tests/cases/compiler/contextualTyping.ts (4 errors) ==== // DEFAULT INTERFACES interface IFoo { n: number; diff --git a/tests/baselines/reference/contextualTypingArrayOfLambdas.js b/tests/baselines/reference/contextualTypingArrayOfLambdas.js index e24ae90176c..59da607079b 100644 --- a/tests/baselines/reference/contextualTypingArrayOfLambdas.js +++ b/tests/baselines/reference/contextualTypingArrayOfLambdas.js @@ -18,8 +18,7 @@ var xs = [(x: A) => { }, (x: B) => { }, (x: C) => { }]; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var A = (function () { function A() { diff --git a/tests/baselines/reference/contextualTypingOfConditionalExpression.js b/tests/baselines/reference/contextualTypingOfConditionalExpression.js index 72c15455e8e..a0f8ea0a4cf 100644 --- a/tests/baselines/reference/contextualTypingOfConditionalExpression.js +++ b/tests/baselines/reference/contextualTypingOfConditionalExpression.js @@ -18,8 +18,7 @@ var x2: (a: A) => void = true ? (a) => a.foo : (b) => b.foo; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var x = true ? function (a) { return a.toExponential(); } : function (b) { return b.toFixed(); }; var A = (function () { diff --git a/tests/baselines/reference/contextualTypingOfConditionalExpression2.js b/tests/baselines/reference/contextualTypingOfConditionalExpression2.js index 4e6b95a6857..2833ed37d4b 100644 --- a/tests/baselines/reference/contextualTypingOfConditionalExpression2.js +++ b/tests/baselines/reference/contextualTypingOfConditionalExpression2.js @@ -16,8 +16,7 @@ var x2: (a: A) => void = true ? (a: C) => a.foo : (b: number) => { }; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var A = (function () { function A() { diff --git a/tests/baselines/reference/crashInsourcePropertyIsRelatableToTargetProperty.js b/tests/baselines/reference/crashInsourcePropertyIsRelatableToTargetProperty.js index 17c9ac649d8..332f4897fc7 100644 --- a/tests/baselines/reference/crashInsourcePropertyIsRelatableToTargetProperty.js +++ b/tests/baselines/reference/crashInsourcePropertyIsRelatableToTargetProperty.js @@ -14,8 +14,7 @@ var a: D = foo("hi", []); var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var C = (function () { function C() { diff --git a/tests/baselines/reference/cyclicGenericTypeInstantiation.js b/tests/baselines/reference/cyclicGenericTypeInstantiation.js new file mode 100644 index 00000000000..10f52e10d89 --- /dev/null +++ b/tests/baselines/reference/cyclicGenericTypeInstantiation.js @@ -0,0 +1,37 @@ +//// [cyclicGenericTypeInstantiation.ts] +function foo() { + var z = foo(); + var y: { + y2: typeof z + }; + return y; +} + + +function bar() { + var z = bar(); + var y: { + y2: typeof z; + } + return y; +} + +var a = foo(); +var b = bar(); +a = b; + + +//// [cyclicGenericTypeInstantiation.js] +function foo() { + var z = foo(); + var y; + return y; +} +function bar() { + var z = bar(); + var y; + return y; +} +var a = foo(); +var b = bar(); +a = b; diff --git a/tests/baselines/reference/cyclicGenericTypeInstantiation.symbols b/tests/baselines/reference/cyclicGenericTypeInstantiation.symbols new file mode 100644 index 00000000000..a6566b86839 --- /dev/null +++ b/tests/baselines/reference/cyclicGenericTypeInstantiation.symbols @@ -0,0 +1,55 @@ +=== tests/cases/compiler/cyclicGenericTypeInstantiation.ts === +function foo() { +>foo : Symbol(foo, Decl(cyclicGenericTypeInstantiation.ts, 0, 0)) +>T : Symbol(T, Decl(cyclicGenericTypeInstantiation.ts, 0, 13)) + + var z = foo(); +>z : Symbol(z, Decl(cyclicGenericTypeInstantiation.ts, 1, 7)) +>foo : Symbol(foo, Decl(cyclicGenericTypeInstantiation.ts, 0, 0)) +>y : Symbol(y, Decl(cyclicGenericTypeInstantiation.ts, 2, 7)) + + var y: { +>y : Symbol(y, Decl(cyclicGenericTypeInstantiation.ts, 2, 7)) + + y2: typeof z +>y2 : Symbol(y2, Decl(cyclicGenericTypeInstantiation.ts, 2, 12)) +>z : Symbol(z, Decl(cyclicGenericTypeInstantiation.ts, 1, 7)) + + }; + return y; +>y : Symbol(y, Decl(cyclicGenericTypeInstantiation.ts, 2, 7)) +} + + +function bar() { +>bar : Symbol(bar, Decl(cyclicGenericTypeInstantiation.ts, 6, 1)) +>T : Symbol(T, Decl(cyclicGenericTypeInstantiation.ts, 9, 13)) + + var z = bar(); +>z : Symbol(z, Decl(cyclicGenericTypeInstantiation.ts, 10, 7)) +>bar : Symbol(bar, Decl(cyclicGenericTypeInstantiation.ts, 6, 1)) +>y : Symbol(y, Decl(cyclicGenericTypeInstantiation.ts, 11, 7)) + + var y: { +>y : Symbol(y, Decl(cyclicGenericTypeInstantiation.ts, 11, 7)) + + y2: typeof z; +>y2 : Symbol(y2, Decl(cyclicGenericTypeInstantiation.ts, 11, 12)) +>z : Symbol(z, Decl(cyclicGenericTypeInstantiation.ts, 10, 7)) + } + return y; +>y : Symbol(y, Decl(cyclicGenericTypeInstantiation.ts, 11, 7)) +} + +var a = foo(); +>a : Symbol(a, Decl(cyclicGenericTypeInstantiation.ts, 17, 3)) +>foo : Symbol(foo, Decl(cyclicGenericTypeInstantiation.ts, 0, 0)) + +var b = bar(); +>b : Symbol(b, Decl(cyclicGenericTypeInstantiation.ts, 18, 3)) +>bar : Symbol(bar, Decl(cyclicGenericTypeInstantiation.ts, 6, 1)) + +a = b; +>a : Symbol(a, Decl(cyclicGenericTypeInstantiation.ts, 17, 3)) +>b : Symbol(b, Decl(cyclicGenericTypeInstantiation.ts, 18, 3)) + diff --git a/tests/baselines/reference/cyclicGenericTypeInstantiation.types b/tests/baselines/reference/cyclicGenericTypeInstantiation.types new file mode 100644 index 00000000000..69b0955b22f --- /dev/null +++ b/tests/baselines/reference/cyclicGenericTypeInstantiation.types @@ -0,0 +1,60 @@ +=== tests/cases/compiler/cyclicGenericTypeInstantiation.ts === +function foo() { +>foo : () => { y2: any; } +>T : T + + var z = foo(); +>z : { y2: any; } +>foo() : { y2: any; } +>foo : () => { y2: any; } +>y : { y2: any; } + + var y: { +>y : { y2: any; } + + y2: typeof z +>y2 : { y2: any; } +>z : { y2: any; } + + }; + return y; +>y : { y2: any; } +} + + +function bar() { +>bar : () => { y2: any; } +>T : T + + var z = bar(); +>z : { y2: any; } +>bar() : { y2: any; } +>bar : () => { y2: any; } +>y : { y2: any; } + + var y: { +>y : { y2: any; } + + y2: typeof z; +>y2 : { y2: any; } +>z : { y2: any; } + } + return y; +>y : { y2: any; } +} + +var a = foo(); +>a : { y2: any; } +>foo() : { y2: any; } +>foo : () => { y2: any; } + +var b = bar(); +>b : { y2: any; } +>bar() : { y2: any; } +>bar : () => { y2: any; } + +a = b; +>a = b : { y2: any; } +>a : { y2: any; } +>b : { y2: any; } + diff --git a/tests/baselines/reference/cyclicGenericTypeInstantiationInference.js b/tests/baselines/reference/cyclicGenericTypeInstantiationInference.js new file mode 100644 index 00000000000..4e093fecf79 --- /dev/null +++ b/tests/baselines/reference/cyclicGenericTypeInstantiationInference.js @@ -0,0 +1,39 @@ +//// [cyclicGenericTypeInstantiationInference.ts] +function foo() { + var z = foo(); + var y: { + y2: typeof z + }; + return y; +} + + +function bar() { + var z = bar(); + var y: { + y2: typeof z; + } + return y; +} + +var a = foo(); +var b = bar(); + +function test(x: typeof a): void { } +test(b); + +//// [cyclicGenericTypeInstantiationInference.js] +function foo() { + var z = foo(); + var y; + return y; +} +function bar() { + var z = bar(); + var y; + return y; +} +var a = foo(); +var b = bar(); +function test(x) { } +test(b); diff --git a/tests/baselines/reference/cyclicGenericTypeInstantiationInference.symbols b/tests/baselines/reference/cyclicGenericTypeInstantiationInference.symbols new file mode 100644 index 00000000000..962a1e12cc5 --- /dev/null +++ b/tests/baselines/reference/cyclicGenericTypeInstantiationInference.symbols @@ -0,0 +1,61 @@ +=== tests/cases/compiler/cyclicGenericTypeInstantiationInference.ts === +function foo() { +>foo : Symbol(foo, Decl(cyclicGenericTypeInstantiationInference.ts, 0, 0)) +>T : Symbol(T, Decl(cyclicGenericTypeInstantiationInference.ts, 0, 13)) + + var z = foo(); +>z : Symbol(z, Decl(cyclicGenericTypeInstantiationInference.ts, 1, 7)) +>foo : Symbol(foo, Decl(cyclicGenericTypeInstantiationInference.ts, 0, 0)) +>y : Symbol(y, Decl(cyclicGenericTypeInstantiationInference.ts, 2, 7)) + + var y: { +>y : Symbol(y, Decl(cyclicGenericTypeInstantiationInference.ts, 2, 7)) + + y2: typeof z +>y2 : Symbol(y2, Decl(cyclicGenericTypeInstantiationInference.ts, 2, 12)) +>z : Symbol(z, Decl(cyclicGenericTypeInstantiationInference.ts, 1, 7)) + + }; + return y; +>y : Symbol(y, Decl(cyclicGenericTypeInstantiationInference.ts, 2, 7)) +} + + +function bar() { +>bar : Symbol(bar, Decl(cyclicGenericTypeInstantiationInference.ts, 6, 1)) +>T : Symbol(T, Decl(cyclicGenericTypeInstantiationInference.ts, 9, 13)) + + var z = bar(); +>z : Symbol(z, Decl(cyclicGenericTypeInstantiationInference.ts, 10, 7)) +>bar : Symbol(bar, Decl(cyclicGenericTypeInstantiationInference.ts, 6, 1)) +>y : Symbol(y, Decl(cyclicGenericTypeInstantiationInference.ts, 11, 7)) + + var y: { +>y : Symbol(y, Decl(cyclicGenericTypeInstantiationInference.ts, 11, 7)) + + y2: typeof z; +>y2 : Symbol(y2, Decl(cyclicGenericTypeInstantiationInference.ts, 11, 12)) +>z : Symbol(z, Decl(cyclicGenericTypeInstantiationInference.ts, 10, 7)) + } + return y; +>y : Symbol(y, Decl(cyclicGenericTypeInstantiationInference.ts, 11, 7)) +} + +var a = foo(); +>a : Symbol(a, Decl(cyclicGenericTypeInstantiationInference.ts, 17, 3)) +>foo : Symbol(foo, Decl(cyclicGenericTypeInstantiationInference.ts, 0, 0)) + +var b = bar(); +>b : Symbol(b, Decl(cyclicGenericTypeInstantiationInference.ts, 18, 3)) +>bar : Symbol(bar, Decl(cyclicGenericTypeInstantiationInference.ts, 6, 1)) + +function test(x: typeof a): void { } +>test : Symbol(test, Decl(cyclicGenericTypeInstantiationInference.ts, 18, 22)) +>T : Symbol(T, Decl(cyclicGenericTypeInstantiationInference.ts, 20, 14)) +>x : Symbol(x, Decl(cyclicGenericTypeInstantiationInference.ts, 20, 17)) +>a : Symbol(a, Decl(cyclicGenericTypeInstantiationInference.ts, 17, 3)) + +test(b); +>test : Symbol(test, Decl(cyclicGenericTypeInstantiationInference.ts, 18, 22)) +>b : Symbol(b, Decl(cyclicGenericTypeInstantiationInference.ts, 18, 3)) + diff --git a/tests/baselines/reference/cyclicGenericTypeInstantiationInference.types b/tests/baselines/reference/cyclicGenericTypeInstantiationInference.types new file mode 100644 index 00000000000..765e8349716 --- /dev/null +++ b/tests/baselines/reference/cyclicGenericTypeInstantiationInference.types @@ -0,0 +1,66 @@ +=== tests/cases/compiler/cyclicGenericTypeInstantiationInference.ts === +function foo() { +>foo : () => { y2: any; } +>T : T + + var z = foo(); +>z : { y2: any; } +>foo() : { y2: any; } +>foo : () => { y2: any; } +>y : { y2: any; } + + var y: { +>y : { y2: any; } + + y2: typeof z +>y2 : { y2: any; } +>z : { y2: any; } + + }; + return y; +>y : { y2: any; } +} + + +function bar() { +>bar : () => { y2: any; } +>T : T + + var z = bar(); +>z : { y2: any; } +>bar() : { y2: any; } +>bar : () => { y2: any; } +>y : { y2: any; } + + var y: { +>y : { y2: any; } + + y2: typeof z; +>y2 : { y2: any; } +>z : { y2: any; } + } + return y; +>y : { y2: any; } +} + +var a = foo(); +>a : { y2: any; } +>foo() : { y2: any; } +>foo : () => { y2: any; } + +var b = bar(); +>b : { y2: any; } +>bar() : { y2: any; } +>bar : () => { y2: any; } + +function test(x: typeof a): void { } +>test : (x: { y2: any; }) => void +>T : T +>x : { y2: any; } +>a : { y2: any; } + +test(b); +>test(b) : void +>test : (x: { y2: any; }) => void +>b : { y2: any; } + diff --git a/tests/baselines/reference/declFileForFunctionTypeAsTypeParameter.js b/tests/baselines/reference/declFileForFunctionTypeAsTypeParameter.js index 134bacd6053..0f13824fc45 100644 --- a/tests/baselines/reference/declFileForFunctionTypeAsTypeParameter.js +++ b/tests/baselines/reference/declFileForFunctionTypeAsTypeParameter.js @@ -13,8 +13,7 @@ interface I extends X<() => number> { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var X = (function () { function X() { diff --git a/tests/baselines/reference/declFileForFunctionTypeAsTypeParameter.types b/tests/baselines/reference/declFileForFunctionTypeAsTypeParameter.types index 5f759fb423f..ba203e39aab 100644 --- a/tests/baselines/reference/declFileForFunctionTypeAsTypeParameter.types +++ b/tests/baselines/reference/declFileForFunctionTypeAsTypeParameter.types @@ -6,7 +6,7 @@ class X { } class C extends X<() => number> { >C : C ->X : X +>X : X<() => number> } interface I extends X<() => number> { >I : I diff --git a/tests/baselines/reference/declFileGenericClassWithGenericExtendedClass.js b/tests/baselines/reference/declFileGenericClassWithGenericExtendedClass.js index 23630ba5218..caaba28859a 100644 --- a/tests/baselines/reference/declFileGenericClassWithGenericExtendedClass.js +++ b/tests/baselines/reference/declFileGenericClassWithGenericExtendedClass.js @@ -16,8 +16,7 @@ class Baz implements IBar { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var Base = (function () { function Base() { diff --git a/tests/baselines/reference/declFileGenericType.js b/tests/baselines/reference/declFileGenericType.js index dfbe147a78d..b67bacebb1a 100644 --- a/tests/baselines/reference/declFileGenericType.js +++ b/tests/baselines/reference/declFileGenericType.js @@ -43,8 +43,7 @@ export var j = C.F6; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var C; (function (C) { diff --git a/tests/baselines/reference/declFileGenericType.types b/tests/baselines/reference/declFileGenericType.types index 7aa20187890..310f812a7bb 100644 --- a/tests/baselines/reference/declFileGenericType.types +++ b/tests/baselines/reference/declFileGenericType.types @@ -153,9 +153,9 @@ export var g = C.F5>(); export class h extends C.A{ } >h : h ->C.A : any +>C.A : C.A >C : typeof C ->A : C.A +>A : typeof C.A >C : any >B : C.B diff --git a/tests/baselines/reference/declFileGenericType2.js b/tests/baselines/reference/declFileGenericType2.js index 03649af4ba6..416e0f6737c 100644 --- a/tests/baselines/reference/declFileGenericType2.js +++ b/tests/baselines/reference/declFileGenericType2.js @@ -46,8 +46,7 @@ module templa.dom.mvc.composite { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; // Module var templa; diff --git a/tests/baselines/reference/declFileGenericType2.types b/tests/baselines/reference/declFileGenericType2.types index e1e1aa0bbfb..07bcba3e85a 100644 --- a/tests/baselines/reference/declFileGenericType2.types +++ b/tests/baselines/reference/declFileGenericType2.types @@ -86,11 +86,11 @@ module templa.dom.mvc { >templa : any >mvc : any >IModel : templa.mvc.IModel ->templa.mvc.AbstractController : any +>templa.mvc.AbstractController : templa.mvc.AbstractController >templa.mvc : typeof templa.mvc >templa : typeof templa >mvc : typeof templa.mvc ->AbstractController : templa.mvc.AbstractController +>AbstractController : typeof templa.mvc.AbstractController >ModelType : ModelType >IElementController : IElementController >ModelType : ModelType @@ -116,13 +116,13 @@ module templa.dom.mvc.composite { >mvc : any >composite : any >ICompositeControllerModel : templa.mvc.composite.ICompositeControllerModel ->templa.dom.mvc.AbstractElementController : any +>templa.dom.mvc.AbstractElementController : AbstractElementController >templa.dom.mvc : typeof mvc >templa.dom : typeof dom >templa : typeof templa >dom : typeof dom >mvc : typeof mvc ->AbstractElementController : AbstractElementController +>AbstractElementController : typeof AbstractElementController >ModelType : ModelType public _controllers: templa.mvc.IController[]; diff --git a/tests/baselines/reference/declFileWithClassNameConflictingWithClassReferredByExtendsClause.js b/tests/baselines/reference/declFileWithClassNameConflictingWithClassReferredByExtendsClause.js index 8881122839e..e21c28138a2 100644 --- a/tests/baselines/reference/declFileWithClassNameConflictingWithClassReferredByExtendsClause.js +++ b/tests/baselines/reference/declFileWithClassNameConflictingWithClassReferredByExtendsClause.js @@ -24,8 +24,7 @@ module X.Y.base.Z { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var X; (function (X) { diff --git a/tests/baselines/reference/declFileWithClassNameConflictingWithClassReferredByExtendsClause.types b/tests/baselines/reference/declFileWithClassNameConflictingWithClassReferredByExtendsClause.types index 56e1d07d0ec..f032ad29b11 100644 --- a/tests/baselines/reference/declFileWithClassNameConflictingWithClassReferredByExtendsClause.types +++ b/tests/baselines/reference/declFileWithClassNameConflictingWithClassReferredByExtendsClause.types @@ -19,13 +19,13 @@ module X.Y.base { export class W extends A.B.Base.W { >W : W ->A.B.Base.W : any +>A.B.Base.W : A.B.Base.W >A.B.Base : typeof A.B.Base >A.B : typeof A.B >A : typeof A >B : typeof A.B >Base : typeof A.B.Base ->W : A.B.Base.W +>W : typeof A.B.Base.W name: string; >name : string @@ -41,13 +41,13 @@ module X.Y.base.Z { export class W extends X.Y.base.W { >W : W >TValue : TValue ->X.Y.base.W : any +>X.Y.base.W : base.W >X.Y.base : typeof base >X.Y : typeof Y >X : typeof X >Y : typeof Y >base : typeof base ->W : base.W +>W : typeof base.W value: boolean; >value : boolean diff --git a/tests/baselines/reference/declFileWithExtendsClauseThatHasItsContainerNameConflict.js b/tests/baselines/reference/declFileWithExtendsClauseThatHasItsContainerNameConflict.js index c06461e89fc..587b8ff1e27 100644 --- a/tests/baselines/reference/declFileWithExtendsClauseThatHasItsContainerNameConflict.js +++ b/tests/baselines/reference/declFileWithExtendsClauseThatHasItsContainerNameConflict.js @@ -22,8 +22,7 @@ module A.B.C { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var A; (function (A) { diff --git a/tests/baselines/reference/declarationEmit_nameConflicts3.js b/tests/baselines/reference/declarationEmit_nameConflicts3.js index ee21d9a408d..07299132bd4 100644 --- a/tests/baselines/reference/declarationEmit_nameConflicts3.js +++ b/tests/baselines/reference/declarationEmit_nameConflicts3.js @@ -30,8 +30,7 @@ module M.P { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var M; (function (M) { diff --git a/tests/baselines/reference/declarationEmit_protectedMembers.js b/tests/baselines/reference/declarationEmit_protectedMembers.js index faa1dc298e1..536f4f4aff7 100644 --- a/tests/baselines/reference/declarationEmit_protectedMembers.js +++ b/tests/baselines/reference/declarationEmit_protectedMembers.js @@ -54,8 +54,7 @@ class C4 { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; // Class with protected members var C1 = (function () { diff --git a/tests/baselines/reference/declareDottedExtend.js b/tests/baselines/reference/declareDottedExtend.js index 2579a5557fc..030e5048ef7 100644 --- a/tests/baselines/reference/declareDottedExtend.js +++ b/tests/baselines/reference/declareDottedExtend.js @@ -15,8 +15,7 @@ class E extends A.B.C{ } var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var ab = A.B; var D = (function (_super) { diff --git a/tests/baselines/reference/declareDottedExtend.types b/tests/baselines/reference/declareDottedExtend.types index 7df6c9ecb7c..1c6c48c85c9 100644 --- a/tests/baselines/reference/declareDottedExtend.types +++ b/tests/baselines/reference/declareDottedExtend.types @@ -14,15 +14,15 @@ import ab = A.B; class D extends ab.C{ } >D : D ->ab.C : any +>ab.C : ab.C >ab : typeof ab ->C : ab.C +>C : typeof ab.C class E extends A.B.C{ } >E : E ->A.B.C : any +>A.B.C : ab.C >A.B : typeof ab >A : typeof A >B : typeof ab ->C : ab.C +>C : typeof ab.C diff --git a/tests/baselines/reference/declareIdentifierAsBeginningOfStatementExpression01.js b/tests/baselines/reference/declareIdentifierAsBeginningOfStatementExpression01.js new file mode 100644 index 00000000000..047b9b76719 --- /dev/null +++ b/tests/baselines/reference/declareIdentifierAsBeginningOfStatementExpression01.js @@ -0,0 +1,16 @@ +//// [declareIdentifierAsBeginningOfStatementExpression01.ts] +class C { +} + +var declare: any; + +declare instanceof C; + +//// [declareIdentifierAsBeginningOfStatementExpression01.js] +var C = (function () { + function C() { + } + return C; +})(); +var declare; +declare instanceof C; diff --git a/tests/baselines/reference/declareIdentifierAsBeginningOfStatementExpression01.symbols b/tests/baselines/reference/declareIdentifierAsBeginningOfStatementExpression01.symbols new file mode 100644 index 00000000000..d4ef7378b08 --- /dev/null +++ b/tests/baselines/reference/declareIdentifierAsBeginningOfStatementExpression01.symbols @@ -0,0 +1,12 @@ +=== tests/cases/compiler/declareIdentifierAsBeginningOfStatementExpression01.ts === +class C { +>C : Symbol(C, Decl(declareIdentifierAsBeginningOfStatementExpression01.ts, 0, 0)) +} + +var declare: any; +>declare : Symbol(declare, Decl(declareIdentifierAsBeginningOfStatementExpression01.ts, 3, 3)) + +declare instanceof C; +>declare : Symbol(declare, Decl(declareIdentifierAsBeginningOfStatementExpression01.ts, 3, 3)) +>C : Symbol(C, Decl(declareIdentifierAsBeginningOfStatementExpression01.ts, 0, 0)) + diff --git a/tests/baselines/reference/declareIdentifierAsBeginningOfStatementExpression01.types b/tests/baselines/reference/declareIdentifierAsBeginningOfStatementExpression01.types new file mode 100644 index 00000000000..2fad2eda164 --- /dev/null +++ b/tests/baselines/reference/declareIdentifierAsBeginningOfStatementExpression01.types @@ -0,0 +1,13 @@ +=== tests/cases/compiler/declareIdentifierAsBeginningOfStatementExpression01.ts === +class C { +>C : C +} + +var declare: any; +>declare : any + +declare instanceof C; +>declare instanceof C : boolean +>declare : any +>C : typeof C + diff --git a/tests/baselines/reference/decoratorOnClass8.errors.txt b/tests/baselines/reference/decoratorOnClass8.errors.txt index cf289456f21..f9ca7fca210 100644 --- a/tests/baselines/reference/decoratorOnClass8.errors.txt +++ b/tests/baselines/reference/decoratorOnClass8.errors.txt @@ -1,4 +1,4 @@ -tests/cases/conformance/decorators/class/decoratorOnClass8.ts(3,1): error TS1222: Unable to resolve signature of class decorator when called as an expression. +tests/cases/conformance/decorators/class/decoratorOnClass8.ts(3,1): error TS1238: Unable to resolve signature of class decorator when called as an expression. Supplied parameters do not match any signature of call target. @@ -7,7 +7,7 @@ tests/cases/conformance/decorators/class/decoratorOnClass8.ts(3,1): error TS1222 @dec() ~~~~~~ -!!! error TS1222: Unable to resolve signature of class decorator when called as an expression. -!!! error TS1222: Supplied parameters do not match any signature of call target. +!!! error TS1238: Unable to resolve signature of class decorator when called as an expression. +!!! error TS1238: Supplied parameters do not match any signature of call target. class C { } \ No newline at end of file diff --git a/tests/baselines/reference/decoratorOnClassMethod12.js b/tests/baselines/reference/decoratorOnClassMethod12.js index aa938eaaaf4..05c4f285291 100644 --- a/tests/baselines/reference/decoratorOnClassMethod12.js +++ b/tests/baselines/reference/decoratorOnClassMethod12.js @@ -13,8 +13,7 @@ module M { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { if (typeof Reflect === "object" && typeof Reflect.decorate === "function") return Reflect.decorate(decorators, target, key, desc); diff --git a/tests/baselines/reference/decoratorOnClassMethod6.errors.txt b/tests/baselines/reference/decoratorOnClassMethod6.errors.txt index 1a5edbbdc48..c8ee66717ef 100644 --- a/tests/baselines/reference/decoratorOnClassMethod6.errors.txt +++ b/tests/baselines/reference/decoratorOnClassMethod6.errors.txt @@ -1,4 +1,4 @@ -tests/cases/conformance/decorators/class/method/decoratorOnClassMethod6.ts(4,5): error TS1225: Unable to resolve signature of method decorator when called as an expression. +tests/cases/conformance/decorators/class/method/decoratorOnClassMethod6.ts(4,5): error TS1241: Unable to resolve signature of method decorator when called as an expression. Supplied parameters do not match any signature of call target. @@ -8,6 +8,6 @@ tests/cases/conformance/decorators/class/method/decoratorOnClassMethod6.ts(4,5): class C { @dec ["method"]() {} ~~~~ -!!! error TS1225: Unable to resolve signature of method decorator when called as an expression. -!!! error TS1225: Supplied parameters do not match any signature of call target. +!!! error TS1241: Unable to resolve signature of method decorator when called as an expression. +!!! error TS1241: Supplied parameters do not match any signature of call target. } \ No newline at end of file diff --git a/tests/baselines/reference/decoratorOnClassMethod8.errors.txt b/tests/baselines/reference/decoratorOnClassMethod8.errors.txt index 690366faec9..f522dc01df9 100644 --- a/tests/baselines/reference/decoratorOnClassMethod8.errors.txt +++ b/tests/baselines/reference/decoratorOnClassMethod8.errors.txt @@ -1,4 +1,4 @@ -tests/cases/conformance/decorators/class/method/decoratorOnClassMethod8.ts(4,5): error TS1225: Unable to resolve signature of method decorator when called as an expression. +tests/cases/conformance/decorators/class/method/decoratorOnClassMethod8.ts(4,5): error TS1241: Unable to resolve signature of method decorator when called as an expression. Supplied parameters do not match any signature of call target. @@ -8,6 +8,6 @@ tests/cases/conformance/decorators/class/method/decoratorOnClassMethod8.ts(4,5): class C { @dec method() {} ~~~~ -!!! error TS1225: Unable to resolve signature of method decorator when called as an expression. -!!! error TS1225: Supplied parameters do not match any signature of call target. +!!! error TS1241: Unable to resolve signature of method decorator when called as an expression. +!!! error TS1241: Supplied parameters do not match any signature of call target. } \ No newline at end of file diff --git a/tests/baselines/reference/decoratorOnClassProperty11.errors.txt b/tests/baselines/reference/decoratorOnClassProperty11.errors.txt index da06808fe98..6ff700564e8 100644 --- a/tests/baselines/reference/decoratorOnClassProperty11.errors.txt +++ b/tests/baselines/reference/decoratorOnClassProperty11.errors.txt @@ -1,4 +1,4 @@ -tests/cases/conformance/decorators/class/property/decoratorOnClassProperty11.ts(4,5): error TS1224: Unable to resolve signature of property decorator when called as an expression. +tests/cases/conformance/decorators/class/property/decoratorOnClassProperty11.ts(4,5): error TS1240: Unable to resolve signature of property decorator when called as an expression. Supplied parameters do not match any signature of call target. @@ -8,6 +8,6 @@ tests/cases/conformance/decorators/class/property/decoratorOnClassProperty11.ts( class C { @dec prop; ~~~~ -!!! error TS1224: Unable to resolve signature of property decorator when called as an expression. -!!! error TS1224: Supplied parameters do not match any signature of call target. +!!! error TS1240: Unable to resolve signature of property decorator when called as an expression. +!!! error TS1240: Supplied parameters do not match any signature of call target. } \ No newline at end of file diff --git a/tests/baselines/reference/decoratorOnClassProperty6.errors.txt b/tests/baselines/reference/decoratorOnClassProperty6.errors.txt index 852735e889f..dbb104e8cd3 100644 --- a/tests/baselines/reference/decoratorOnClassProperty6.errors.txt +++ b/tests/baselines/reference/decoratorOnClassProperty6.errors.txt @@ -1,4 +1,4 @@ -tests/cases/conformance/decorators/class/property/decoratorOnClassProperty6.ts(4,5): error TS1224: Unable to resolve signature of property decorator when called as an expression. +tests/cases/conformance/decorators/class/property/decoratorOnClassProperty6.ts(4,5): error TS1240: Unable to resolve signature of property decorator when called as an expression. Supplied parameters do not match any signature of call target. @@ -8,6 +8,6 @@ tests/cases/conformance/decorators/class/property/decoratorOnClassProperty6.ts(4 class C { @dec prop; ~~~~ -!!! error TS1224: Unable to resolve signature of property decorator when called as an expression. -!!! error TS1224: Supplied parameters do not match any signature of call target. +!!! error TS1240: Unable to resolve signature of property decorator when called as an expression. +!!! error TS1240: Supplied parameters do not match any signature of call target. } \ No newline at end of file diff --git a/tests/baselines/reference/decoratorOnClassProperty7.errors.txt b/tests/baselines/reference/decoratorOnClassProperty7.errors.txt index f2d16787352..41396acd17e 100644 --- a/tests/baselines/reference/decoratorOnClassProperty7.errors.txt +++ b/tests/baselines/reference/decoratorOnClassProperty7.errors.txt @@ -1,4 +1,4 @@ -tests/cases/conformance/decorators/class/property/decoratorOnClassProperty7.ts(4,5): error TS1224: Unable to resolve signature of property decorator when called as an expression. +tests/cases/conformance/decorators/class/property/decoratorOnClassProperty7.ts(4,5): error TS1240: Unable to resolve signature of property decorator when called as an expression. Supplied parameters do not match any signature of call target. @@ -8,6 +8,6 @@ tests/cases/conformance/decorators/class/property/decoratorOnClassProperty7.ts(4 class C { @dec prop; ~~~~ -!!! error TS1224: Unable to resolve signature of property decorator when called as an expression. -!!! error TS1224: Supplied parameters do not match any signature of call target. +!!! error TS1240: Unable to resolve signature of property decorator when called as an expression. +!!! error TS1240: Supplied parameters do not match any signature of call target. } \ No newline at end of file diff --git a/tests/baselines/reference/deleteOperatorInvalidOperations.errors.txt b/tests/baselines/reference/deleteOperatorInvalidOperations.errors.txt index 5f7c6d70450..d50be713d0a 100644 --- a/tests/baselines/reference/deleteOperatorInvalidOperations.errors.txt +++ b/tests/baselines/reference/deleteOperatorInvalidOperations.errors.txt @@ -1,9 +1,10 @@ tests/cases/conformance/expressions/unaryOperators/deleteOperator/deleteOperatorInvalidOperations.ts(5,20): error TS1005: ',' expected. tests/cases/conformance/expressions/unaryOperators/deleteOperator/deleteOperatorInvalidOperations.ts(5,27): error TS1109: Expression expected. tests/cases/conformance/expressions/unaryOperators/deleteOperator/deleteOperatorInvalidOperations.ts(8,23): error TS1109: Expression expected. +tests/cases/conformance/expressions/unaryOperators/deleteOperator/deleteOperatorInvalidOperations.ts(13,16): error TS1102: 'delete' cannot be called on an identifier in strict mode. -==== tests/cases/conformance/expressions/unaryOperators/deleteOperator/deleteOperatorInvalidOperations.ts (3 errors) ==== +==== tests/cases/conformance/expressions/unaryOperators/deleteOperator/deleteOperatorInvalidOperations.ts (4 errors) ==== // Unary operator delete var ANY; @@ -23,5 +24,7 @@ tests/cases/conformance/expressions/unaryOperators/deleteOperator/deleteOperator class testADelx { constructor(public s: () => {}) { delete s; //expect error + ~ +!!! error TS1102: 'delete' cannot be called on an identifier in strict mode. } } \ No newline at end of file diff --git a/tests/baselines/reference/derivedClassConstructorWithoutSuperCall.js b/tests/baselines/reference/derivedClassConstructorWithoutSuperCall.js index 37dc2db870b..b9090176add 100644 --- a/tests/baselines/reference/derivedClassConstructorWithoutSuperCall.js +++ b/tests/baselines/reference/derivedClassConstructorWithoutSuperCall.js @@ -37,8 +37,7 @@ class Derived4 extends Base2 { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var Base = (function () { function Base() { diff --git a/tests/baselines/reference/derivedClassFunctionOverridesBaseClassAccessor.js b/tests/baselines/reference/derivedClassFunctionOverridesBaseClassAccessor.js index eaf7dfd5698..64da47e68e0 100644 --- a/tests/baselines/reference/derivedClassFunctionOverridesBaseClassAccessor.js +++ b/tests/baselines/reference/derivedClassFunctionOverridesBaseClassAccessor.js @@ -18,8 +18,7 @@ class Derived extends Base { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var Base = (function () { function Base() { diff --git a/tests/baselines/reference/derivedClassIncludesInheritedMembers.js b/tests/baselines/reference/derivedClassIncludesInheritedMembers.js index b83255ccf93..0538ba9b54a 100644 --- a/tests/baselines/reference/derivedClassIncludesInheritedMembers.js +++ b/tests/baselines/reference/derivedClassIncludesInheritedMembers.js @@ -44,8 +44,7 @@ var r8 = d2[1]; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var Base = (function () { function Base(x) { diff --git a/tests/baselines/reference/derivedClassOverridesIndexersWithAssignmentCompatibility.js b/tests/baselines/reference/derivedClassOverridesIndexersWithAssignmentCompatibility.js index 1fe59d78044..a575c9bb183 100644 --- a/tests/baselines/reference/derivedClassOverridesIndexersWithAssignmentCompatibility.js +++ b/tests/baselines/reference/derivedClassOverridesIndexersWithAssignmentCompatibility.js @@ -21,8 +21,7 @@ class Derived2 extends Base2 { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var Base = (function () { function Base() { diff --git a/tests/baselines/reference/derivedClassOverridesPrivateFunction1.js b/tests/baselines/reference/derivedClassOverridesPrivateFunction1.js index b9cd6df0338..7e11209b8fe 100644 --- a/tests/baselines/reference/derivedClassOverridesPrivateFunction1.js +++ b/tests/baselines/reference/derivedClassOverridesPrivateFunction1.js @@ -19,8 +19,7 @@ new DerivedClass(); var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var BaseClass = (function () { function BaseClass() { diff --git a/tests/baselines/reference/derivedClassOverridesPrivates.js b/tests/baselines/reference/derivedClassOverridesPrivates.js index 2cc8360a803..6662b5013d8 100644 --- a/tests/baselines/reference/derivedClassOverridesPrivates.js +++ b/tests/baselines/reference/derivedClassOverridesPrivates.js @@ -19,8 +19,7 @@ class Derived2 extends Base2 { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var Base = (function () { function Base() { diff --git a/tests/baselines/reference/derivedClassOverridesProtectedMembers.js b/tests/baselines/reference/derivedClassOverridesProtectedMembers.js index 48ee6eded6c..21f2ce87880 100644 --- a/tests/baselines/reference/derivedClassOverridesProtectedMembers.js +++ b/tests/baselines/reference/derivedClassOverridesProtectedMembers.js @@ -40,8 +40,7 @@ class Derived extends Base { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var x; var y; diff --git a/tests/baselines/reference/derivedClassOverridesProtectedMembers2.js b/tests/baselines/reference/derivedClassOverridesProtectedMembers2.js index fca27b0de04..b5fe3e93af5 100644 --- a/tests/baselines/reference/derivedClassOverridesProtectedMembers2.js +++ b/tests/baselines/reference/derivedClassOverridesProtectedMembers2.js @@ -67,8 +67,7 @@ var r8 = d2[1]; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var x; var y; diff --git a/tests/baselines/reference/derivedClassOverridesProtectedMembers3.js b/tests/baselines/reference/derivedClassOverridesProtectedMembers3.js index 2a102d55eac..c4dc1d0e9d5 100644 --- a/tests/baselines/reference/derivedClassOverridesProtectedMembers3.js +++ b/tests/baselines/reference/derivedClassOverridesProtectedMembers3.js @@ -75,8 +75,7 @@ class Derived10 extends Base { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var x; var y; diff --git a/tests/baselines/reference/derivedClassOverridesProtectedMembers4.js b/tests/baselines/reference/derivedClassOverridesProtectedMembers4.js index 5145f3919a8..f25c3b792de 100644 --- a/tests/baselines/reference/derivedClassOverridesProtectedMembers4.js +++ b/tests/baselines/reference/derivedClassOverridesProtectedMembers4.js @@ -18,8 +18,7 @@ class Derived2 extends Derived1 { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var x; var y; diff --git a/tests/baselines/reference/derivedClassOverridesPublicMembers.js b/tests/baselines/reference/derivedClassOverridesPublicMembers.js index 0529189e4c1..5125be4eeeb 100644 --- a/tests/baselines/reference/derivedClassOverridesPublicMembers.js +++ b/tests/baselines/reference/derivedClassOverridesPublicMembers.js @@ -66,8 +66,7 @@ var r8 = d2[1]; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var x; var y; diff --git a/tests/baselines/reference/derivedClassOverridesWithoutSubtype.js b/tests/baselines/reference/derivedClassOverridesWithoutSubtype.js index 5cb746bfdd3..9762c88035a 100644 --- a/tests/baselines/reference/derivedClassOverridesWithoutSubtype.js +++ b/tests/baselines/reference/derivedClassOverridesWithoutSubtype.js @@ -27,8 +27,7 @@ class Derived2 extends Base2 { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var Base = (function () { function Base() { diff --git a/tests/baselines/reference/derivedClassParameterProperties.js b/tests/baselines/reference/derivedClassParameterProperties.js index dd5b206ecdd..55c0a312b71 100644 --- a/tests/baselines/reference/derivedClassParameterProperties.js +++ b/tests/baselines/reference/derivedClassParameterProperties.js @@ -99,8 +99,7 @@ class Derived10 extends Base2 { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var Base = (function () { function Base() { diff --git a/tests/baselines/reference/derivedClassSuperCallsInNonConstructorMembers.js b/tests/baselines/reference/derivedClassSuperCallsInNonConstructorMembers.js index d2914cd6949..0c214d42fec 100644 --- a/tests/baselines/reference/derivedClassSuperCallsInNonConstructorMembers.js +++ b/tests/baselines/reference/derivedClassSuperCallsInNonConstructorMembers.js @@ -36,8 +36,7 @@ class Derived extends Base { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var Base = (function () { function Base() { diff --git a/tests/baselines/reference/derivedClassSuperCallsWithThisArg.js b/tests/baselines/reference/derivedClassSuperCallsWithThisArg.js index 7c7e9b40cec..a81a092fa54 100644 --- a/tests/baselines/reference/derivedClassSuperCallsWithThisArg.js +++ b/tests/baselines/reference/derivedClassSuperCallsWithThisArg.js @@ -32,8 +32,7 @@ class Derived4 extends Base { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var Base = (function () { function Base(a) { diff --git a/tests/baselines/reference/derivedClassTransitivity.js b/tests/baselines/reference/derivedClassTransitivity.js index ad4f3e481a7..de7669a71b5 100644 --- a/tests/baselines/reference/derivedClassTransitivity.js +++ b/tests/baselines/reference/derivedClassTransitivity.js @@ -25,8 +25,7 @@ var r2 = e.foo(''); var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var C = (function () { function C() { diff --git a/tests/baselines/reference/derivedClassTransitivity2.js b/tests/baselines/reference/derivedClassTransitivity2.js index efeb25195ff..22e930ab7f9 100644 --- a/tests/baselines/reference/derivedClassTransitivity2.js +++ b/tests/baselines/reference/derivedClassTransitivity2.js @@ -25,8 +25,7 @@ var r2 = e.foo(1, ''); var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var C = (function () { function C() { diff --git a/tests/baselines/reference/derivedClassTransitivity3.js b/tests/baselines/reference/derivedClassTransitivity3.js index 8befbf18731..a1aa3a978eb 100644 --- a/tests/baselines/reference/derivedClassTransitivity3.js +++ b/tests/baselines/reference/derivedClassTransitivity3.js @@ -25,8 +25,7 @@ var r2 = e.foo('', 1); var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var C = (function () { function C() { diff --git a/tests/baselines/reference/derivedClassTransitivity4.js b/tests/baselines/reference/derivedClassTransitivity4.js index 546c7e4a849..a4d319707c7 100644 --- a/tests/baselines/reference/derivedClassTransitivity4.js +++ b/tests/baselines/reference/derivedClassTransitivity4.js @@ -25,8 +25,7 @@ var r2 = e.foo(''); var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var C = (function () { function C() { diff --git a/tests/baselines/reference/derivedClassWithAny.js b/tests/baselines/reference/derivedClassWithAny.js index 6f9ef484627..123853f3afd 100644 --- a/tests/baselines/reference/derivedClassWithAny.js +++ b/tests/baselines/reference/derivedClassWithAny.js @@ -63,8 +63,7 @@ var r = c.foo(); // e.foo would return string var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var C = (function () { function C() { diff --git a/tests/baselines/reference/derivedClassWithPrivateInstanceShadowingProtectedInstance.js b/tests/baselines/reference/derivedClassWithPrivateInstanceShadowingProtectedInstance.js index bf8b1b51cd1..3454c60f881 100644 --- a/tests/baselines/reference/derivedClassWithPrivateInstanceShadowingProtectedInstance.js +++ b/tests/baselines/reference/derivedClassWithPrivateInstanceShadowingProtectedInstance.js @@ -26,8 +26,7 @@ class Derived extends Base { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var Base = (function () { function Base() { diff --git a/tests/baselines/reference/derivedClassWithPrivateInstanceShadowingPublicInstance.js b/tests/baselines/reference/derivedClassWithPrivateInstanceShadowingPublicInstance.js index 131c529f3bf..7de92c9cb2f 100644 --- a/tests/baselines/reference/derivedClassWithPrivateInstanceShadowingPublicInstance.js +++ b/tests/baselines/reference/derivedClassWithPrivateInstanceShadowingPublicInstance.js @@ -36,8 +36,7 @@ Derived.a = 2; // error var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var Base = (function () { function Base() { diff --git a/tests/baselines/reference/derivedClassWithPrivateStaticShadowingProtectedStatic.js b/tests/baselines/reference/derivedClassWithPrivateStaticShadowingProtectedStatic.js index d661eeadc06..36d2b7d2dc3 100644 --- a/tests/baselines/reference/derivedClassWithPrivateStaticShadowingProtectedStatic.js +++ b/tests/baselines/reference/derivedClassWithPrivateStaticShadowingProtectedStatic.js @@ -25,8 +25,7 @@ class Derived extends Base { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var Base = (function () { function Base() { diff --git a/tests/baselines/reference/derivedClassWithPrivateStaticShadowingPublicStatic.js b/tests/baselines/reference/derivedClassWithPrivateStaticShadowingPublicStatic.js index c3fc34b21c1..36080385b3b 100644 --- a/tests/baselines/reference/derivedClassWithPrivateStaticShadowingPublicStatic.js +++ b/tests/baselines/reference/derivedClassWithPrivateStaticShadowingPublicStatic.js @@ -37,8 +37,7 @@ Derived.a = 2; // error var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var Base = (function () { function Base() { diff --git a/tests/baselines/reference/derivedClassWithoutExplicitConstructor.js b/tests/baselines/reference/derivedClassWithoutExplicitConstructor.js index 16b9b110a5f..27a634ab2d9 100644 --- a/tests/baselines/reference/derivedClassWithoutExplicitConstructor.js +++ b/tests/baselines/reference/derivedClassWithoutExplicitConstructor.js @@ -29,8 +29,7 @@ var d2 = new D(new Date()); // ok var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var Base = (function () { function Base(x) { diff --git a/tests/baselines/reference/derivedClassWithoutExplicitConstructor2.js b/tests/baselines/reference/derivedClassWithoutExplicitConstructor2.js index 6e413752f1d..82c5eec1d7d 100644 --- a/tests/baselines/reference/derivedClassWithoutExplicitConstructor2.js +++ b/tests/baselines/reference/derivedClassWithoutExplicitConstructor2.js @@ -37,8 +37,7 @@ var d4 = new D(new Date(), new Date(), new Date()); var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var Base = (function () { function Base(x) { diff --git a/tests/baselines/reference/derivedClassWithoutExplicitConstructor3.js b/tests/baselines/reference/derivedClassWithoutExplicitConstructor3.js index b72fdb1503d..4bfa7c81577 100644 --- a/tests/baselines/reference/derivedClassWithoutExplicitConstructor3.js +++ b/tests/baselines/reference/derivedClassWithoutExplicitConstructor3.js @@ -51,8 +51,7 @@ var d3 = new D2(new Date(), new Date()); // ok var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var Base = (function () { function Base(x) { diff --git a/tests/baselines/reference/derivedClasses.js b/tests/baselines/reference/derivedClasses.js index 7221031cb8b..214c65bde6c 100644 --- a/tests/baselines/reference/derivedClasses.js +++ b/tests/baselines/reference/derivedClasses.js @@ -34,8 +34,7 @@ b.hue(); var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var Red = (function (_super) { __extends(Red, _super); diff --git a/tests/baselines/reference/derivedGenericClassWithAny.js b/tests/baselines/reference/derivedGenericClassWithAny.js index b5bfbd5e5db..15835e78bd5 100644 --- a/tests/baselines/reference/derivedGenericClassWithAny.js +++ b/tests/baselines/reference/derivedGenericClassWithAny.js @@ -46,8 +46,7 @@ var r = c.foo(); // e.foo would return string var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var C = (function () { function C() { diff --git a/tests/baselines/reference/derivedTypeAccessesHiddenBaseCallViaSuperPropertyAccess.js b/tests/baselines/reference/derivedTypeAccessesHiddenBaseCallViaSuperPropertyAccess.js index 564a51f2b13..0839b93971b 100644 --- a/tests/baselines/reference/derivedTypeAccessesHiddenBaseCallViaSuperPropertyAccess.js +++ b/tests/baselines/reference/derivedTypeAccessesHiddenBaseCallViaSuperPropertyAccess.js @@ -21,8 +21,7 @@ class Derived extends Base { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var Base = (function () { function Base() { diff --git a/tests/baselines/reference/derivedTypeDoesNotRequireExtendsClause.js b/tests/baselines/reference/derivedTypeDoesNotRequireExtendsClause.js index f981a5e6e54..f00c32114cf 100644 --- a/tests/baselines/reference/derivedTypeDoesNotRequireExtendsClause.js +++ b/tests/baselines/reference/derivedTypeDoesNotRequireExtendsClause.js @@ -24,8 +24,7 @@ var r: Base[] = [d1, d2]; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var Base = (function () { function Base() { diff --git a/tests/baselines/reference/destructuringParameterDeclaration3ES5.symbols b/tests/baselines/reference/destructuringParameterDeclaration3ES5.symbols index 033ad46ece1..6af2560504d 100644 --- a/tests/baselines/reference/destructuringParameterDeclaration3ES5.symbols +++ b/tests/baselines/reference/destructuringParameterDeclaration3ES5.symbols @@ -9,17 +9,17 @@ type arrayString = Array >arrayString : Symbol(arrayString, Decl(destructuringParameterDeclaration3ES5.ts, 0, 0)) >Array : Symbol(Array, Decl(lib.d.ts, 1000, 23), Decl(lib.d.ts, 1171, 11), Decl(lib.d.ts, 1439, 1)) ->String : Symbol(String, Decl(lib.d.ts, 275, 1), Decl(lib.d.ts, 443, 11), Decl(lib.d.ts, 1538, 1)) +>String : Symbol(String, Decl(lib.d.ts, 275, 1), Decl(lib.d.ts, 443, 11), Decl(lib.d.ts, 1543, 1)) type someArray = Array | number[]; >someArray : Symbol(someArray, Decl(destructuringParameterDeclaration3ES5.ts, 7, 32)) >Array : Symbol(Array, Decl(lib.d.ts, 1000, 23), Decl(lib.d.ts, 1171, 11), Decl(lib.d.ts, 1439, 1)) ->String : Symbol(String, Decl(lib.d.ts, 275, 1), Decl(lib.d.ts, 443, 11), Decl(lib.d.ts, 1538, 1)) +>String : Symbol(String, Decl(lib.d.ts, 275, 1), Decl(lib.d.ts, 443, 11), Decl(lib.d.ts, 1543, 1)) type stringOrNumArray = Array; >stringOrNumArray : Symbol(stringOrNumArray, Decl(destructuringParameterDeclaration3ES5.ts, 8, 42)) >Array : Symbol(Array, Decl(lib.d.ts, 1000, 23), Decl(lib.d.ts, 1171, 11), Decl(lib.d.ts, 1439, 1)) ->String : Symbol(String, Decl(lib.d.ts, 275, 1), Decl(lib.d.ts, 443, 11), Decl(lib.d.ts, 1538, 1)) +>String : Symbol(String, Decl(lib.d.ts, 275, 1), Decl(lib.d.ts, 443, 11), Decl(lib.d.ts, 1543, 1)) >Number : Symbol(Number, Decl(lib.d.ts, 456, 40), Decl(lib.d.ts, 518, 11)) function a1(...x: (number|string)[]) { } @@ -34,7 +34,7 @@ function a3(...a: Array) { } >a3 : Symbol(a3, Decl(destructuringParameterDeclaration3ES5.ts, 12, 21)) >a : Symbol(a, Decl(destructuringParameterDeclaration3ES5.ts, 13, 12)) >Array : Symbol(Array, Decl(lib.d.ts, 1000, 23), Decl(lib.d.ts, 1171, 11), Decl(lib.d.ts, 1439, 1)) ->String : Symbol(String, Decl(lib.d.ts, 275, 1), Decl(lib.d.ts, 443, 11), Decl(lib.d.ts, 1538, 1)) +>String : Symbol(String, Decl(lib.d.ts, 275, 1), Decl(lib.d.ts, 443, 11), Decl(lib.d.ts, 1543, 1)) function a4(...a: arrayString) { } >a4 : Symbol(a4, Decl(destructuringParameterDeclaration3ES5.ts, 13, 36)) diff --git a/tests/baselines/reference/destructuringParameterDeclaration3ES5.types b/tests/baselines/reference/destructuringParameterDeclaration3ES5.types index 64bede3e2de..d51a0e32dc8 100644 --- a/tests/baselines/reference/destructuringParameterDeclaration3ES5.types +++ b/tests/baselines/reference/destructuringParameterDeclaration3ES5.types @@ -12,7 +12,7 @@ type arrayString = Array >String : String type someArray = Array | number[]; ->someArray : number[] | String[] +>someArray : String[] | number[] >Array : T[] >String : String diff --git a/tests/baselines/reference/destructuringParameterDeclaration3ES6.symbols b/tests/baselines/reference/destructuringParameterDeclaration3ES6.symbols index d23b624a023..84c21ff77e6 100644 --- a/tests/baselines/reference/destructuringParameterDeclaration3ES6.symbols +++ b/tests/baselines/reference/destructuringParameterDeclaration3ES6.symbols @@ -9,17 +9,17 @@ type arrayString = Array >arrayString : Symbol(arrayString, Decl(destructuringParameterDeclaration3ES6.ts, 0, 0)) >Array : Symbol(Array, Decl(lib.d.ts, 1000, 23), Decl(lib.d.ts, 1171, 11), Decl(lib.d.ts, 1439, 1)) ->String : Symbol(String, Decl(lib.d.ts, 275, 1), Decl(lib.d.ts, 443, 11), Decl(lib.d.ts, 1538, 1)) +>String : Symbol(String, Decl(lib.d.ts, 275, 1), Decl(lib.d.ts, 443, 11), Decl(lib.d.ts, 1543, 1)) type someArray = Array | number[]; >someArray : Symbol(someArray, Decl(destructuringParameterDeclaration3ES6.ts, 7, 32)) >Array : Symbol(Array, Decl(lib.d.ts, 1000, 23), Decl(lib.d.ts, 1171, 11), Decl(lib.d.ts, 1439, 1)) ->String : Symbol(String, Decl(lib.d.ts, 275, 1), Decl(lib.d.ts, 443, 11), Decl(lib.d.ts, 1538, 1)) +>String : Symbol(String, Decl(lib.d.ts, 275, 1), Decl(lib.d.ts, 443, 11), Decl(lib.d.ts, 1543, 1)) type stringOrNumArray = Array; >stringOrNumArray : Symbol(stringOrNumArray, Decl(destructuringParameterDeclaration3ES6.ts, 8, 42)) >Array : Symbol(Array, Decl(lib.d.ts, 1000, 23), Decl(lib.d.ts, 1171, 11), Decl(lib.d.ts, 1439, 1)) ->String : Symbol(String, Decl(lib.d.ts, 275, 1), Decl(lib.d.ts, 443, 11), Decl(lib.d.ts, 1538, 1)) +>String : Symbol(String, Decl(lib.d.ts, 275, 1), Decl(lib.d.ts, 443, 11), Decl(lib.d.ts, 1543, 1)) >Number : Symbol(Number, Decl(lib.d.ts, 456, 40), Decl(lib.d.ts, 518, 11)) function a1(...x: (number|string)[]) { } @@ -34,7 +34,7 @@ function a3(...a: Array) { } >a3 : Symbol(a3, Decl(destructuringParameterDeclaration3ES6.ts, 12, 21)) >a : Symbol(a, Decl(destructuringParameterDeclaration3ES6.ts, 13, 12)) >Array : Symbol(Array, Decl(lib.d.ts, 1000, 23), Decl(lib.d.ts, 1171, 11), Decl(lib.d.ts, 1439, 1)) ->String : Symbol(String, Decl(lib.d.ts, 275, 1), Decl(lib.d.ts, 443, 11), Decl(lib.d.ts, 1538, 1)) +>String : Symbol(String, Decl(lib.d.ts, 275, 1), Decl(lib.d.ts, 443, 11), Decl(lib.d.ts, 1543, 1)) function a4(...a: arrayString) { } >a4 : Symbol(a4, Decl(destructuringParameterDeclaration3ES6.ts, 13, 36)) diff --git a/tests/baselines/reference/destructuringParameterDeclaration3ES6.types b/tests/baselines/reference/destructuringParameterDeclaration3ES6.types index aea7b2ae15a..63d5d074a8d 100644 --- a/tests/baselines/reference/destructuringParameterDeclaration3ES6.types +++ b/tests/baselines/reference/destructuringParameterDeclaration3ES6.types @@ -12,7 +12,7 @@ type arrayString = Array >String : String type someArray = Array | number[]; ->someArray : number[] | String[] +>someArray : String[] | number[] >Array : T[] >String : String diff --git a/tests/baselines/reference/destructuringParameterDeclaration5.js b/tests/baselines/reference/destructuringParameterDeclaration5.js index 7540302599c..38366ca67ba 100644 --- a/tests/baselines/reference/destructuringParameterDeclaration5.js +++ b/tests/baselines/reference/destructuringParameterDeclaration5.js @@ -55,8 +55,7 @@ d3({ y: "world" }); var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var Class = (function () { function Class() { diff --git a/tests/baselines/reference/destructuringTypeAssertionsES5_1.errors.txt b/tests/baselines/reference/destructuringTypeAssertionsES5_1.errors.txt new file mode 100644 index 00000000000..187c1d33f3d --- /dev/null +++ b/tests/baselines/reference/destructuringTypeAssertionsES5_1.errors.txt @@ -0,0 +1,7 @@ +tests/cases/conformance/es6/destructuring/destructuringTypeAssertionsES5_1.ts(1,18): error TS2304: Cannot find name 'foo'. + + +==== tests/cases/conformance/es6/destructuring/destructuringTypeAssertionsES5_1.ts (1 errors) ==== + var { x } = foo(); + ~~~ +!!! error TS2304: Cannot find name 'foo'. \ No newline at end of file diff --git a/tests/baselines/reference/destructuringTypeAssertionsES5_1.js b/tests/baselines/reference/destructuringTypeAssertionsES5_1.js new file mode 100644 index 00000000000..296cad051b1 --- /dev/null +++ b/tests/baselines/reference/destructuringTypeAssertionsES5_1.js @@ -0,0 +1,5 @@ +//// [destructuringTypeAssertionsES5_1.ts] +var { x } = foo(); + +//// [destructuringTypeAssertionsES5_1.js] +var x = foo().x; diff --git a/tests/baselines/reference/destructuringTypeAssertionsES5_2.errors.txt b/tests/baselines/reference/destructuringTypeAssertionsES5_2.errors.txt new file mode 100644 index 00000000000..2036653820b --- /dev/null +++ b/tests/baselines/reference/destructuringTypeAssertionsES5_2.errors.txt @@ -0,0 +1,7 @@ +tests/cases/conformance/es6/destructuring/destructuringTypeAssertionsES5_2.ts(1,19): error TS2304: Cannot find name 'foo'. + + +==== tests/cases/conformance/es6/destructuring/destructuringTypeAssertionsES5_2.ts (1 errors) ==== + var { x } = (foo()); + ~~~ +!!! error TS2304: Cannot find name 'foo'. \ No newline at end of file diff --git a/tests/baselines/reference/destructuringTypeAssertionsES5_2.js b/tests/baselines/reference/destructuringTypeAssertionsES5_2.js new file mode 100644 index 00000000000..1725b7042ec --- /dev/null +++ b/tests/baselines/reference/destructuringTypeAssertionsES5_2.js @@ -0,0 +1,5 @@ +//// [destructuringTypeAssertionsES5_2.ts] +var { x } = (foo()); + +//// [destructuringTypeAssertionsES5_2.js] +var x = foo().x; diff --git a/tests/baselines/reference/destructuringTypeAssertionsES5_3.errors.txt b/tests/baselines/reference/destructuringTypeAssertionsES5_3.errors.txt new file mode 100644 index 00000000000..a3aef8b91ea --- /dev/null +++ b/tests/baselines/reference/destructuringTypeAssertionsES5_3.errors.txt @@ -0,0 +1,7 @@ +tests/cases/conformance/es6/destructuring/destructuringTypeAssertionsES5_3.ts(1,19): error TS2304: Cannot find name 'foo'. + + +==== tests/cases/conformance/es6/destructuring/destructuringTypeAssertionsES5_3.ts (1 errors) ==== + var { x } = (foo()); + ~~~ +!!! error TS2304: Cannot find name 'foo'. \ No newline at end of file diff --git a/tests/baselines/reference/destructuringTypeAssertionsES5_3.js b/tests/baselines/reference/destructuringTypeAssertionsES5_3.js new file mode 100644 index 00000000000..1c8b8b1e5d8 --- /dev/null +++ b/tests/baselines/reference/destructuringTypeAssertionsES5_3.js @@ -0,0 +1,5 @@ +//// [destructuringTypeAssertionsES5_3.ts] +var { x } = (foo()); + +//// [destructuringTypeAssertionsES5_3.js] +var x = (foo()).x; diff --git a/tests/baselines/reference/destructuringTypeAssertionsES5_4.errors.txt b/tests/baselines/reference/destructuringTypeAssertionsES5_4.errors.txt new file mode 100644 index 00000000000..a27afe42f3c --- /dev/null +++ b/tests/baselines/reference/destructuringTypeAssertionsES5_4.errors.txt @@ -0,0 +1,7 @@ +tests/cases/conformance/es6/destructuring/destructuringTypeAssertionsES5_4.ts(1,23): error TS2304: Cannot find name 'foo'. + + +==== tests/cases/conformance/es6/destructuring/destructuringTypeAssertionsES5_4.ts (1 errors) ==== + var { x } = foo(); + ~~~ +!!! error TS2304: Cannot find name 'foo'. \ No newline at end of file diff --git a/tests/baselines/reference/destructuringTypeAssertionsES5_4.js b/tests/baselines/reference/destructuringTypeAssertionsES5_4.js new file mode 100644 index 00000000000..66a3e89c9b0 --- /dev/null +++ b/tests/baselines/reference/destructuringTypeAssertionsES5_4.js @@ -0,0 +1,5 @@ +//// [destructuringTypeAssertionsES5_4.ts] +var { x } = foo(); + +//// [destructuringTypeAssertionsES5_4.js] +var x = foo().x; diff --git a/tests/baselines/reference/destructuringTypeAssertionsES5_5.js b/tests/baselines/reference/destructuringTypeAssertionsES5_5.js new file mode 100644 index 00000000000..a51ac02af77 --- /dev/null +++ b/tests/baselines/reference/destructuringTypeAssertionsES5_5.js @@ -0,0 +1,5 @@ +//// [destructuringTypeAssertionsES5_5.ts] +var { x } = 0; + +//// [destructuringTypeAssertionsES5_5.js] +var x = (0).x; diff --git a/tests/baselines/reference/destructuringTypeAssertionsES5_5.symbols b/tests/baselines/reference/destructuringTypeAssertionsES5_5.symbols new file mode 100644 index 00000000000..d8e335f3e73 --- /dev/null +++ b/tests/baselines/reference/destructuringTypeAssertionsES5_5.symbols @@ -0,0 +1,4 @@ +=== tests/cases/conformance/es6/destructuring/destructuringTypeAssertionsES5_5.ts === +var { x } = 0; +>x : Symbol(x, Decl(destructuringTypeAssertionsES5_5.ts, 0, 5)) + diff --git a/tests/baselines/reference/destructuringTypeAssertionsES5_5.types b/tests/baselines/reference/destructuringTypeAssertionsES5_5.types new file mode 100644 index 00000000000..a7111cc4361 --- /dev/null +++ b/tests/baselines/reference/destructuringTypeAssertionsES5_5.types @@ -0,0 +1,6 @@ +=== tests/cases/conformance/es6/destructuring/destructuringTypeAssertionsES5_5.ts === +var { x } = 0; +>x : any +>0 : any +>0 : number + diff --git a/tests/baselines/reference/destructuringTypeAssertionsES5_6.errors.txt b/tests/baselines/reference/destructuringTypeAssertionsES5_6.errors.txt new file mode 100644 index 00000000000..9a27c4f47ab --- /dev/null +++ b/tests/baselines/reference/destructuringTypeAssertionsES5_6.errors.txt @@ -0,0 +1,7 @@ +tests/cases/conformance/es6/destructuring/destructuringTypeAssertionsES5_6.ts(1,22): error TS2304: Cannot find name 'Foo'. + + +==== tests/cases/conformance/es6/destructuring/destructuringTypeAssertionsES5_6.ts (1 errors) ==== + var { x } = new Foo; + ~~~ +!!! error TS2304: Cannot find name 'Foo'. \ No newline at end of file diff --git a/tests/baselines/reference/destructuringTypeAssertionsES5_6.js b/tests/baselines/reference/destructuringTypeAssertionsES5_6.js new file mode 100644 index 00000000000..01fd78f44e9 --- /dev/null +++ b/tests/baselines/reference/destructuringTypeAssertionsES5_6.js @@ -0,0 +1,5 @@ +//// [destructuringTypeAssertionsES5_6.ts] +var { x } = new Foo; + +//// [destructuringTypeAssertionsES5_6.js] +var x = (new Foo).x; diff --git a/tests/baselines/reference/destructuringTypeAssertionsES5_7.errors.txt b/tests/baselines/reference/destructuringTypeAssertionsES5_7.errors.txt new file mode 100644 index 00000000000..984f6a1dbb4 --- /dev/null +++ b/tests/baselines/reference/destructuringTypeAssertionsES5_7.errors.txt @@ -0,0 +1,7 @@ +tests/cases/conformance/es6/destructuring/destructuringTypeAssertionsES5_7.ts(1,27): error TS2304: Cannot find name 'Foo'. + + +==== tests/cases/conformance/es6/destructuring/destructuringTypeAssertionsES5_7.ts (1 errors) ==== + var { x } = new Foo; + ~~~ +!!! error TS2304: Cannot find name 'Foo'. \ No newline at end of file diff --git a/tests/baselines/reference/destructuringTypeAssertionsES5_7.js b/tests/baselines/reference/destructuringTypeAssertionsES5_7.js new file mode 100644 index 00000000000..78492eefc28 --- /dev/null +++ b/tests/baselines/reference/destructuringTypeAssertionsES5_7.js @@ -0,0 +1,5 @@ +//// [destructuringTypeAssertionsES5_7.ts] +var { x } = new Foo; + +//// [destructuringTypeAssertionsES5_7.js] +var x = (new Foo).x; diff --git a/tests/baselines/reference/downlevelLetConst11.errors.txt b/tests/baselines/reference/downlevelLetConst11.errors.txt index 42449bd3c8a..29932f55c1f 100644 --- a/tests/baselines/reference/downlevelLetConst11.errors.txt +++ b/tests/baselines/reference/downlevelLetConst11.errors.txt @@ -1,8 +1,11 @@ -tests/cases/compiler/downlevelLetConst11.ts(2,4): error TS1123: Variable declaration list cannot be empty. +tests/cases/compiler/downlevelLetConst11.ts(2,1): error TS1212: Identifier expected. 'let' is a reserved word in strict mode +tests/cases/compiler/downlevelLetConst11.ts(2,1): error TS2304: Cannot find name 'let'. -==== tests/cases/compiler/downlevelLetConst11.ts (1 errors) ==== +==== tests/cases/compiler/downlevelLetConst11.ts (2 errors) ==== "use strict"; let - -!!! error TS1123: Variable declaration list cannot be empty. \ No newline at end of file + ~~~ +!!! error TS1212: Identifier expected. 'let' is a reserved word in strict mode + ~~~ +!!! error TS2304: Cannot find name 'let'. \ No newline at end of file diff --git a/tests/baselines/reference/downlevelLetConst11.js b/tests/baselines/reference/downlevelLetConst11.js index 377c7e6a9ed..e9749923d09 100644 --- a/tests/baselines/reference/downlevelLetConst11.js +++ b/tests/baselines/reference/downlevelLetConst11.js @@ -4,4 +4,4 @@ let //// [downlevelLetConst11.js] "use strict"; -var ; +let; diff --git a/tests/baselines/reference/emitArrowFunctionWhenUsingArguments14_ES6.symbols b/tests/baselines/reference/emitArrowFunctionWhenUsingArguments14_ES6.symbols index 18e1063f1e6..48564baf796 100644 --- a/tests/baselines/reference/emitArrowFunctionWhenUsingArguments14_ES6.symbols +++ b/tests/baselines/reference/emitArrowFunctionWhenUsingArguments14_ES6.symbols @@ -5,7 +5,7 @@ function f() { if (Math.random()) { >Math.random : Symbol(Math.random, Decl(lib.d.ts, 608, 38)) ->Math : Symbol(Math, Decl(lib.d.ts, 522, 1), Decl(lib.d.ts, 633, 11), Decl(lib.d.ts, 1694, 1)) +>Math : Symbol(Math, Decl(lib.d.ts, 522, 1), Decl(lib.d.ts, 633, 11), Decl(lib.d.ts, 1691, 60)) >random : Symbol(Math.random, Decl(lib.d.ts, 608, 38)) let arguments = 100; diff --git a/tests/baselines/reference/emitArrowFunctionWhenUsingArguments15_ES6.symbols b/tests/baselines/reference/emitArrowFunctionWhenUsingArguments15_ES6.symbols index 6885b359416..5f62de9bfa1 100644 --- a/tests/baselines/reference/emitArrowFunctionWhenUsingArguments15_ES6.symbols +++ b/tests/baselines/reference/emitArrowFunctionWhenUsingArguments15_ES6.symbols @@ -8,7 +8,7 @@ function f() { if (Math.random()) { >Math.random : Symbol(Math.random, Decl(lib.d.ts, 608, 38)) ->Math : Symbol(Math, Decl(lib.d.ts, 522, 1), Decl(lib.d.ts, 633, 11), Decl(lib.d.ts, 1694, 1)) +>Math : Symbol(Math, Decl(lib.d.ts, 522, 1), Decl(lib.d.ts, 633, 11), Decl(lib.d.ts, 1691, 60)) >random : Symbol(Math.random, Decl(lib.d.ts, 608, 38)) const arguments = 100; diff --git a/tests/baselines/reference/emitArrowFunctionWhenUsingArguments16_ES6.symbols b/tests/baselines/reference/emitArrowFunctionWhenUsingArguments16_ES6.symbols index ae6be6f7951..b54ac35ba78 100644 --- a/tests/baselines/reference/emitArrowFunctionWhenUsingArguments16_ES6.symbols +++ b/tests/baselines/reference/emitArrowFunctionWhenUsingArguments16_ES6.symbols @@ -8,7 +8,7 @@ function f() { if (Math.random()) { >Math.random : Symbol(Math.random, Decl(lib.d.ts, 608, 38)) ->Math : Symbol(Math, Decl(lib.d.ts, 522, 1), Decl(lib.d.ts, 633, 11), Decl(lib.d.ts, 1694, 1)) +>Math : Symbol(Math, Decl(lib.d.ts, 522, 1), Decl(lib.d.ts, 633, 11), Decl(lib.d.ts, 1691, 60)) >random : Symbol(Math.random, Decl(lib.d.ts, 608, 38)) return () => arguments[0]; diff --git a/tests/baselines/reference/emitArrowFunctionWhenUsingArguments17_ES6.symbols b/tests/baselines/reference/emitArrowFunctionWhenUsingArguments17_ES6.symbols index c8bf211897a..df900ac860e 100644 --- a/tests/baselines/reference/emitArrowFunctionWhenUsingArguments17_ES6.symbols +++ b/tests/baselines/reference/emitArrowFunctionWhenUsingArguments17_ES6.symbols @@ -9,7 +9,7 @@ function f() { if (Math.random()) { >Math.random : Symbol(Math.random, Decl(lib.d.ts, 608, 38)) ->Math : Symbol(Math, Decl(lib.d.ts, 522, 1), Decl(lib.d.ts, 633, 11), Decl(lib.d.ts, 1694, 1)) +>Math : Symbol(Math, Decl(lib.d.ts, 522, 1), Decl(lib.d.ts, 633, 11), Decl(lib.d.ts, 1691, 60)) >random : Symbol(Math.random, Decl(lib.d.ts, 608, 38)) return () => arguments[0]; diff --git a/tests/baselines/reference/emitArrowFunctionWhenUsingArguments18_ES6.symbols b/tests/baselines/reference/emitArrowFunctionWhenUsingArguments18_ES6.symbols index cc867dd2c72..4d0887c1ff8 100644 --- a/tests/baselines/reference/emitArrowFunctionWhenUsingArguments18_ES6.symbols +++ b/tests/baselines/reference/emitArrowFunctionWhenUsingArguments18_ES6.symbols @@ -9,7 +9,7 @@ function f() { if (Math.random()) { >Math.random : Symbol(Math.random, Decl(lib.d.ts, 608, 38)) ->Math : Symbol(Math, Decl(lib.d.ts, 522, 1), Decl(lib.d.ts, 633, 11), Decl(lib.d.ts, 1694, 1)) +>Math : Symbol(Math, Decl(lib.d.ts, 522, 1), Decl(lib.d.ts, 633, 11), Decl(lib.d.ts, 1691, 60)) >random : Symbol(Math.random, Decl(lib.d.ts, 608, 38)) return () => arguments; diff --git a/tests/baselines/reference/emitClassDeclarationWithExtensionAndTypeArgumentInES6.types b/tests/baselines/reference/emitClassDeclarationWithExtensionAndTypeArgumentInES6.types index 0f546fa7b86..e469a377985 100644 --- a/tests/baselines/reference/emitClassDeclarationWithExtensionAndTypeArgumentInES6.types +++ b/tests/baselines/reference/emitClassDeclarationWithExtensionAndTypeArgumentInES6.types @@ -9,11 +9,11 @@ class B { } class C extends B { } >C : C ->B : B +>B : B class D extends B { >D : D ->B : B +>B : B constructor(a: any) >a : any diff --git a/tests/baselines/reference/emitThisInSuperMethodCall.js b/tests/baselines/reference/emitThisInSuperMethodCall.js index 9224e156de9..f5cff5a8fa5 100644 --- a/tests/baselines/reference/emitThisInSuperMethodCall.js +++ b/tests/baselines/reference/emitThisInSuperMethodCall.js @@ -31,8 +31,7 @@ class RegisteredUser extends User { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var User = (function () { function User() { diff --git a/tests/baselines/reference/errorForwardReferenceForwadingConstructor.js b/tests/baselines/reference/errorForwardReferenceForwadingConstructor.js index f1a0d741a5c..0b30745fa15 100644 --- a/tests/baselines/reference/errorForwardReferenceForwadingConstructor.js +++ b/tests/baselines/reference/errorForwardReferenceForwadingConstructor.js @@ -15,8 +15,7 @@ class derived extends base { } var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; function f() { var d1 = new derived(); diff --git a/tests/baselines/reference/errorRecoveryWithDotFollowedByNamespaceKeyword.errors.txt b/tests/baselines/reference/errorRecoveryWithDotFollowedByNamespaceKeyword.errors.txt new file mode 100644 index 00000000000..f22c018e9ea --- /dev/null +++ b/tests/baselines/reference/errorRecoveryWithDotFollowedByNamespaceKeyword.errors.txt @@ -0,0 +1,18 @@ +tests/cases/compiler/errorRecoveryWithDotFollowedByNamespaceKeyword.ts(4,15): error TS1003: Identifier expected. +tests/cases/compiler/errorRecoveryWithDotFollowedByNamespaceKeyword.ts(9,2): error TS1005: '}' expected. + + +==== tests/cases/compiler/errorRecoveryWithDotFollowedByNamespaceKeyword.ts (2 errors) ==== + namespace A { + function foo() { + if (true) { + B. + +!!! error TS1003: Identifier expected. + + + namespace B { + export function baz() { } + } + +!!! error TS1005: '}' expected. \ No newline at end of file diff --git a/tests/baselines/reference/errorRecoveryWithDotFollowedByNamespaceKeyword.js b/tests/baselines/reference/errorRecoveryWithDotFollowedByNamespaceKeyword.js new file mode 100644 index 00000000000..7eccb5c25ee --- /dev/null +++ b/tests/baselines/reference/errorRecoveryWithDotFollowedByNamespaceKeyword.js @@ -0,0 +1,26 @@ +//// [errorRecoveryWithDotFollowedByNamespaceKeyword.ts] +namespace A { + function foo() { + if (true) { + B. + + + namespace B { + export function baz() { } +} + +//// [errorRecoveryWithDotFollowedByNamespaceKeyword.js] +var A; +(function (A) { + function foo() { + if (true) { + B. + ; + var B; + (function (B) { + function baz() { } + B.baz = baz; + })(B || (B = {})); + } + } +})(A || (A = {})); diff --git a/tests/baselines/reference/errorSuperCalls.js b/tests/baselines/reference/errorSuperCalls.js index bd692f35fa3..d2d4911c76a 100644 --- a/tests/baselines/reference/errorSuperCalls.js +++ b/tests/baselines/reference/errorSuperCalls.js @@ -78,8 +78,7 @@ class OtherDerived extends OtherBase { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; //super call in class constructor with no base type var NoBase = (function () { diff --git a/tests/baselines/reference/errorSuperPropertyAccess.js b/tests/baselines/reference/errorSuperPropertyAccess.js index abf077d2b82..57a574d8a06 100644 --- a/tests/baselines/reference/errorSuperPropertyAccess.js +++ b/tests/baselines/reference/errorSuperPropertyAccess.js @@ -132,8 +132,7 @@ var obj = { n: super.wat, p: super.foo() }; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; //super property access in constructor of class with no base type //super property access in instance member function of class with no base type diff --git a/tests/baselines/reference/errorsInGenericTypeReference.js b/tests/baselines/reference/errorsInGenericTypeReference.js index 0ba69b601ae..42c7456be60 100644 --- a/tests/baselines/reference/errorsInGenericTypeReference.js +++ b/tests/baselines/reference/errorsInGenericTypeReference.js @@ -76,8 +76,7 @@ interface testInterface2 { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var Foo = (function () { function Foo() { diff --git a/tests/baselines/reference/es6ClassSuperCodegenBug.js b/tests/baselines/reference/es6ClassSuperCodegenBug.js index a374778ef45..62c96f6260d 100644 --- a/tests/baselines/reference/es6ClassSuperCodegenBug.js +++ b/tests/baselines/reference/es6ClassSuperCodegenBug.js @@ -17,8 +17,7 @@ class B extends A { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var A = (function () { function A(str1, str2) { diff --git a/tests/baselines/reference/es6ClassTest.js b/tests/baselines/reference/es6ClassTest.js index bf65840e31c..9247dfde1c3 100644 --- a/tests/baselines/reference/es6ClassTest.js +++ b/tests/baselines/reference/es6ClassTest.js @@ -88,8 +88,7 @@ declare module AmbientMod { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var Bar = (function () { function Bar(n) { diff --git a/tests/baselines/reference/es6ClassTest2.js b/tests/baselines/reference/es6ClassTest2.js index 40f1c15c8f1..20200a692ff 100644 --- a/tests/baselines/reference/es6ClassTest2.js +++ b/tests/baselines/reference/es6ClassTest2.js @@ -162,8 +162,7 @@ var ccwc = new ChildClassWithoutConstructor(1, "s"); var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var BasicMonster = (function () { function BasicMonster(name, health) { diff --git a/tests/baselines/reference/es6ClassTest7.js b/tests/baselines/reference/es6ClassTest7.js index c4f7e83b9a2..970e9c4fd9e 100644 --- a/tests/baselines/reference/es6ClassTest7.js +++ b/tests/baselines/reference/es6ClassTest7.js @@ -12,8 +12,7 @@ class Bar extends M.Foo { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var Bar = (function (_super) { __extends(Bar, _super); diff --git a/tests/baselines/reference/es6ClassTest7.types b/tests/baselines/reference/es6ClassTest7.types index f92ddad6e82..c0399204ffa 100644 --- a/tests/baselines/reference/es6ClassTest7.types +++ b/tests/baselines/reference/es6ClassTest7.types @@ -9,8 +9,8 @@ declare module M { class Bar extends M.Foo { >Bar : Bar ->M.Foo : any +>M.Foo : M.Foo >M : typeof M ->Foo : M.Foo +>Foo : typeof M.Foo } diff --git a/tests/baselines/reference/exportAssignmentOfGenericType1.js b/tests/baselines/reference/exportAssignmentOfGenericType1.js index 983c328cd98..59fa01f2ca0 100644 --- a/tests/baselines/reference/exportAssignmentOfGenericType1.js +++ b/tests/baselines/reference/exportAssignmentOfGenericType1.js @@ -26,8 +26,7 @@ define(["require", "exports"], function (require, exports) { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; define(["require", "exports", "exportAssignmentOfGenericType1_0"], function (require, exports, q) { var M = (function (_super) { diff --git a/tests/baselines/reference/exportAssignmentOfGenericType1.types b/tests/baselines/reference/exportAssignmentOfGenericType1.types index 1bf3e7454a7..06ff38b2623 100644 --- a/tests/baselines/reference/exportAssignmentOfGenericType1.types +++ b/tests/baselines/reference/exportAssignmentOfGenericType1.types @@ -5,7 +5,7 @@ import q = require("exportAssignmentOfGenericType1_0"); class M extends q { } >M : M ->q : q +>q : q var m: M; >m : M diff --git a/tests/baselines/reference/exportDeclarationInInternalModule.js b/tests/baselines/reference/exportDeclarationInInternalModule.js index 9894f1fb194..4a1ee9b739f 100644 --- a/tests/baselines/reference/exportDeclarationInInternalModule.js +++ b/tests/baselines/reference/exportDeclarationInInternalModule.js @@ -22,8 +22,7 @@ var a: Bbb.SomeType; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var Bbb = (function () { function Bbb() { diff --git a/tests/baselines/reference/exportNonInitializedVariablesAMD.errors.txt b/tests/baselines/reference/exportNonInitializedVariablesAMD.errors.txt index ae79675d8dd..28d7253a70c 100644 --- a/tests/baselines/reference/exportNonInitializedVariablesAMD.errors.txt +++ b/tests/baselines/reference/exportNonInitializedVariablesAMD.errors.txt @@ -1,15 +1,18 @@ tests/cases/conformance/externalModules/exportNonInitializedVariablesAMD.ts(2,4): error TS1123: Variable declaration list cannot be empty. +tests/cases/conformance/externalModules/exportNonInitializedVariablesAMD.ts(3,1): error TS1214: Identifier expected. 'let' is a reserved word in strict mode. Modules are automatically in strict mode. tests/cases/conformance/externalModules/exportNonInitializedVariablesAMD.ts(3,1): error TS2304: Cannot find name 'let'. tests/cases/conformance/externalModules/exportNonInitializedVariablesAMD.ts(4,6): error TS1123: Variable declaration list cannot be empty. -==== tests/cases/conformance/externalModules/exportNonInitializedVariablesAMD.ts (3 errors) ==== +==== tests/cases/conformance/externalModules/exportNonInitializedVariablesAMD.ts (4 errors) ==== var; !!! error TS1123: Variable declaration list cannot be empty. let; ~~~ +!!! error TS1214: Identifier expected. 'let' is a reserved word in strict mode. Modules are automatically in strict mode. + ~~~ !!! error TS2304: Cannot find name 'let'. const; diff --git a/tests/baselines/reference/exportNonInitializedVariablesCommonJS.errors.txt b/tests/baselines/reference/exportNonInitializedVariablesCommonJS.errors.txt index 65a18649af3..84d4cab9c83 100644 --- a/tests/baselines/reference/exportNonInitializedVariablesCommonJS.errors.txt +++ b/tests/baselines/reference/exportNonInitializedVariablesCommonJS.errors.txt @@ -1,15 +1,18 @@ tests/cases/conformance/externalModules/exportNonInitializedVariablesCommonJS.ts(2,4): error TS1123: Variable declaration list cannot be empty. +tests/cases/conformance/externalModules/exportNonInitializedVariablesCommonJS.ts(3,1): error TS1214: Identifier expected. 'let' is a reserved word in strict mode. Modules are automatically in strict mode. tests/cases/conformance/externalModules/exportNonInitializedVariablesCommonJS.ts(3,1): error TS2304: Cannot find name 'let'. tests/cases/conformance/externalModules/exportNonInitializedVariablesCommonJS.ts(4,6): error TS1123: Variable declaration list cannot be empty. -==== tests/cases/conformance/externalModules/exportNonInitializedVariablesCommonJS.ts (3 errors) ==== +==== tests/cases/conformance/externalModules/exportNonInitializedVariablesCommonJS.ts (4 errors) ==== var; !!! error TS1123: Variable declaration list cannot be empty. let; ~~~ +!!! error TS1214: Identifier expected. 'let' is a reserved word in strict mode. Modules are automatically in strict mode. + ~~~ !!! error TS2304: Cannot find name 'let'. const; diff --git a/tests/baselines/reference/exportNonInitializedVariablesES6.errors.txt b/tests/baselines/reference/exportNonInitializedVariablesES6.errors.txt index 905d16b360f..08e1d9588b6 100644 --- a/tests/baselines/reference/exportNonInitializedVariablesES6.errors.txt +++ b/tests/baselines/reference/exportNonInitializedVariablesES6.errors.txt @@ -1,15 +1,18 @@ tests/cases/conformance/externalModules/exportNonInitializedVariablesES6.ts(2,4): error TS1123: Variable declaration list cannot be empty. +tests/cases/conformance/externalModules/exportNonInitializedVariablesES6.ts(3,1): error TS1214: Identifier expected. 'let' is a reserved word in strict mode. Modules are automatically in strict mode. tests/cases/conformance/externalModules/exportNonInitializedVariablesES6.ts(3,1): error TS2304: Cannot find name 'let'. tests/cases/conformance/externalModules/exportNonInitializedVariablesES6.ts(4,6): error TS1123: Variable declaration list cannot be empty. -==== tests/cases/conformance/externalModules/exportNonInitializedVariablesES6.ts (3 errors) ==== +==== tests/cases/conformance/externalModules/exportNonInitializedVariablesES6.ts (4 errors) ==== var; !!! error TS1123: Variable declaration list cannot be empty. let; ~~~ +!!! error TS1214: Identifier expected. 'let' is a reserved word in strict mode. Modules are automatically in strict mode. + ~~~ !!! error TS2304: Cannot find name 'let'. const; diff --git a/tests/baselines/reference/exportNonInitializedVariablesSystem.errors.txt b/tests/baselines/reference/exportNonInitializedVariablesSystem.errors.txt index d7aeb5d2ac0..1e461ea7253 100644 --- a/tests/baselines/reference/exportNonInitializedVariablesSystem.errors.txt +++ b/tests/baselines/reference/exportNonInitializedVariablesSystem.errors.txt @@ -1,15 +1,18 @@ tests/cases/conformance/externalModules/exportNonInitializedVariablesSystem.ts(2,4): error TS1123: Variable declaration list cannot be empty. +tests/cases/conformance/externalModules/exportNonInitializedVariablesSystem.ts(3,1): error TS1214: Identifier expected. 'let' is a reserved word in strict mode. Modules are automatically in strict mode. tests/cases/conformance/externalModules/exportNonInitializedVariablesSystem.ts(3,1): error TS2304: Cannot find name 'let'. tests/cases/conformance/externalModules/exportNonInitializedVariablesSystem.ts(4,6): error TS1123: Variable declaration list cannot be empty. -==== tests/cases/conformance/externalModules/exportNonInitializedVariablesSystem.ts (3 errors) ==== +==== tests/cases/conformance/externalModules/exportNonInitializedVariablesSystem.ts (4 errors) ==== var; !!! error TS1123: Variable declaration list cannot be empty. let; ~~~ +!!! error TS1214: Identifier expected. 'let' is a reserved word in strict mode. Modules are automatically in strict mode. + ~~~ !!! error TS2304: Cannot find name 'let'. const; diff --git a/tests/baselines/reference/exportNonInitializedVariablesUMD.errors.txt b/tests/baselines/reference/exportNonInitializedVariablesUMD.errors.txt index eaf68e67055..b180c138501 100644 --- a/tests/baselines/reference/exportNonInitializedVariablesUMD.errors.txt +++ b/tests/baselines/reference/exportNonInitializedVariablesUMD.errors.txt @@ -1,15 +1,18 @@ tests/cases/conformance/externalModules/exportNonInitializedVariablesUMD.ts(2,4): error TS1123: Variable declaration list cannot be empty. +tests/cases/conformance/externalModules/exportNonInitializedVariablesUMD.ts(3,1): error TS1214: Identifier expected. 'let' is a reserved word in strict mode. Modules are automatically in strict mode. tests/cases/conformance/externalModules/exportNonInitializedVariablesUMD.ts(3,1): error TS2304: Cannot find name 'let'. tests/cases/conformance/externalModules/exportNonInitializedVariablesUMD.ts(4,6): error TS1123: Variable declaration list cannot be empty. -==== tests/cases/conformance/externalModules/exportNonInitializedVariablesUMD.ts (3 errors) ==== +==== tests/cases/conformance/externalModules/exportNonInitializedVariablesUMD.ts (4 errors) ==== var; !!! error TS1123: Variable declaration list cannot be empty. let; ~~~ +!!! error TS1214: Identifier expected. 'let' is a reserved word in strict mode. Modules are automatically in strict mode. + ~~~ !!! error TS2304: Cannot find name 'let'. const; diff --git a/tests/baselines/reference/exportSpecifierAndExportedMemberDeclaration.js b/tests/baselines/reference/exportSpecifierAndExportedMemberDeclaration.js new file mode 100644 index 00000000000..3fc40121011 --- /dev/null +++ b/tests/baselines/reference/exportSpecifierAndExportedMemberDeclaration.js @@ -0,0 +1,15 @@ +//// [exportSpecifierAndExportedMemberDeclaration.ts] +declare module "m2" { + export module X { + interface I { } + } + function Y(); + export { Y as X }; + function Z(): X.I; +} + +declare module "m2" { + function Z2(): X.I; +} + +//// [exportSpecifierAndExportedMemberDeclaration.js] diff --git a/tests/baselines/reference/exportSpecifierAndExportedMemberDeclaration.symbols b/tests/baselines/reference/exportSpecifierAndExportedMemberDeclaration.symbols new file mode 100644 index 00000000000..7e2de735c47 --- /dev/null +++ b/tests/baselines/reference/exportSpecifierAndExportedMemberDeclaration.symbols @@ -0,0 +1,27 @@ +=== tests/cases/compiler/exportSpecifierAndExportedMemberDeclaration.ts === +declare module "m2" { + export module X { +>X : Symbol(X, Decl(exportSpecifierAndExportedMemberDeclaration.ts, 0, 21), Decl(exportSpecifierAndExportedMemberDeclaration.ts, 5, 12)) + + interface I { } +>I : Symbol(I, Decl(exportSpecifierAndExportedMemberDeclaration.ts, 1, 21)) + } + function Y(); +>Y : Symbol(Y, Decl(exportSpecifierAndExportedMemberDeclaration.ts, 3, 5)) + + export { Y as X }; +>Y : Symbol(X, Decl(exportSpecifierAndExportedMemberDeclaration.ts, 0, 21), Decl(exportSpecifierAndExportedMemberDeclaration.ts, 5, 12)) +>X : Symbol(X, Decl(exportSpecifierAndExportedMemberDeclaration.ts, 0, 21), Decl(exportSpecifierAndExportedMemberDeclaration.ts, 5, 12)) + + function Z(): X.I; +>Z : Symbol(Z, Decl(exportSpecifierAndExportedMemberDeclaration.ts, 5, 22)) +>X : Symbol(X, Decl(exportSpecifierAndExportedMemberDeclaration.ts, 0, 21), Decl(exportSpecifierAndExportedMemberDeclaration.ts, 5, 12)) +>I : Symbol(X.I, Decl(exportSpecifierAndExportedMemberDeclaration.ts, 1, 21)) +} + +declare module "m2" { + function Z2(): X.I; +>Z2 : Symbol(Z2, Decl(exportSpecifierAndExportedMemberDeclaration.ts, 9, 21)) +>X : Symbol(X, Decl(exportSpecifierAndExportedMemberDeclaration.ts, 0, 21), Decl(exportSpecifierAndExportedMemberDeclaration.ts, 5, 12)) +>I : Symbol(X.I, Decl(exportSpecifierAndExportedMemberDeclaration.ts, 1, 21)) +} diff --git a/tests/baselines/reference/exportSpecifierAndExportedMemberDeclaration.types b/tests/baselines/reference/exportSpecifierAndExportedMemberDeclaration.types new file mode 100644 index 00000000000..931552819c7 --- /dev/null +++ b/tests/baselines/reference/exportSpecifierAndExportedMemberDeclaration.types @@ -0,0 +1,27 @@ +=== tests/cases/compiler/exportSpecifierAndExportedMemberDeclaration.ts === +declare module "m2" { + export module X { +>X : () => any + + interface I { } +>I : I + } + function Y(); +>Y : () => any + + export { Y as X }; +>Y : () => any +>X : () => any + + function Z(): X.I; +>Z : () => X.I +>X : any +>I : X.I +} + +declare module "m2" { + function Z2(): X.I; +>Z2 : () => X.I +>X : any +>I : X.I +} diff --git a/tests/baselines/reference/exportSpecifierAndLocalMemberDeclaration.errors.txt b/tests/baselines/reference/exportSpecifierAndLocalMemberDeclaration.errors.txt new file mode 100644 index 00000000000..eb444919f2c --- /dev/null +++ b/tests/baselines/reference/exportSpecifierAndLocalMemberDeclaration.errors.txt @@ -0,0 +1,18 @@ +tests/cases/compiler/exportSpecifierAndLocalMemberDeclaration.ts(11,20): error TS2503: Cannot find namespace 'X'. + + +==== tests/cases/compiler/exportSpecifierAndLocalMemberDeclaration.ts (1 errors) ==== + declare module "m2" { + module X { + interface I { } + } + function Y(); + export { Y as X }; + function Z(): X.I; + } + + declare module "m2" { + function Z2(): X.I; + ~ +!!! error TS2503: Cannot find namespace 'X'. + } \ No newline at end of file diff --git a/tests/baselines/reference/exportSpecifierAndLocalMemberDeclaration.js b/tests/baselines/reference/exportSpecifierAndLocalMemberDeclaration.js new file mode 100644 index 00000000000..d99ff3627ed --- /dev/null +++ b/tests/baselines/reference/exportSpecifierAndLocalMemberDeclaration.js @@ -0,0 +1,15 @@ +//// [exportSpecifierAndLocalMemberDeclaration.ts] +declare module "m2" { + module X { + interface I { } + } + function Y(); + export { Y as X }; + function Z(): X.I; +} + +declare module "m2" { + function Z2(): X.I; +} + +//// [exportSpecifierAndLocalMemberDeclaration.js] diff --git a/tests/baselines/reference/exportSpecifierReferencingOuterDeclaration1.js b/tests/baselines/reference/exportSpecifierReferencingOuterDeclaration1.js new file mode 100644 index 00000000000..003956e2822 --- /dev/null +++ b/tests/baselines/reference/exportSpecifierReferencingOuterDeclaration1.js @@ -0,0 +1,8 @@ +//// [exportSpecifierReferencingOuterDeclaration1.ts] +declare module X { export interface bar { } } +declare module "m" { + export { X }; + export function foo(): X.bar; +} + +//// [exportSpecifierReferencingOuterDeclaration1.js] diff --git a/tests/baselines/reference/exportSpecifierReferencingOuterDeclaration1.symbols b/tests/baselines/reference/exportSpecifierReferencingOuterDeclaration1.symbols new file mode 100644 index 00000000000..16abde86d32 --- /dev/null +++ b/tests/baselines/reference/exportSpecifierReferencingOuterDeclaration1.symbols @@ -0,0 +1,14 @@ +=== tests/cases/compiler/exportSpecifierReferencingOuterDeclaration1.ts === +declare module X { export interface bar { } } +>X : Symbol(X, Decl(exportSpecifierReferencingOuterDeclaration1.ts, 0, 0)) +>bar : Symbol(bar, Decl(exportSpecifierReferencingOuterDeclaration1.ts, 0, 18)) + +declare module "m" { + export { X }; +>X : Symbol(X, Decl(exportSpecifierReferencingOuterDeclaration1.ts, 2, 12)) + + export function foo(): X.bar; +>foo : Symbol(foo, Decl(exportSpecifierReferencingOuterDeclaration1.ts, 2, 17)) +>X : Symbol(X, Decl(exportSpecifierReferencingOuterDeclaration1.ts, 0, 0)) +>bar : Symbol(X.bar, Decl(exportSpecifierReferencingOuterDeclaration1.ts, 0, 18)) +} diff --git a/tests/baselines/reference/exportSpecifierReferencingOuterDeclaration1.types b/tests/baselines/reference/exportSpecifierReferencingOuterDeclaration1.types new file mode 100644 index 00000000000..be03554a1b0 --- /dev/null +++ b/tests/baselines/reference/exportSpecifierReferencingOuterDeclaration1.types @@ -0,0 +1,14 @@ +=== tests/cases/compiler/exportSpecifierReferencingOuterDeclaration1.ts === +declare module X { export interface bar { } } +>X : any +>bar : bar + +declare module "m" { + export { X }; +>X : any + + export function foo(): X.bar; +>foo : () => X.bar +>X : any +>bar : X.bar +} diff --git a/tests/baselines/reference/exportSpecifierReferencingOuterDeclaration2.js b/tests/baselines/reference/exportSpecifierReferencingOuterDeclaration2.js new file mode 100644 index 00000000000..e8e96784083 --- /dev/null +++ b/tests/baselines/reference/exportSpecifierReferencingOuterDeclaration2.js @@ -0,0 +1,11 @@ +//// [tests/cases/compiler/exportSpecifierReferencingOuterDeclaration2.ts] //// + +//// [exportSpecifierReferencingOuterDeclaration2_A.ts] +declare module X { export interface bar { } } + +//// [exportSpecifierReferencingOuterDeclaration2_B.ts] +export { X }; +export declare function foo(): X.bar; + +//// [exportSpecifierReferencingOuterDeclaration2_A.js] +//// [exportSpecifierReferencingOuterDeclaration2_B.js] diff --git a/tests/baselines/reference/exportSpecifierReferencingOuterDeclaration2.symbols b/tests/baselines/reference/exportSpecifierReferencingOuterDeclaration2.symbols new file mode 100644 index 00000000000..9a57645b1cb --- /dev/null +++ b/tests/baselines/reference/exportSpecifierReferencingOuterDeclaration2.symbols @@ -0,0 +1,14 @@ +=== tests/cases/compiler/exportSpecifierReferencingOuterDeclaration2_A.ts === +declare module X { export interface bar { } } +>X : Symbol(X, Decl(exportSpecifierReferencingOuterDeclaration2_A.ts, 0, 0)) +>bar : Symbol(bar, Decl(exportSpecifierReferencingOuterDeclaration2_A.ts, 0, 18)) + +=== tests/cases/compiler/exportSpecifierReferencingOuterDeclaration2_B.ts === +export { X }; +>X : Symbol(X, Decl(exportSpecifierReferencingOuterDeclaration2_B.ts, 0, 8)) + +export declare function foo(): X.bar; +>foo : Symbol(foo, Decl(exportSpecifierReferencingOuterDeclaration2_B.ts, 0, 13)) +>X : Symbol(X, Decl(exportSpecifierReferencingOuterDeclaration2_A.ts, 0, 0)) +>bar : Symbol(X.bar, Decl(exportSpecifierReferencingOuterDeclaration2_A.ts, 0, 18)) + diff --git a/tests/baselines/reference/exportSpecifierReferencingOuterDeclaration2.types b/tests/baselines/reference/exportSpecifierReferencingOuterDeclaration2.types new file mode 100644 index 00000000000..fa59948c116 --- /dev/null +++ b/tests/baselines/reference/exportSpecifierReferencingOuterDeclaration2.types @@ -0,0 +1,14 @@ +=== tests/cases/compiler/exportSpecifierReferencingOuterDeclaration2_A.ts === +declare module X { export interface bar { } } +>X : any +>bar : bar + +=== tests/cases/compiler/exportSpecifierReferencingOuterDeclaration2_B.ts === +export { X }; +>X : any + +export declare function foo(): X.bar; +>foo : () => X.bar +>X : any +>bar : X.bar + diff --git a/tests/baselines/reference/exportSpecifierReferencingOuterDeclaration3.errors.txt b/tests/baselines/reference/exportSpecifierReferencingOuterDeclaration3.errors.txt new file mode 100644 index 00000000000..e144c48bea4 --- /dev/null +++ b/tests/baselines/reference/exportSpecifierReferencingOuterDeclaration3.errors.txt @@ -0,0 +1,13 @@ +tests/cases/compiler/exportSpecifierReferencingOuterDeclaration3.ts(6,30): error TS2305: Module 'X' has no exported member 'bar'. + + +==== tests/cases/compiler/exportSpecifierReferencingOuterDeclaration3.ts (1 errors) ==== + declare module X { export interface bar { } } + declare module "m" { + module X { export interface foo { } } + export { X }; + export function foo(): X.foo; + export function bar(): X.bar; // error + ~~~ +!!! error TS2305: Module 'X' has no exported member 'bar'. + } \ No newline at end of file diff --git a/tests/baselines/reference/exportSpecifierReferencingOuterDeclaration3.js b/tests/baselines/reference/exportSpecifierReferencingOuterDeclaration3.js new file mode 100644 index 00000000000..0f6fff977da --- /dev/null +++ b/tests/baselines/reference/exportSpecifierReferencingOuterDeclaration3.js @@ -0,0 +1,10 @@ +//// [exportSpecifierReferencingOuterDeclaration3.ts] +declare module X { export interface bar { } } +declare module "m" { + module X { export interface foo { } } + export { X }; + export function foo(): X.foo; + export function bar(): X.bar; // error +} + +//// [exportSpecifierReferencingOuterDeclaration3.js] diff --git a/tests/baselines/reference/exportSpecifierReferencingOuterDeclaration4.errors.txt b/tests/baselines/reference/exportSpecifierReferencingOuterDeclaration4.errors.txt new file mode 100644 index 00000000000..6ac67c70d17 --- /dev/null +++ b/tests/baselines/reference/exportSpecifierReferencingOuterDeclaration4.errors.txt @@ -0,0 +1,13 @@ +tests/cases/compiler/exportSpecifierReferencingOuterDeclaration2_B.ts(4,34): error TS2305: Module 'X' has no exported member 'bar'. + + +==== tests/cases/compiler/exportSpecifierReferencingOuterDeclaration2_A.ts (0 errors) ==== + declare module X { export interface bar { } } + +==== tests/cases/compiler/exportSpecifierReferencingOuterDeclaration2_B.ts (1 errors) ==== + declare module X { export interface foo { } } + export { X }; + export declare function foo(): X.foo; + export declare function bar(): X.bar; // error + ~~~ +!!! error TS2305: Module 'X' has no exported member 'bar'. \ No newline at end of file diff --git a/tests/baselines/reference/exportSpecifierReferencingOuterDeclaration4.js b/tests/baselines/reference/exportSpecifierReferencingOuterDeclaration4.js new file mode 100644 index 00000000000..4edb5f711a6 --- /dev/null +++ b/tests/baselines/reference/exportSpecifierReferencingOuterDeclaration4.js @@ -0,0 +1,13 @@ +//// [tests/cases/compiler/exportSpecifierReferencingOuterDeclaration4.ts] //// + +//// [exportSpecifierReferencingOuterDeclaration2_A.ts] +declare module X { export interface bar { } } + +//// [exportSpecifierReferencingOuterDeclaration2_B.ts] +declare module X { export interface foo { } } +export { X }; +export declare function foo(): X.foo; +export declare function bar(): X.bar; // error + +//// [exportSpecifierReferencingOuterDeclaration2_A.js] +//// [exportSpecifierReferencingOuterDeclaration2_B.js] diff --git a/tests/baselines/reference/exportsAndImports3-amd.js b/tests/baselines/reference/exportsAndImports3-amd.js index e816dec9f62..3a33b12c7ff 100644 --- a/tests/baselines/reference/exportsAndImports3-amd.js +++ b/tests/baselines/reference/exportsAndImports3-amd.js @@ -40,25 +40,25 @@ define(["require", "exports"], function (require, exports) { exports.v1 = exports.v; function f() { } exports.f = f; - exports.f1 = exports.f; + exports.f1 = f; var C = (function () { function C() { } return C; })(); exports.C = C; - exports.C1 = exports.C; + exports.C1 = C; (function (E) { E[E["A"] = 0] = "A"; E[E["B"] = 1] = "B"; E[E["C"] = 2] = "C"; })(exports.E || (exports.E = {})); var E = exports.E; - exports.E1 = exports.E; + exports.E1 = E; var M; (function (M) { })(M = exports.M || (exports.M = {})); - exports.M1 = exports.M; + exports.M1 = M; exports.a = M.x; exports.a1 = exports.a; }); diff --git a/tests/baselines/reference/exportsAndImports3.js b/tests/baselines/reference/exportsAndImports3.js index db29b62449e..47491ccbc04 100644 --- a/tests/baselines/reference/exportsAndImports3.js +++ b/tests/baselines/reference/exportsAndImports3.js @@ -39,25 +39,25 @@ exports.v = 1; exports.v1 = exports.v; function f() { } exports.f = f; -exports.f1 = exports.f; +exports.f1 = f; var C = (function () { function C() { } return C; })(); exports.C = C; -exports.C1 = exports.C; +exports.C1 = C; (function (E) { E[E["A"] = 0] = "A"; E[E["B"] = 1] = "B"; E[E["C"] = 2] = "C"; })(exports.E || (exports.E = {})); var E = exports.E; -exports.E1 = exports.E; +exports.E1 = E; var M; (function (M) { })(M = exports.M || (exports.M = {})); -exports.M1 = exports.M; +exports.M1 = M; exports.a = M.x; exports.a1 = exports.a; //// [t2.js] diff --git a/tests/baselines/reference/exportsAndImportsWithContextualKeywordNames01.errors.txt b/tests/baselines/reference/exportsAndImportsWithContextualKeywordNames01.errors.txt new file mode 100644 index 00000000000..6d443464d99 --- /dev/null +++ b/tests/baselines/reference/exportsAndImportsWithContextualKeywordNames01.errors.txt @@ -0,0 +1,23 @@ +tests/cases/conformance/es6/modules/t3.ts(1,17): error TS1214: Identifier expected. 'yield' is a reserved word in strict mode. Modules are automatically in strict mode. + + +==== tests/cases/conformance/es6/modules/t1.ts (0 errors) ==== + + let set = { + set foo(x: number) { + } + } + let get = 10; + + export { set, get }; + +==== tests/cases/conformance/es6/modules/t2.ts (0 errors) ==== + import * as set from "./t1"; + +==== tests/cases/conformance/es6/modules/t3.ts (1 errors) ==== + import { set as yield } from "./t1"; + ~~~~~ +!!! error TS1214: Identifier expected. 'yield' is a reserved word in strict mode. Modules are automatically in strict mode. + +==== tests/cases/conformance/es6/modules/t4.ts (0 errors) ==== + import { get } from "./t1"; \ No newline at end of file diff --git a/tests/baselines/reference/exportsAndImportsWithContextualKeywordNames01.symbols b/tests/baselines/reference/exportsAndImportsWithContextualKeywordNames01.symbols deleted file mode 100644 index f6695a9cf37..00000000000 --- a/tests/baselines/reference/exportsAndImportsWithContextualKeywordNames01.symbols +++ /dev/null @@ -1,30 +0,0 @@ -=== tests/cases/conformance/es6/modules/t1.ts === - -let set = { ->set : Symbol(set, Decl(t1.ts, 1, 3)) - - set foo(x: number) { ->foo : Symbol(foo, Decl(t1.ts, 1, 11)) ->x : Symbol(x, Decl(t1.ts, 2, 12)) - } -} -let get = 10; ->get : Symbol(get, Decl(t1.ts, 5, 3)) - -export { set, get }; ->set : Symbol(set, Decl(t1.ts, 7, 8)) ->get : Symbol(get, Decl(t1.ts, 7, 13)) - -=== tests/cases/conformance/es6/modules/t2.ts === -import * as set from "./t1"; ->set : Symbol(set, Decl(t2.ts, 0, 6)) - -=== tests/cases/conformance/es6/modules/t3.ts === -import { set as yield } from "./t1"; ->set : Symbol(yield, Decl(t3.ts, 0, 8)) ->yield : Symbol(yield, Decl(t3.ts, 0, 8)) - -=== tests/cases/conformance/es6/modules/t4.ts === -import { get } from "./t1"; ->get : Symbol(get, Decl(t4.ts, 0, 8)) - diff --git a/tests/baselines/reference/exportsAndImportsWithContextualKeywordNames01.types b/tests/baselines/reference/exportsAndImportsWithContextualKeywordNames01.types deleted file mode 100644 index a687787c462..00000000000 --- a/tests/baselines/reference/exportsAndImportsWithContextualKeywordNames01.types +++ /dev/null @@ -1,32 +0,0 @@ -=== tests/cases/conformance/es6/modules/t1.ts === - -let set = { ->set : { foo: number; } ->{ set foo(x: number) { }} : { foo: number; } - - set foo(x: number) { ->foo : number ->x : number - } -} -let get = 10; ->get : number ->10 : number - -export { set, get }; ->set : { foo: number; } ->get : number - -=== tests/cases/conformance/es6/modules/t2.ts === -import * as set from "./t1"; ->set : typeof set - -=== tests/cases/conformance/es6/modules/t3.ts === -import { set as yield } from "./t1"; ->set : { foo: number; } ->yield : { foo: number; } - -=== tests/cases/conformance/es6/modules/t4.ts === -import { get } from "./t1"; ->get : number - diff --git a/tests/baselines/reference/extBaseClass1.js b/tests/baselines/reference/extBaseClass1.js index 9e7421b906c..07923eccc88 100644 --- a/tests/baselines/reference/extBaseClass1.js +++ b/tests/baselines/reference/extBaseClass1.js @@ -23,8 +23,7 @@ module N { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var M; (function (M) { diff --git a/tests/baselines/reference/extBaseClass1.types b/tests/baselines/reference/extBaseClass1.types index b476e1b4206..1ab2ec3ba53 100644 --- a/tests/baselines/reference/extBaseClass1.types +++ b/tests/baselines/reference/extBaseClass1.types @@ -30,9 +30,9 @@ module N { export class C3 extends M.B { >C3 : C3 ->M.B : any +>M.B : M.B >M : typeof M ->B : M.B +>B : typeof M.B } } diff --git a/tests/baselines/reference/extBaseClass2.errors.txt b/tests/baselines/reference/extBaseClass2.errors.txt index 10c406b6ba0..b4d243c7ef2 100644 --- a/tests/baselines/reference/extBaseClass2.errors.txt +++ b/tests/baselines/reference/extBaseClass2.errors.txt @@ -1,4 +1,4 @@ -tests/cases/compiler/extBaseClass2.ts(2,31): error TS2305: Module 'M' has no exported member 'B'. +tests/cases/compiler/extBaseClass2.ts(2,31): error TS2339: Property 'B' does not exist on type 'typeof M'. tests/cases/compiler/extBaseClass2.ts(7,29): error TS2304: Cannot find name 'B'. @@ -6,7 +6,7 @@ tests/cases/compiler/extBaseClass2.ts(7,29): error TS2304: Cannot find name 'B'. module N { export class C4 extends M.B { ~ -!!! error TS2305: Module 'M' has no exported member 'B'. +!!! error TS2339: Property 'B' does not exist on type 'typeof M'. } } diff --git a/tests/baselines/reference/extBaseClass2.js b/tests/baselines/reference/extBaseClass2.js index e5a717bca80..6e9972c3f29 100644 --- a/tests/baselines/reference/extBaseClass2.js +++ b/tests/baselines/reference/extBaseClass2.js @@ -14,8 +14,7 @@ module M { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var N; (function (N) { diff --git a/tests/baselines/reference/extendAndImplementTheSameBaseType.js b/tests/baselines/reference/extendAndImplementTheSameBaseType.js index c69315dbd61..6a631ceebf8 100644 --- a/tests/baselines/reference/extendAndImplementTheSameBaseType.js +++ b/tests/baselines/reference/extendAndImplementTheSameBaseType.js @@ -17,8 +17,7 @@ d.foo; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var C = (function () { function C() { diff --git a/tests/baselines/reference/extendAndImplementTheSameBaseType2.js b/tests/baselines/reference/extendAndImplementTheSameBaseType2.js index 06ea74880c2..42cf785c0b0 100644 --- a/tests/baselines/reference/extendAndImplementTheSameBaseType2.js +++ b/tests/baselines/reference/extendAndImplementTheSameBaseType2.js @@ -20,8 +20,7 @@ var r4: number = d.bar(); var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var C = (function () { function C() { diff --git a/tests/baselines/reference/extendBaseClassBeforeItsDeclared.js b/tests/baselines/reference/extendBaseClassBeforeItsDeclared.js index 7598d771bac..d8c54b58d7e 100644 --- a/tests/baselines/reference/extendBaseClassBeforeItsDeclared.js +++ b/tests/baselines/reference/extendBaseClassBeforeItsDeclared.js @@ -7,8 +7,7 @@ class base { constructor (public n: number) { } } var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var derived = (function (_super) { __extends(derived, _super); diff --git a/tests/baselines/reference/extendNonClassSymbol1.errors.txt b/tests/baselines/reference/extendNonClassSymbol1.errors.txt deleted file mode 100644 index 587ac3a5f04..00000000000 --- a/tests/baselines/reference/extendNonClassSymbol1.errors.txt +++ /dev/null @@ -1,9 +0,0 @@ -tests/cases/compiler/extendNonClassSymbol1.ts(3,17): error TS2304: Cannot find name 'x'. - - -==== tests/cases/compiler/extendNonClassSymbol1.ts (1 errors) ==== - class A { foo() { } } - var x = A; - class C extends x { } // error, could not find symbol xs - ~ -!!! error TS2304: Cannot find name 'x'. \ No newline at end of file diff --git a/tests/baselines/reference/extendNonClassSymbol1.js b/tests/baselines/reference/extendNonClassSymbol1.js index 59da2d7ca2b..29408686068 100644 --- a/tests/baselines/reference/extendNonClassSymbol1.js +++ b/tests/baselines/reference/extendNonClassSymbol1.js @@ -7,8 +7,7 @@ class C extends x { } // error, could not find symbol xs var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var A = (function () { function A() { diff --git a/tests/baselines/reference/extendNonClassSymbol1.symbols b/tests/baselines/reference/extendNonClassSymbol1.symbols new file mode 100644 index 00000000000..02291ebb181 --- /dev/null +++ b/tests/baselines/reference/extendNonClassSymbol1.symbols @@ -0,0 +1,12 @@ +=== tests/cases/compiler/extendNonClassSymbol1.ts === +class A { foo() { } } +>A : Symbol(A, Decl(extendNonClassSymbol1.ts, 0, 0)) +>foo : Symbol(foo, Decl(extendNonClassSymbol1.ts, 0, 9)) + +var x = A; +>x : Symbol(x, Decl(extendNonClassSymbol1.ts, 1, 3)) +>A : Symbol(A, Decl(extendNonClassSymbol1.ts, 0, 0)) + +class C extends x { } // error, could not find symbol xs +>C : Symbol(C, Decl(extendNonClassSymbol1.ts, 1, 10)) + diff --git a/tests/baselines/reference/extendNonClassSymbol1.types b/tests/baselines/reference/extendNonClassSymbol1.types new file mode 100644 index 00000000000..72ae7b4566c --- /dev/null +++ b/tests/baselines/reference/extendNonClassSymbol1.types @@ -0,0 +1,13 @@ +=== tests/cases/compiler/extendNonClassSymbol1.ts === +class A { foo() { } } +>A : A +>foo : () => void + +var x = A; +>x : typeof A +>A : typeof A + +class C extends x { } // error, could not find symbol xs +>C : C +>x : A + diff --git a/tests/baselines/reference/extendNonClassSymbol2.errors.txt b/tests/baselines/reference/extendNonClassSymbol2.errors.txt index 1b54474ac39..5554ff60a26 100644 --- a/tests/baselines/reference/extendNonClassSymbol2.errors.txt +++ b/tests/baselines/reference/extendNonClassSymbol2.errors.txt @@ -1,4 +1,4 @@ -tests/cases/compiler/extendNonClassSymbol2.ts(5,17): error TS2304: Cannot find name 'Foo'. +tests/cases/compiler/extendNonClassSymbol2.ts(5,17): error TS2507: Type '() => void' is not a constructor function type. ==== tests/cases/compiler/extendNonClassSymbol2.ts (1 errors) ==== @@ -8,4 +8,4 @@ tests/cases/compiler/extendNonClassSymbol2.ts(5,17): error TS2304: Cannot find n var x = new Foo(); // legal, considered a constructor function class C extends Foo {} // error, could not find symbol Foo ~~~ -!!! error TS2304: Cannot find name 'Foo'. \ No newline at end of file +!!! error TS2507: Type '() => void' is not a constructor function type. \ No newline at end of file diff --git a/tests/baselines/reference/extendNonClassSymbol2.js b/tests/baselines/reference/extendNonClassSymbol2.js index 830994e3d26..a65eeca612a 100644 --- a/tests/baselines/reference/extendNonClassSymbol2.js +++ b/tests/baselines/reference/extendNonClassSymbol2.js @@ -9,8 +9,7 @@ class C extends Foo {} // error, could not find symbol Foo var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; function Foo() { this.x = 1; diff --git a/tests/baselines/reference/extendingClassFromAliasAndUsageInIndexer.js b/tests/baselines/reference/extendingClassFromAliasAndUsageInIndexer.js index 0bf86390b74..297a7527ec0 100644 --- a/tests/baselines/reference/extendingClassFromAliasAndUsageInIndexer.js +++ b/tests/baselines/reference/extendingClassFromAliasAndUsageInIndexer.js @@ -43,8 +43,7 @@ exports.Model = Model; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var Backbone = require("extendingClassFromAliasAndUsageInIndexer_backbone"); var VisualizationModel = (function (_super) { @@ -59,8 +58,7 @@ exports.VisualizationModel = VisualizationModel; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var Backbone = require("extendingClassFromAliasAndUsageInIndexer_backbone"); var VisualizationModel = (function (_super) { diff --git a/tests/baselines/reference/extendingClassFromAliasAndUsageInIndexer.types b/tests/baselines/reference/extendingClassFromAliasAndUsageInIndexer.types index 5b9154516c5..b5323ae5c85 100644 --- a/tests/baselines/reference/extendingClassFromAliasAndUsageInIndexer.types +++ b/tests/baselines/reference/extendingClassFromAliasAndUsageInIndexer.types @@ -61,9 +61,9 @@ import Backbone = require("extendingClassFromAliasAndUsageInIndexer_backbone"); export class VisualizationModel extends Backbone.Model { >VisualizationModel : VisualizationModel ->Backbone.Model : any +>Backbone.Model : Backbone.Model >Backbone : typeof Backbone ->Model : Backbone.Model +>Model : typeof Backbone.Model // interesting stuff here } @@ -74,9 +74,9 @@ import Backbone = require("extendingClassFromAliasAndUsageInIndexer_backbone"); export class VisualizationModel extends Backbone.Model { >VisualizationModel : VisualizationModel ->Backbone.Model : any +>Backbone.Model : Backbone.Model >Backbone : typeof Backbone ->Model : Backbone.Model +>Model : typeof Backbone.Model // different interesting stuff here } diff --git a/tests/baselines/reference/extendsClauseAlreadySeen.js b/tests/baselines/reference/extendsClauseAlreadySeen.js index 3e7151b8e0d..ed6602c116a 100644 --- a/tests/baselines/reference/extendsClauseAlreadySeen.js +++ b/tests/baselines/reference/extendsClauseAlreadySeen.js @@ -10,8 +10,7 @@ class D extends C extends C { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var C = (function () { function C() { diff --git a/tests/baselines/reference/extendsClauseAlreadySeen2.js b/tests/baselines/reference/extendsClauseAlreadySeen2.js index 9ee428c36ed..2c77f4e673f 100644 --- a/tests/baselines/reference/extendsClauseAlreadySeen2.js +++ b/tests/baselines/reference/extendsClauseAlreadySeen2.js @@ -10,8 +10,7 @@ class D extends C extends C { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var C = (function () { function C() { diff --git a/tests/baselines/reference/for-inStatements.js b/tests/baselines/reference/for-inStatements.js index 749c7b47b34..d735a37ba97 100644 --- a/tests/baselines/reference/for-inStatements.js +++ b/tests/baselines/reference/for-inStatements.js @@ -84,8 +84,7 @@ for (var x in Color.Blue) { } var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var aString; for (aString in {}) { } diff --git a/tests/baselines/reference/for-inStatementsInvalid.js b/tests/baselines/reference/for-inStatementsInvalid.js index e1806272790..93b9fb9b97f 100644 --- a/tests/baselines/reference/for-inStatementsInvalid.js +++ b/tests/baselines/reference/for-inStatementsInvalid.js @@ -67,8 +67,7 @@ for (var x in i[42]) { } var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var aNumber; for (aNumber in {}) { } diff --git a/tests/baselines/reference/for-of32.errors.txt b/tests/baselines/reference/for-of32.errors.txt index 4b139d386c0..f382ea40984 100644 --- a/tests/baselines/reference/for-of32.errors.txt +++ b/tests/baselines/reference/for-of32.errors.txt @@ -1,7 +1,7 @@ -tests/cases/conformance/es6/for-ofStatements/for-of32.ts(1,10): error TS7022: 'v' implicitly has type 'any' because it is does not have a type annotation and is referenced directly or indirectly in its own initializer. +tests/cases/conformance/es6/for-ofStatements/for-of32.ts(1,10): error TS7022: 'v' implicitly has type 'any' because it does not have a type annotation and is referenced directly or indirectly in its own initializer. ==== tests/cases/conformance/es6/for-ofStatements/for-of32.ts (1 errors) ==== for (var v of v) { } ~ -!!! error TS7022: 'v' implicitly has type 'any' because it is does not have a type annotation and is referenced directly or indirectly in its own initializer. \ No newline at end of file +!!! error TS7022: 'v' implicitly has type 'any' because it does not have a type annotation and is referenced directly or indirectly in its own initializer. \ No newline at end of file diff --git a/tests/baselines/reference/for-of33.errors.txt b/tests/baselines/reference/for-of33.errors.txt index cd2d48566ab..ff1feacd7b3 100644 --- a/tests/baselines/reference/for-of33.errors.txt +++ b/tests/baselines/reference/for-of33.errors.txt @@ -1,11 +1,11 @@ -tests/cases/conformance/es6/for-ofStatements/for-of33.ts(1,10): error TS7022: 'v' implicitly has type 'any' because it is does not have a type annotation and is referenced directly or indirectly in its own initializer. +tests/cases/conformance/es6/for-ofStatements/for-of33.ts(1,10): error TS7022: 'v' implicitly has type 'any' because it does not have a type annotation and is referenced directly or indirectly in its own initializer. tests/cases/conformance/es6/for-ofStatements/for-of33.ts(4,5): error TS7023: '[Symbol.iterator]' 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. ==== tests/cases/conformance/es6/for-ofStatements/for-of33.ts (2 errors) ==== for (var v of new StringIterator) { } ~ -!!! error TS7022: 'v' implicitly has type 'any' because it is does not have a type annotation and is referenced directly or indirectly in its own initializer. +!!! error TS7022: 'v' implicitly has type 'any' because it does not have a type annotation and is referenced directly or indirectly in its own initializer. class StringIterator { [Symbol.iterator]() { diff --git a/tests/baselines/reference/for-of34.errors.txt b/tests/baselines/reference/for-of34.errors.txt index a4f55ed29ba..c378a8f5bb8 100644 --- a/tests/baselines/reference/for-of34.errors.txt +++ b/tests/baselines/reference/for-of34.errors.txt @@ -1,11 +1,11 @@ -tests/cases/conformance/es6/for-ofStatements/for-of34.ts(1,10): error TS7022: 'v' implicitly has type 'any' because it is does not have a type annotation and is referenced directly or indirectly in its own initializer. +tests/cases/conformance/es6/for-ofStatements/for-of34.ts(1,10): error TS7022: 'v' implicitly has type 'any' because it does not have a type annotation and is referenced directly or indirectly in its own initializer. tests/cases/conformance/es6/for-ofStatements/for-of34.ts(4,5): error TS7023: 'next' 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. ==== tests/cases/conformance/es6/for-ofStatements/for-of34.ts (2 errors) ==== for (var v of new StringIterator) { } ~ -!!! error TS7022: 'v' implicitly has type 'any' because it is does not have a type annotation and is referenced directly or indirectly in its own initializer. +!!! error TS7022: 'v' implicitly has type 'any' because it does not have a type annotation and is referenced directly or indirectly in its own initializer. class StringIterator { next() { diff --git a/tests/baselines/reference/for-of35.errors.txt b/tests/baselines/reference/for-of35.errors.txt index 65529752b9b..58fb5056fd7 100644 --- a/tests/baselines/reference/for-of35.errors.txt +++ b/tests/baselines/reference/for-of35.errors.txt @@ -1,11 +1,11 @@ -tests/cases/conformance/es6/for-ofStatements/for-of35.ts(1,10): error TS7022: 'v' implicitly has type 'any' because it is does not have a type annotation and is referenced directly or indirectly in its own initializer. +tests/cases/conformance/es6/for-ofStatements/for-of35.ts(1,10): error TS7022: 'v' implicitly has type 'any' because it does not have a type annotation and is referenced directly or indirectly in its own initializer. tests/cases/conformance/es6/for-ofStatements/for-of35.ts(4,5): error TS7023: 'next' 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. ==== tests/cases/conformance/es6/for-ofStatements/for-of35.ts (2 errors) ==== for (var v of new StringIterator) { } ~ -!!! error TS7022: 'v' implicitly has type 'any' because it is does not have a type annotation and is referenced directly or indirectly in its own initializer. +!!! error TS7022: 'v' implicitly has type 'any' because it does not have a type annotation and is referenced directly or indirectly in its own initializer. class StringIterator { next() { diff --git a/tests/baselines/reference/for-of37.symbols b/tests/baselines/reference/for-of37.symbols index 93f6c4f7dd6..739d9be0af0 100644 --- a/tests/baselines/reference/for-of37.symbols +++ b/tests/baselines/reference/for-of37.symbols @@ -1,7 +1,7 @@ === tests/cases/conformance/es6/for-ofStatements/for-of37.ts === var map = new Map([["", true]]); >map : Symbol(map, Decl(for-of37.ts, 0, 3)) ->Map : Symbol(Map, Decl(lib.d.ts, 1867, 1), Decl(lib.d.ts, 1889, 11)) +>Map : Symbol(Map, Decl(lib.d.ts, 1864, 1), Decl(lib.d.ts, 1886, 11)) for (var v of map) { >v : Symbol(v, Decl(for-of37.ts, 1, 8)) diff --git a/tests/baselines/reference/for-of38.symbols b/tests/baselines/reference/for-of38.symbols index fab42d91724..9322fea69e6 100644 --- a/tests/baselines/reference/for-of38.symbols +++ b/tests/baselines/reference/for-of38.symbols @@ -1,7 +1,7 @@ === tests/cases/conformance/es6/for-ofStatements/for-of38.ts === var map = new Map([["", true]]); >map : Symbol(map, Decl(for-of38.ts, 0, 3)) ->Map : Symbol(Map, Decl(lib.d.ts, 1867, 1), Decl(lib.d.ts, 1889, 11)) +>Map : Symbol(Map, Decl(lib.d.ts, 1864, 1), Decl(lib.d.ts, 1886, 11)) for (var [k, v] of map) { >k : Symbol(k, Decl(for-of38.ts, 1, 10)) diff --git a/tests/baselines/reference/for-of40.symbols b/tests/baselines/reference/for-of40.symbols index 1cd3538f987..72bbf78884e 100644 --- a/tests/baselines/reference/for-of40.symbols +++ b/tests/baselines/reference/for-of40.symbols @@ -1,7 +1,7 @@ === tests/cases/conformance/es6/for-ofStatements/for-of40.ts === var map = new Map([["", true]]); >map : Symbol(map, Decl(for-of40.ts, 0, 3)) ->Map : Symbol(Map, Decl(lib.d.ts, 1867, 1), Decl(lib.d.ts, 1889, 11)) +>Map : Symbol(Map, Decl(lib.d.ts, 1864, 1), Decl(lib.d.ts, 1886, 11)) for (var [k = "", v = false] of map) { >k : Symbol(k, Decl(for-of40.ts, 1, 10)) diff --git a/tests/baselines/reference/for-of45.symbols b/tests/baselines/reference/for-of45.symbols index 9fda4cb4e0a..e1e7717269f 100644 --- a/tests/baselines/reference/for-of45.symbols +++ b/tests/baselines/reference/for-of45.symbols @@ -5,7 +5,7 @@ var k: string, v: boolean; var map = new Map([["", true]]); >map : Symbol(map, Decl(for-of45.ts, 1, 3)) ->Map : Symbol(Map, Decl(lib.d.ts, 1867, 1), Decl(lib.d.ts, 1889, 11)) +>Map : Symbol(Map, Decl(lib.d.ts, 1864, 1), Decl(lib.d.ts, 1886, 11)) for ([k = "", v = false] of map) { >k : Symbol(k, Decl(for-of45.ts, 0, 3)) diff --git a/tests/baselines/reference/for-of50.symbols b/tests/baselines/reference/for-of50.symbols index c176e1aca0c..571dd9dc389 100644 --- a/tests/baselines/reference/for-of50.symbols +++ b/tests/baselines/reference/for-of50.symbols @@ -1,7 +1,7 @@ === tests/cases/conformance/es6/for-ofStatements/for-of50.ts === var map = new Map([["", true]]); >map : Symbol(map, Decl(for-of50.ts, 0, 3)) ->Map : Symbol(Map, Decl(lib.d.ts, 1867, 1), Decl(lib.d.ts, 1889, 11)) +>Map : Symbol(Map, Decl(lib.d.ts, 1864, 1), Decl(lib.d.ts, 1886, 11)) for (const [k, v] of map) { >k : Symbol(k, Decl(for-of50.ts, 1, 12)) diff --git a/tests/baselines/reference/for-of57.symbols b/tests/baselines/reference/for-of57.symbols index 27aed0777ba..574d52e4c56 100644 --- a/tests/baselines/reference/for-of57.symbols +++ b/tests/baselines/reference/for-of57.symbols @@ -1,7 +1,7 @@ === tests/cases/conformance/es6/for-ofStatements/for-of57.ts === var iter: Iterable; >iter : Symbol(iter, Decl(for-of57.ts, 0, 3)) ->Iterable : Symbol(Iterable, Decl(lib.d.ts, 1663, 1)) +>Iterable : Symbol(Iterable, Decl(lib.d.ts, 1668, 1)) for (let num of iter) { } >num : Symbol(num, Decl(for-of57.ts, 1, 8)) diff --git a/tests/baselines/reference/forStatementsMultipleInvalidDecl.js b/tests/baselines/reference/forStatementsMultipleInvalidDecl.js index b00e8acef14..1dde9981880 100644 --- a/tests/baselines/reference/forStatementsMultipleInvalidDecl.js +++ b/tests/baselines/reference/forStatementsMultipleInvalidDecl.js @@ -57,8 +57,7 @@ for( var m = M.A;;){} var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var C = (function () { function C() { diff --git a/tests/baselines/reference/functionDeclarationWithResolutionOfTypeNamedArguments01.js b/tests/baselines/reference/functionDeclarationWithResolutionOfTypeNamedArguments01.js new file mode 100644 index 00000000000..3659f3fd9f9 --- /dev/null +++ b/tests/baselines/reference/functionDeclarationWithResolutionOfTypeNamedArguments01.js @@ -0,0 +1,12 @@ +//// [functionDeclarationWithResolutionOfTypeNamedArguments01.ts] +interface arguments { +} + +function f() { + arguments; +} + +//// [functionDeclarationWithResolutionOfTypeNamedArguments01.js] +function f() { + arguments; +} diff --git a/tests/baselines/reference/functionDeclarationWithResolutionOfTypeNamedArguments01.symbols b/tests/baselines/reference/functionDeclarationWithResolutionOfTypeNamedArguments01.symbols new file mode 100644 index 00000000000..8a36f146001 --- /dev/null +++ b/tests/baselines/reference/functionDeclarationWithResolutionOfTypeNamedArguments01.symbols @@ -0,0 +1,12 @@ +=== tests/cases/compiler/functionDeclarationWithResolutionOfTypeNamedArguments01.ts === +interface arguments { +>arguments : Symbol(arguments, Decl(functionDeclarationWithResolutionOfTypeNamedArguments01.ts, 0, 0)) +} + +function f() { +>f : Symbol(f, Decl(functionDeclarationWithResolutionOfTypeNamedArguments01.ts, 1, 1)) + + arguments; +>arguments : Symbol(arguments, Decl(functionDeclarationWithResolutionOfTypeNamedArguments01.ts, 0, 0)) +>arguments : Symbol(arguments) +} diff --git a/tests/baselines/reference/functionDeclarationWithResolutionOfTypeNamedArguments01.types b/tests/baselines/reference/functionDeclarationWithResolutionOfTypeNamedArguments01.types new file mode 100644 index 00000000000..72dbbf8ec69 --- /dev/null +++ b/tests/baselines/reference/functionDeclarationWithResolutionOfTypeNamedArguments01.types @@ -0,0 +1,13 @@ +=== tests/cases/compiler/functionDeclarationWithResolutionOfTypeNamedArguments01.ts === +interface arguments { +>arguments : arguments +} + +function f() { +>f : () => void + + arguments; +>arguments : arguments +>arguments : arguments +>arguments : IArguments +} diff --git a/tests/baselines/reference/functionDeclarationWithResolutionOfTypeOfSameName01.js b/tests/baselines/reference/functionDeclarationWithResolutionOfTypeOfSameName01.js new file mode 100644 index 00000000000..6f5bb2cacf9 --- /dev/null +++ b/tests/baselines/reference/functionDeclarationWithResolutionOfTypeOfSameName01.js @@ -0,0 +1,12 @@ +//// [functionDeclarationWithResolutionOfTypeOfSameName01.ts] +interface f { +} + +function f() { + f; +} + +//// [functionDeclarationWithResolutionOfTypeOfSameName01.js] +function f() { + f; +} diff --git a/tests/baselines/reference/functionDeclarationWithResolutionOfTypeOfSameName01.symbols b/tests/baselines/reference/functionDeclarationWithResolutionOfTypeOfSameName01.symbols new file mode 100644 index 00000000000..aa51fad0538 --- /dev/null +++ b/tests/baselines/reference/functionDeclarationWithResolutionOfTypeOfSameName01.symbols @@ -0,0 +1,12 @@ +=== tests/cases/compiler/functionDeclarationWithResolutionOfTypeOfSameName01.ts === +interface f { +>f : Symbol(f, Decl(functionDeclarationWithResolutionOfTypeOfSameName01.ts, 0, 0), Decl(functionDeclarationWithResolutionOfTypeOfSameName01.ts, 1, 1)) +} + +function f() { +>f : Symbol(f, Decl(functionDeclarationWithResolutionOfTypeOfSameName01.ts, 0, 0), Decl(functionDeclarationWithResolutionOfTypeOfSameName01.ts, 1, 1)) + + f; +>f : Symbol(f, Decl(functionDeclarationWithResolutionOfTypeOfSameName01.ts, 0, 0), Decl(functionDeclarationWithResolutionOfTypeOfSameName01.ts, 1, 1)) +>f : Symbol(f, Decl(functionDeclarationWithResolutionOfTypeOfSameName01.ts, 0, 0), Decl(functionDeclarationWithResolutionOfTypeOfSameName01.ts, 1, 1)) +} diff --git a/tests/baselines/reference/functionDeclarationWithResolutionOfTypeOfSameName01.types b/tests/baselines/reference/functionDeclarationWithResolutionOfTypeOfSameName01.types new file mode 100644 index 00000000000..1067b8989c8 --- /dev/null +++ b/tests/baselines/reference/functionDeclarationWithResolutionOfTypeOfSameName01.types @@ -0,0 +1,13 @@ +=== tests/cases/compiler/functionDeclarationWithResolutionOfTypeOfSameName01.ts === +interface f { +>f : f +} + +function f() { +>f : () => void + + f; +>f : f +>f : f +>f : () => void +} diff --git a/tests/baselines/reference/functionExpressionWithResolutionOfTypeNamedArguments01.js b/tests/baselines/reference/functionExpressionWithResolutionOfTypeNamedArguments01.js new file mode 100644 index 00000000000..43b38f2dd39 --- /dev/null +++ b/tests/baselines/reference/functionExpressionWithResolutionOfTypeNamedArguments01.js @@ -0,0 +1,12 @@ +//// [functionExpressionWithResolutionOfTypeNamedArguments01.ts] +interface arguments { +} + +var x = function f() { + arguments; +} + +//// [functionExpressionWithResolutionOfTypeNamedArguments01.js] +var x = function f() { + arguments; +}; diff --git a/tests/baselines/reference/functionExpressionWithResolutionOfTypeNamedArguments01.symbols b/tests/baselines/reference/functionExpressionWithResolutionOfTypeNamedArguments01.symbols new file mode 100644 index 00000000000..d2455fd0106 --- /dev/null +++ b/tests/baselines/reference/functionExpressionWithResolutionOfTypeNamedArguments01.symbols @@ -0,0 +1,13 @@ +=== tests/cases/compiler/functionExpressionWithResolutionOfTypeNamedArguments01.ts === +interface arguments { +>arguments : Symbol(arguments, Decl(functionExpressionWithResolutionOfTypeNamedArguments01.ts, 0, 0)) +} + +var x = function f() { +>x : Symbol(x, Decl(functionExpressionWithResolutionOfTypeNamedArguments01.ts, 3, 3)) +>f : Symbol(f, Decl(functionExpressionWithResolutionOfTypeNamedArguments01.ts, 3, 7)) + + arguments; +>arguments : Symbol(arguments, Decl(functionExpressionWithResolutionOfTypeNamedArguments01.ts, 0, 0)) +>arguments : Symbol(arguments) +} diff --git a/tests/baselines/reference/functionExpressionWithResolutionOfTypeNamedArguments01.types b/tests/baselines/reference/functionExpressionWithResolutionOfTypeNamedArguments01.types new file mode 100644 index 00000000000..1a65010a4f6 --- /dev/null +++ b/tests/baselines/reference/functionExpressionWithResolutionOfTypeNamedArguments01.types @@ -0,0 +1,15 @@ +=== tests/cases/compiler/functionExpressionWithResolutionOfTypeNamedArguments01.ts === +interface arguments { +>arguments : arguments +} + +var x = function f() { +>x : () => void +>function f() { arguments;} : () => void +>f : () => void + + arguments; +>arguments : arguments +>arguments : arguments +>arguments : IArguments +} diff --git a/tests/baselines/reference/functionExpressionWithResolutionOfTypeOfSameName01.js b/tests/baselines/reference/functionExpressionWithResolutionOfTypeOfSameName01.js new file mode 100644 index 00000000000..c9af7ab3297 --- /dev/null +++ b/tests/baselines/reference/functionExpressionWithResolutionOfTypeOfSameName01.js @@ -0,0 +1,12 @@ +//// [functionExpressionWithResolutionOfTypeOfSameName01.ts] +interface f { +} + +var x = function f() { + f; +} + +//// [functionExpressionWithResolutionOfTypeOfSameName01.js] +var x = function f() { + f; +}; diff --git a/tests/baselines/reference/functionExpressionWithResolutionOfTypeOfSameName01.symbols b/tests/baselines/reference/functionExpressionWithResolutionOfTypeOfSameName01.symbols new file mode 100644 index 00000000000..cd2248c6018 --- /dev/null +++ b/tests/baselines/reference/functionExpressionWithResolutionOfTypeOfSameName01.symbols @@ -0,0 +1,13 @@ +=== tests/cases/compiler/functionExpressionWithResolutionOfTypeOfSameName01.ts === +interface f { +>f : Symbol(f, Decl(functionExpressionWithResolutionOfTypeOfSameName01.ts, 0, 0)) +} + +var x = function f() { +>x : Symbol(x, Decl(functionExpressionWithResolutionOfTypeOfSameName01.ts, 3, 3)) +>f : Symbol(f, Decl(functionExpressionWithResolutionOfTypeOfSameName01.ts, 3, 7)) + + f; +>f : Symbol(f, Decl(functionExpressionWithResolutionOfTypeOfSameName01.ts, 0, 0)) +>f : Symbol(f, Decl(functionExpressionWithResolutionOfTypeOfSameName01.ts, 3, 7)) +} diff --git a/tests/baselines/reference/functionExpressionWithResolutionOfTypeOfSameName01.types b/tests/baselines/reference/functionExpressionWithResolutionOfTypeOfSameName01.types new file mode 100644 index 00000000000..08b51f35226 --- /dev/null +++ b/tests/baselines/reference/functionExpressionWithResolutionOfTypeOfSameName01.types @@ -0,0 +1,15 @@ +=== tests/cases/compiler/functionExpressionWithResolutionOfTypeOfSameName01.ts === +interface f { +>f : f +} + +var x = function f() { +>x : () => void +>function f() { f;} : () => void +>f : () => void + + f; +>f : f +>f : f +>f : () => void +} diff --git a/tests/baselines/reference/functionExpressionWithResolutionOfTypeOfSameName02.js b/tests/baselines/reference/functionExpressionWithResolutionOfTypeOfSameName02.js new file mode 100644 index 00000000000..ada96c63a56 --- /dev/null +++ b/tests/baselines/reference/functionExpressionWithResolutionOfTypeOfSameName02.js @@ -0,0 +1,12 @@ +//// [functionExpressionWithResolutionOfTypeOfSameName02.ts] +interface Foo { +} + +var x = function Foo() { + var x: Foo; +} + +//// [functionExpressionWithResolutionOfTypeOfSameName02.js] +var x = function Foo() { + var x; +}; diff --git a/tests/baselines/reference/functionExpressionWithResolutionOfTypeOfSameName02.symbols b/tests/baselines/reference/functionExpressionWithResolutionOfTypeOfSameName02.symbols new file mode 100644 index 00000000000..89b46c99b4e --- /dev/null +++ b/tests/baselines/reference/functionExpressionWithResolutionOfTypeOfSameName02.symbols @@ -0,0 +1,13 @@ +=== tests/cases/compiler/functionExpressionWithResolutionOfTypeOfSameName02.ts === +interface Foo { +>Foo : Symbol(Foo, Decl(functionExpressionWithResolutionOfTypeOfSameName02.ts, 0, 0)) +} + +var x = function Foo() { +>x : Symbol(x, Decl(functionExpressionWithResolutionOfTypeOfSameName02.ts, 3, 3)) +>Foo : Symbol(Foo, Decl(functionExpressionWithResolutionOfTypeOfSameName02.ts, 3, 7)) + + var x: Foo; +>x : Symbol(x, Decl(functionExpressionWithResolutionOfTypeOfSameName02.ts, 4, 7)) +>Foo : Symbol(Foo, Decl(functionExpressionWithResolutionOfTypeOfSameName02.ts, 0, 0)) +} diff --git a/tests/baselines/reference/functionExpressionWithResolutionOfTypeOfSameName02.types b/tests/baselines/reference/functionExpressionWithResolutionOfTypeOfSameName02.types new file mode 100644 index 00000000000..218276a95ea --- /dev/null +++ b/tests/baselines/reference/functionExpressionWithResolutionOfTypeOfSameName02.types @@ -0,0 +1,14 @@ +=== tests/cases/compiler/functionExpressionWithResolutionOfTypeOfSameName02.ts === +interface Foo { +>Foo : Foo +} + +var x = function Foo() { +>x : () => void +>function Foo() { var x: Foo;} : () => void +>Foo : () => void + + var x: Foo; +>x : Foo +>Foo : Foo +} diff --git a/tests/baselines/reference/functionImplementationErrors.js b/tests/baselines/reference/functionImplementationErrors.js index 6c1daffdaf1..42be5f21458 100644 --- a/tests/baselines/reference/functionImplementationErrors.js +++ b/tests/baselines/reference/functionImplementationErrors.js @@ -77,8 +77,7 @@ var f13 = () => { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; // FunctionExpression with no return type annotation with multiple return statements with unrelated types var f1 = function () { diff --git a/tests/baselines/reference/functionImplementations.js b/tests/baselines/reference/functionImplementations.js index 0370c4c0027..3fc040650e4 100644 --- a/tests/baselines/reference/functionImplementations.js +++ b/tests/baselines/reference/functionImplementations.js @@ -160,8 +160,7 @@ var f12: (x: number) => any = x => { // should be (x: number) => Base | AnotherC var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; // FunctionExpression with no return type annotation and no return statement returns void var v = function () { }(); diff --git a/tests/baselines/reference/functionSubtypingOfVarArgs.js b/tests/baselines/reference/functionSubtypingOfVarArgs.js index b0168975677..ddcb0570908 100644 --- a/tests/baselines/reference/functionSubtypingOfVarArgs.js +++ b/tests/baselines/reference/functionSubtypingOfVarArgs.js @@ -18,8 +18,7 @@ class StringEvent extends EventBase { // should work var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var EventBase = (function () { function EventBase() { diff --git a/tests/baselines/reference/functionSubtypingOfVarArgs2.js b/tests/baselines/reference/functionSubtypingOfVarArgs2.js index 7efd35cc2d2..d04a5b97dae 100644 --- a/tests/baselines/reference/functionSubtypingOfVarArgs2.js +++ b/tests/baselines/reference/functionSubtypingOfVarArgs2.js @@ -18,8 +18,7 @@ class StringEvent extends EventBase { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var EventBase = (function () { function EventBase() { diff --git a/tests/baselines/reference/functionsWithModifiersInBlocks1.errors.txt b/tests/baselines/reference/functionsWithModifiersInBlocks1.errors.txt index 94e246f8972..f6240f5e697 100644 --- a/tests/baselines/reference/functionsWithModifiersInBlocks1.errors.txt +++ b/tests/baselines/reference/functionsWithModifiersInBlocks1.errors.txt @@ -4,12 +4,11 @@ tests/cases/compiler/functionsWithModifiersInBlocks1.ts(2,25): error TS1184: An tests/cases/compiler/functionsWithModifiersInBlocks1.ts(3,4): error TS1184: Modifiers cannot appear here. tests/cases/compiler/functionsWithModifiersInBlocks1.ts(3,20): error TS2393: Duplicate function implementation. tests/cases/compiler/functionsWithModifiersInBlocks1.ts(4,4): error TS1184: Modifiers cannot appear here. -tests/cases/compiler/functionsWithModifiersInBlocks1.ts(4,12): error TS1029: 'export' modifier must precede 'declare' modifier. tests/cases/compiler/functionsWithModifiersInBlocks1.ts(4,28): error TS2393: Duplicate function implementation. tests/cases/compiler/functionsWithModifiersInBlocks1.ts(4,32): error TS1184: An implementation cannot be declared in ambient contexts. -==== tests/cases/compiler/functionsWithModifiersInBlocks1.ts (9 errors) ==== +==== tests/cases/compiler/functionsWithModifiersInBlocks1.ts (8 errors) ==== { declare function f() { } ~~~~~~~ @@ -26,8 +25,6 @@ tests/cases/compiler/functionsWithModifiersInBlocks1.ts(4,32): error TS1184: An declare export function f() { } ~~~~~~~ !!! error TS1184: Modifiers cannot appear here. - ~~~~~~ -!!! error TS1029: 'export' modifier must precede 'declare' modifier. ~ !!! error TS2393: Duplicate function implementation. ~ diff --git a/tests/baselines/reference/generatedContextualTyping.js b/tests/baselines/reference/generatedContextualTyping.js index 3c2c704ddb0..1f7d2b8035f 100644 --- a/tests/baselines/reference/generatedContextualTyping.js +++ b/tests/baselines/reference/generatedContextualTyping.js @@ -358,8 +358,7 @@ var x356 = function(n: Genric) { }; x356({ func: n => { return [d1, d2]; } var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var Base = (function () { function Base() { diff --git a/tests/baselines/reference/generatorES6_1.errors.txt b/tests/baselines/reference/generatorES6_1.errors.txt deleted file mode 100644 index b02da7f0b53..00000000000 --- a/tests/baselines/reference/generatorES6_1.errors.txt +++ /dev/null @@ -1,12 +0,0 @@ -tests/cases/compiler/generatorES6_1.ts(1,9): error TS9001: Generators are not currently supported. -tests/cases/compiler/generatorES6_1.ts(2,5): error TS9000: 'yield' expressions are not currently supported. - - -==== tests/cases/compiler/generatorES6_1.ts (2 errors) ==== - function* foo() { - ~ -!!! error TS9001: Generators are not currently supported. - yield - ~~~~~ -!!! error TS9000: 'yield' expressions are not currently supported. - } \ No newline at end of file diff --git a/tests/baselines/reference/generatorES6_1.symbols b/tests/baselines/reference/generatorES6_1.symbols new file mode 100644 index 00000000000..fc5aa602e01 --- /dev/null +++ b/tests/baselines/reference/generatorES6_1.symbols @@ -0,0 +1,6 @@ +=== tests/cases/compiler/generatorES6_1.ts === +function* foo() { +>foo : Symbol(foo, Decl(generatorES6_1.ts, 0, 0)) + + yield +} diff --git a/tests/baselines/reference/generatorES6_1.types b/tests/baselines/reference/generatorES6_1.types new file mode 100644 index 00000000000..13ac7c05844 --- /dev/null +++ b/tests/baselines/reference/generatorES6_1.types @@ -0,0 +1,7 @@ +=== tests/cases/compiler/generatorES6_1.ts === +function* foo() { +>foo : () => IterableIterator + + yield +>yield : any +} diff --git a/tests/baselines/reference/generatorES6_2.errors.txt b/tests/baselines/reference/generatorES6_2.errors.txt deleted file mode 100644 index 8d956fc7f63..00000000000 --- a/tests/baselines/reference/generatorES6_2.errors.txt +++ /dev/null @@ -1,14 +0,0 @@ -tests/cases/compiler/generatorES6_2.ts(2,12): error TS9001: Generators are not currently supported. -tests/cases/compiler/generatorES6_2.ts(3,9): error TS9000: 'yield' expressions are not currently supported. - - -==== tests/cases/compiler/generatorES6_2.ts (2 errors) ==== - class C { - public * foo() { - ~ -!!! error TS9001: Generators are not currently supported. - yield 1 - ~~~~~ -!!! error TS9000: 'yield' expressions are not currently supported. - } - } \ No newline at end of file diff --git a/tests/baselines/reference/generatorES6_2.symbols b/tests/baselines/reference/generatorES6_2.symbols new file mode 100644 index 00000000000..a64b1304692 --- /dev/null +++ b/tests/baselines/reference/generatorES6_2.symbols @@ -0,0 +1,10 @@ +=== tests/cases/compiler/generatorES6_2.ts === +class C { +>C : Symbol(C, Decl(generatorES6_2.ts, 0, 0)) + + public * foo() { +>foo : Symbol(foo, Decl(generatorES6_2.ts, 0, 9)) + + yield 1 + } +} diff --git a/tests/baselines/reference/generatorES6_2.types b/tests/baselines/reference/generatorES6_2.types new file mode 100644 index 00000000000..9c9c8692757 --- /dev/null +++ b/tests/baselines/reference/generatorES6_2.types @@ -0,0 +1,12 @@ +=== tests/cases/compiler/generatorES6_2.ts === +class C { +>C : C + + public * foo() { +>foo : () => IterableIterator + + yield 1 +>yield 1 : any +>1 : number + } +} diff --git a/tests/baselines/reference/generatorES6_3.errors.txt b/tests/baselines/reference/generatorES6_3.errors.txt deleted file mode 100644 index e1c1d918ce6..00000000000 --- a/tests/baselines/reference/generatorES6_3.errors.txt +++ /dev/null @@ -1,12 +0,0 @@ -tests/cases/compiler/generatorES6_3.ts(1,17): error TS9001: Generators are not currently supported. -tests/cases/compiler/generatorES6_3.ts(2,5): error TS9000: 'yield' expressions are not currently supported. - - -==== tests/cases/compiler/generatorES6_3.ts (2 errors) ==== - var v = function*() { - ~ -!!! error TS9001: Generators are not currently supported. - yield 0 - ~~~~~ -!!! error TS9000: 'yield' expressions are not currently supported. - } \ No newline at end of file diff --git a/tests/baselines/reference/generatorES6_3.symbols b/tests/baselines/reference/generatorES6_3.symbols new file mode 100644 index 00000000000..329c96e6de8 --- /dev/null +++ b/tests/baselines/reference/generatorES6_3.symbols @@ -0,0 +1,6 @@ +=== tests/cases/compiler/generatorES6_3.ts === +var v = function*() { +>v : Symbol(v, Decl(generatorES6_3.ts, 0, 3)) + + yield 0 +} diff --git a/tests/baselines/reference/generatorES6_3.types b/tests/baselines/reference/generatorES6_3.types new file mode 100644 index 00000000000..e87ad23ba77 --- /dev/null +++ b/tests/baselines/reference/generatorES6_3.types @@ -0,0 +1,9 @@ +=== tests/cases/compiler/generatorES6_3.ts === +var v = function*() { +>v : () => IterableIterator +>function*() { yield 0} : () => IterableIterator + + yield 0 +>yield 0 : any +>0 : number +} diff --git a/tests/baselines/reference/generatorES6_4.errors.txt b/tests/baselines/reference/generatorES6_4.errors.txt deleted file mode 100644 index 37c375e9728..00000000000 --- a/tests/baselines/reference/generatorES6_4.errors.txt +++ /dev/null @@ -1,14 +0,0 @@ -tests/cases/compiler/generatorES6_4.ts(2,4): error TS9001: Generators are not currently supported. -tests/cases/compiler/generatorES6_4.ts(3,8): error TS9000: 'yield' expressions are not currently supported. - - -==== tests/cases/compiler/generatorES6_4.ts (2 errors) ==== - var v = { - *foo() { - ~ -!!! error TS9001: Generators are not currently supported. - yield 0 - ~~~~~ -!!! error TS9000: 'yield' expressions are not currently supported. - } - } \ No newline at end of file diff --git a/tests/baselines/reference/generatorES6_4.symbols b/tests/baselines/reference/generatorES6_4.symbols new file mode 100644 index 00000000000..fc514dad45f --- /dev/null +++ b/tests/baselines/reference/generatorES6_4.symbols @@ -0,0 +1,10 @@ +=== tests/cases/compiler/generatorES6_4.ts === +var v = { +>v : Symbol(v, Decl(generatorES6_4.ts, 0, 3)) + + *foo() { +>foo : Symbol(foo, Decl(generatorES6_4.ts, 0, 9)) + + yield 0 + } +} diff --git a/tests/baselines/reference/generatorES6_4.types b/tests/baselines/reference/generatorES6_4.types new file mode 100644 index 00000000000..64b0924919b --- /dev/null +++ b/tests/baselines/reference/generatorES6_4.types @@ -0,0 +1,13 @@ +=== tests/cases/compiler/generatorES6_4.ts === +var v = { +>v : { foo(): IterableIterator; } +>{ *foo() { yield 0 }} : { foo(): IterableIterator; } + + *foo() { +>foo : () => IterableIterator + + yield 0 +>yield 0 : any +>0 : number + } +} diff --git a/tests/baselines/reference/generatorES6_5.errors.txt b/tests/baselines/reference/generatorES6_5.errors.txt index f6fa8a5bc18..20e6f3abe9f 100644 --- a/tests/baselines/reference/generatorES6_5.errors.txt +++ b/tests/baselines/reference/generatorES6_5.errors.txt @@ -1,12 +1,15 @@ -tests/cases/compiler/generatorES6_5.ts(1,9): error TS9001: Generators are not currently supported. -tests/cases/compiler/generatorES6_5.ts(2,5): error TS9000: 'yield' expressions are not currently supported. +tests/cases/compiler/generatorES6_5.ts(2,11): error TS2304: Cannot find name 'a'. +tests/cases/compiler/generatorES6_5.ts(2,15): error TS2304: Cannot find name 'b'. +tests/cases/compiler/generatorES6_5.ts(2,19): error TS2304: Cannot find name 'c'. -==== tests/cases/compiler/generatorES6_5.ts (2 errors) ==== +==== tests/cases/compiler/generatorES6_5.ts (3 errors) ==== function* foo() { - ~ -!!! error TS9001: Generators are not currently supported. yield a ? b : c; - ~~~~~ -!!! error TS9000: 'yield' expressions are not currently supported. + ~ +!!! error TS2304: Cannot find name 'a'. + ~ +!!! error TS2304: Cannot find name 'b'. + ~ +!!! error TS2304: Cannot find name 'c'. } \ No newline at end of file diff --git a/tests/baselines/reference/generatorES6_6.errors.txt b/tests/baselines/reference/generatorES6_6.errors.txt deleted file mode 100644 index 1f568aeb9e4..00000000000 --- a/tests/baselines/reference/generatorES6_6.errors.txt +++ /dev/null @@ -1,14 +0,0 @@ -tests/cases/compiler/generatorES6_6.ts(2,3): error TS9001: Generators are not currently supported. -tests/cases/compiler/generatorES6_6.ts(3,13): error TS9000: 'yield' expressions are not currently supported. - - -==== tests/cases/compiler/generatorES6_6.ts (2 errors) ==== - class C { - *[Symbol.iterator]() { - ~ -!!! error TS9001: Generators are not currently supported. - let a = yield 1; - ~~~~~ -!!! error TS9000: 'yield' expressions are not currently supported. - } - } \ No newline at end of file diff --git a/tests/baselines/reference/generatorES6_6.symbols b/tests/baselines/reference/generatorES6_6.symbols new file mode 100644 index 00000000000..4cdac0f12c5 --- /dev/null +++ b/tests/baselines/reference/generatorES6_6.symbols @@ -0,0 +1,13 @@ +=== tests/cases/compiler/generatorES6_6.ts === +class C { +>C : Symbol(C, Decl(generatorES6_6.ts, 0, 0)) + + *[Symbol.iterator]() { +>Symbol.iterator : Symbol(SymbolConstructor.iterator, Decl(lib.d.ts, 1236, 31)) +>Symbol : Symbol(Symbol, Decl(lib.d.ts, 1186, 52), Decl(lib.d.ts, 1292, 11)) +>iterator : Symbol(SymbolConstructor.iterator, Decl(lib.d.ts, 1236, 31)) + + let a = yield 1; +>a : Symbol(a, Decl(generatorES6_6.ts, 2, 7)) + } +} diff --git a/tests/baselines/reference/generatorES6_6.types b/tests/baselines/reference/generatorES6_6.types new file mode 100644 index 00000000000..4e3de8cea1e --- /dev/null +++ b/tests/baselines/reference/generatorES6_6.types @@ -0,0 +1,15 @@ +=== tests/cases/compiler/generatorES6_6.ts === +class C { +>C : C + + *[Symbol.iterator]() { +>Symbol.iterator : symbol +>Symbol : SymbolConstructor +>iterator : symbol + + let a = yield 1; +>a : any +>yield 1 : any +>1 : number + } +} diff --git a/tests/baselines/reference/generatorInAmbientContext1.errors.txt b/tests/baselines/reference/generatorInAmbientContext1.errors.txt new file mode 100644 index 00000000000..f3e458e80ca --- /dev/null +++ b/tests/baselines/reference/generatorInAmbientContext1.errors.txt @@ -0,0 +1,9 @@ +tests/cases/conformance/es6/yieldExpressions/generatorInAmbientContext1.ts(2,5): error TS1221: Generators are not allowed in an ambient context. + + +==== tests/cases/conformance/es6/yieldExpressions/generatorInAmbientContext1.ts (1 errors) ==== + declare class C { + *generator(): any; + ~ +!!! error TS1221: Generators are not allowed in an ambient context. + } \ No newline at end of file diff --git a/tests/baselines/reference/generatorInAmbientContext1.js b/tests/baselines/reference/generatorInAmbientContext1.js new file mode 100644 index 00000000000..e7b4e03e64e --- /dev/null +++ b/tests/baselines/reference/generatorInAmbientContext1.js @@ -0,0 +1,6 @@ +//// [generatorInAmbientContext1.ts] +declare class C { + *generator(): any; +} + +//// [generatorInAmbientContext1.js] diff --git a/tests/baselines/reference/generatorInAmbientContext2.errors.txt b/tests/baselines/reference/generatorInAmbientContext2.errors.txt new file mode 100644 index 00000000000..d6cd02f72ef --- /dev/null +++ b/tests/baselines/reference/generatorInAmbientContext2.errors.txt @@ -0,0 +1,9 @@ +tests/cases/conformance/es6/yieldExpressions/generatorInAmbientContext2.ts(2,14): error TS1221: Generators are not allowed in an ambient context. + + +==== tests/cases/conformance/es6/yieldExpressions/generatorInAmbientContext2.ts (1 errors) ==== + declare module M { + function *generator(): any; + ~ +!!! error TS1221: Generators are not allowed in an ambient context. + } \ No newline at end of file diff --git a/tests/baselines/reference/generatorInAmbientContext2.js b/tests/baselines/reference/generatorInAmbientContext2.js new file mode 100644 index 00000000000..f7742ccc235 --- /dev/null +++ b/tests/baselines/reference/generatorInAmbientContext2.js @@ -0,0 +1,6 @@ +//// [generatorInAmbientContext2.ts] +declare module M { + function *generator(): any; +} + +//// [generatorInAmbientContext2.js] diff --git a/tests/baselines/reference/generatorInAmbientContext3.d.errors.txt b/tests/baselines/reference/generatorInAmbientContext3.d.errors.txt new file mode 100644 index 00000000000..d53591ef80c --- /dev/null +++ b/tests/baselines/reference/generatorInAmbientContext3.d.errors.txt @@ -0,0 +1,9 @@ +tests/cases/conformance/es6/yieldExpressions/generatorInAmbientContext3.d.ts(2,5): error TS1221: Generators are not allowed in an ambient context. + + +==== tests/cases/conformance/es6/yieldExpressions/generatorInAmbientContext3.d.ts (1 errors) ==== + declare class C { + *generator(): any; + ~ +!!! error TS1221: Generators are not allowed in an ambient context. + } \ No newline at end of file diff --git a/tests/baselines/reference/generatorInAmbientContext4.d.errors.txt b/tests/baselines/reference/generatorInAmbientContext4.d.errors.txt new file mode 100644 index 00000000000..171ad2e6647 --- /dev/null +++ b/tests/baselines/reference/generatorInAmbientContext4.d.errors.txt @@ -0,0 +1,9 @@ +tests/cases/conformance/es6/yieldExpressions/generatorInAmbientContext4.d.ts(2,14): error TS1221: Generators are not allowed in an ambient context. + + +==== tests/cases/conformance/es6/yieldExpressions/generatorInAmbientContext4.d.ts (1 errors) ==== + declare module M { + function *generator(): any; + ~ +!!! error TS1221: Generators are not allowed in an ambient context. + } \ No newline at end of file diff --git a/tests/baselines/reference/generatorInAmbientContext5.js b/tests/baselines/reference/generatorInAmbientContext5.js new file mode 100644 index 00000000000..044155e8dd5 --- /dev/null +++ b/tests/baselines/reference/generatorInAmbientContext5.js @@ -0,0 +1,15 @@ +//// [generatorInAmbientContext5.ts] +class C { + *generator(): any { } +} + +//// [generatorInAmbientContext5.js] +class C { + *generator() { } +} + + +//// [generatorInAmbientContext5.d.ts] +declare class C { + generator(): any; +} diff --git a/tests/baselines/reference/generatorInAmbientContext5.symbols b/tests/baselines/reference/generatorInAmbientContext5.symbols new file mode 100644 index 00000000000..78139a7e597 --- /dev/null +++ b/tests/baselines/reference/generatorInAmbientContext5.symbols @@ -0,0 +1,7 @@ +=== tests/cases/conformance/es6/yieldExpressions/generatorInAmbientContext5.ts === +class C { +>C : Symbol(C, Decl(generatorInAmbientContext5.ts, 0, 0)) + + *generator(): any { } +>generator : Symbol(generator, Decl(generatorInAmbientContext5.ts, 0, 9)) +} diff --git a/tests/baselines/reference/generatorInAmbientContext5.types b/tests/baselines/reference/generatorInAmbientContext5.types new file mode 100644 index 00000000000..169aba8201b --- /dev/null +++ b/tests/baselines/reference/generatorInAmbientContext5.types @@ -0,0 +1,7 @@ +=== tests/cases/conformance/es6/yieldExpressions/generatorInAmbientContext5.ts === +class C { +>C : C + + *generator(): any { } +>generator : () => any +} diff --git a/tests/baselines/reference/generatorInAmbientContext6.js b/tests/baselines/reference/generatorInAmbientContext6.js new file mode 100644 index 00000000000..10cfa85d933 --- /dev/null +++ b/tests/baselines/reference/generatorInAmbientContext6.js @@ -0,0 +1,17 @@ +//// [generatorInAmbientContext6.ts] +module M { + export function *generator(): any { } +} + +//// [generatorInAmbientContext6.js] +var M; +(function (M) { + function* generator() { } + M.generator = generator; +})(M || (M = {})); + + +//// [generatorInAmbientContext6.d.ts] +declare module M { + function generator(): any; +} diff --git a/tests/baselines/reference/generatorInAmbientContext6.symbols b/tests/baselines/reference/generatorInAmbientContext6.symbols new file mode 100644 index 00000000000..e921a2b1f96 --- /dev/null +++ b/tests/baselines/reference/generatorInAmbientContext6.symbols @@ -0,0 +1,7 @@ +=== tests/cases/conformance/es6/yieldExpressions/generatorInAmbientContext6.ts === +module M { +>M : Symbol(M, Decl(generatorInAmbientContext6.ts, 0, 0)) + + export function *generator(): any { } +>generator : Symbol(generator, Decl(generatorInAmbientContext6.ts, 0, 10)) +} diff --git a/tests/baselines/reference/generatorInAmbientContext6.types b/tests/baselines/reference/generatorInAmbientContext6.types new file mode 100644 index 00000000000..d960126210e --- /dev/null +++ b/tests/baselines/reference/generatorInAmbientContext6.types @@ -0,0 +1,7 @@ +=== tests/cases/conformance/es6/yieldExpressions/generatorInAmbientContext6.ts === +module M { +>M : typeof M + + export function *generator(): any { } +>generator : () => any +} diff --git a/tests/baselines/reference/generatorOverloads1.errors.txt b/tests/baselines/reference/generatorOverloads1.errors.txt new file mode 100644 index 00000000000..280ca7c516b --- /dev/null +++ b/tests/baselines/reference/generatorOverloads1.errors.txt @@ -0,0 +1,14 @@ +tests/cases/conformance/es6/yieldExpressions/generatorOverloads1.ts(2,13): error TS1222: An overload signature cannot be declared as a generator. +tests/cases/conformance/es6/yieldExpressions/generatorOverloads1.ts(3,13): error TS1222: An overload signature cannot be declared as a generator. + + +==== tests/cases/conformance/es6/yieldExpressions/generatorOverloads1.ts (2 errors) ==== + module M { + function* f(s: string): Iterable; + ~ +!!! error TS1222: An overload signature cannot be declared as a generator. + function* f(s: number): Iterable; + ~ +!!! error TS1222: An overload signature cannot be declared as a generator. + function* f(s: any): Iterable { } + } \ No newline at end of file diff --git a/tests/baselines/reference/generatorOverloads1.js b/tests/baselines/reference/generatorOverloads1.js new file mode 100644 index 00000000000..0ce5ae10f4d --- /dev/null +++ b/tests/baselines/reference/generatorOverloads1.js @@ -0,0 +1,12 @@ +//// [generatorOverloads1.ts] +module M { + function* f(s: string): Iterable; + function* f(s: number): Iterable; + function* f(s: any): Iterable { } +} + +//// [generatorOverloads1.js] +var M; +(function (M) { + function* f(s) { } +})(M || (M = {})); diff --git a/tests/baselines/reference/generatorOverloads2.errors.txt b/tests/baselines/reference/generatorOverloads2.errors.txt new file mode 100644 index 00000000000..349b9382eb1 --- /dev/null +++ b/tests/baselines/reference/generatorOverloads2.errors.txt @@ -0,0 +1,17 @@ +tests/cases/conformance/es6/yieldExpressions/generatorOverloads2.ts(2,13): error TS1221: Generators are not allowed in an ambient context. +tests/cases/conformance/es6/yieldExpressions/generatorOverloads2.ts(3,13): error TS1221: Generators are not allowed in an ambient context. +tests/cases/conformance/es6/yieldExpressions/generatorOverloads2.ts(4,13): error TS1221: Generators are not allowed in an ambient context. + + +==== tests/cases/conformance/es6/yieldExpressions/generatorOverloads2.ts (3 errors) ==== + declare module M { + function* f(s: string): Iterable; + ~ +!!! error TS1221: Generators are not allowed in an ambient context. + function* f(s: number): Iterable; + ~ +!!! error TS1221: Generators are not allowed in an ambient context. + function* f(s: any): Iterable; + ~ +!!! error TS1221: Generators are not allowed in an ambient context. + } \ No newline at end of file diff --git a/tests/baselines/reference/generatorOverloads2.js b/tests/baselines/reference/generatorOverloads2.js new file mode 100644 index 00000000000..4fa3837ed36 --- /dev/null +++ b/tests/baselines/reference/generatorOverloads2.js @@ -0,0 +1,8 @@ +//// [generatorOverloads2.ts] +declare module M { + function* f(s: string): Iterable; + function* f(s: number): Iterable; + function* f(s: any): Iterable; +} + +//// [generatorOverloads2.js] diff --git a/tests/baselines/reference/generatorOverloads3.errors.txt b/tests/baselines/reference/generatorOverloads3.errors.txt new file mode 100644 index 00000000000..d7ef5da20ec --- /dev/null +++ b/tests/baselines/reference/generatorOverloads3.errors.txt @@ -0,0 +1,14 @@ +tests/cases/conformance/es6/yieldExpressions/generatorOverloads3.ts(2,5): error TS1222: An overload signature cannot be declared as a generator. +tests/cases/conformance/es6/yieldExpressions/generatorOverloads3.ts(3,5): error TS1222: An overload signature cannot be declared as a generator. + + +==== tests/cases/conformance/es6/yieldExpressions/generatorOverloads3.ts (2 errors) ==== + class C { + *f(s: string): Iterable; + ~ +!!! error TS1222: An overload signature cannot be declared as a generator. + *f(s: number): Iterable; + ~ +!!! error TS1222: An overload signature cannot be declared as a generator. + *f(s: any): Iterable { } + } \ No newline at end of file diff --git a/tests/baselines/reference/generatorOverloads3.js b/tests/baselines/reference/generatorOverloads3.js new file mode 100644 index 00000000000..55ba5dcdc99 --- /dev/null +++ b/tests/baselines/reference/generatorOverloads3.js @@ -0,0 +1,11 @@ +//// [generatorOverloads3.ts] +class C { + *f(s: string): Iterable; + *f(s: number): Iterable; + *f(s: any): Iterable { } +} + +//// [generatorOverloads3.js] +class C { + *f(s) { } +} diff --git a/tests/baselines/reference/generatorOverloads4.js b/tests/baselines/reference/generatorOverloads4.js new file mode 100644 index 00000000000..8ebbcb59381 --- /dev/null +++ b/tests/baselines/reference/generatorOverloads4.js @@ -0,0 +1,11 @@ +//// [generatorOverloads4.ts] +class C { + f(s: string): Iterable; + f(s: number): Iterable; + *f(s: any): Iterable { } +} + +//// [generatorOverloads4.js] +class C { + *f(s) { } +} diff --git a/tests/baselines/reference/generatorOverloads4.symbols b/tests/baselines/reference/generatorOverloads4.symbols new file mode 100644 index 00000000000..afae1c1a808 --- /dev/null +++ b/tests/baselines/reference/generatorOverloads4.symbols @@ -0,0 +1,19 @@ +=== tests/cases/conformance/es6/yieldExpressions/generatorOverloads4.ts === +class C { +>C : Symbol(C, Decl(generatorOverloads4.ts, 0, 0)) + + f(s: string): Iterable; +>f : Symbol(f, Decl(generatorOverloads4.ts, 0, 9), Decl(generatorOverloads4.ts, 1, 32), Decl(generatorOverloads4.ts, 2, 32)) +>s : Symbol(s, Decl(generatorOverloads4.ts, 1, 6)) +>Iterable : Symbol(Iterable, Decl(lib.d.ts, 1668, 1)) + + f(s: number): Iterable; +>f : Symbol(f, Decl(generatorOverloads4.ts, 0, 9), Decl(generatorOverloads4.ts, 1, 32), Decl(generatorOverloads4.ts, 2, 32)) +>s : Symbol(s, Decl(generatorOverloads4.ts, 2, 6)) +>Iterable : Symbol(Iterable, Decl(lib.d.ts, 1668, 1)) + + *f(s: any): Iterable { } +>f : Symbol(f, Decl(generatorOverloads4.ts, 0, 9), Decl(generatorOverloads4.ts, 1, 32), Decl(generatorOverloads4.ts, 2, 32)) +>s : Symbol(s, Decl(generatorOverloads4.ts, 3, 7)) +>Iterable : Symbol(Iterable, Decl(lib.d.ts, 1668, 1)) +} diff --git a/tests/baselines/reference/generatorOverloads4.types b/tests/baselines/reference/generatorOverloads4.types new file mode 100644 index 00000000000..493e0ac307c --- /dev/null +++ b/tests/baselines/reference/generatorOverloads4.types @@ -0,0 +1,19 @@ +=== tests/cases/conformance/es6/yieldExpressions/generatorOverloads4.ts === +class C { +>C : C + + f(s: string): Iterable; +>f : { (s: string): Iterable; (s: number): Iterable; } +>s : string +>Iterable : Iterable + + f(s: number): Iterable; +>f : { (s: string): Iterable; (s: number): Iterable; } +>s : number +>Iterable : Iterable + + *f(s: any): Iterable { } +>f : { (s: string): Iterable; (s: number): Iterable; } +>s : any +>Iterable : Iterable +} diff --git a/tests/baselines/reference/generatorOverloads5.js b/tests/baselines/reference/generatorOverloads5.js new file mode 100644 index 00000000000..c6d928045fa --- /dev/null +++ b/tests/baselines/reference/generatorOverloads5.js @@ -0,0 +1,12 @@ +//// [generatorOverloads5.ts] +module M { + function f(s: string): Iterable; + function f(s: number): Iterable; + function* f(s: any): Iterable { } +} + +//// [generatorOverloads5.js] +var M; +(function (M) { + function* f(s) { } +})(M || (M = {})); diff --git a/tests/baselines/reference/generatorOverloads5.symbols b/tests/baselines/reference/generatorOverloads5.symbols new file mode 100644 index 00000000000..0a14548d197 --- /dev/null +++ b/tests/baselines/reference/generatorOverloads5.symbols @@ -0,0 +1,19 @@ +=== tests/cases/conformance/es6/yieldExpressions/generatorOverloads5.ts === +module M { +>M : Symbol(M, Decl(generatorOverloads5.ts, 0, 0)) + + function f(s: string): Iterable; +>f : Symbol(f, Decl(generatorOverloads5.ts, 0, 10), Decl(generatorOverloads5.ts, 1, 41), Decl(generatorOverloads5.ts, 2, 41)) +>s : Symbol(s, Decl(generatorOverloads5.ts, 1, 15)) +>Iterable : Symbol(Iterable, Decl(lib.d.ts, 1668, 1)) + + function f(s: number): Iterable; +>f : Symbol(f, Decl(generatorOverloads5.ts, 0, 10), Decl(generatorOverloads5.ts, 1, 41), Decl(generatorOverloads5.ts, 2, 41)) +>s : Symbol(s, Decl(generatorOverloads5.ts, 2, 15)) +>Iterable : Symbol(Iterable, Decl(lib.d.ts, 1668, 1)) + + function* f(s: any): Iterable { } +>f : Symbol(f, Decl(generatorOverloads5.ts, 0, 10), Decl(generatorOverloads5.ts, 1, 41), Decl(generatorOverloads5.ts, 2, 41)) +>s : Symbol(s, Decl(generatorOverloads5.ts, 3, 16)) +>Iterable : Symbol(Iterable, Decl(lib.d.ts, 1668, 1)) +} diff --git a/tests/baselines/reference/generatorOverloads5.types b/tests/baselines/reference/generatorOverloads5.types new file mode 100644 index 00000000000..276baf1ff40 --- /dev/null +++ b/tests/baselines/reference/generatorOverloads5.types @@ -0,0 +1,19 @@ +=== tests/cases/conformance/es6/yieldExpressions/generatorOverloads5.ts === +module M { +>M : typeof M + + function f(s: string): Iterable; +>f : { (s: string): Iterable; (s: number): Iterable; } +>s : string +>Iterable : Iterable + + function f(s: number): Iterable; +>f : { (s: string): Iterable; (s: number): Iterable; } +>s : number +>Iterable : Iterable + + function* f(s: any): Iterable { } +>f : { (s: string): Iterable; (s: number): Iterable; } +>s : any +>Iterable : Iterable +} diff --git a/tests/baselines/reference/generatorTypeCheck1.js b/tests/baselines/reference/generatorTypeCheck1.js new file mode 100644 index 00000000000..eb3cbcd2fe0 --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck1.js @@ -0,0 +1,5 @@ +//// [generatorTypeCheck1.ts] +function* g1(): Iterator { } + +//// [generatorTypeCheck1.js] +function* g1() { } diff --git a/tests/baselines/reference/generatorTypeCheck1.symbols b/tests/baselines/reference/generatorTypeCheck1.symbols new file mode 100644 index 00000000000..58ee2aa66f8 --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck1.symbols @@ -0,0 +1,5 @@ +=== tests/cases/conformance/es6/yieldExpressions/generatorTypeCheck1.ts === +function* g1(): Iterator { } +>g1 : Symbol(g1, Decl(generatorTypeCheck1.ts, 0, 0)) +>Iterator : Symbol(Iterator, Decl(lib.d.ts, 1662, 1)) + diff --git a/tests/baselines/reference/generatorTypeCheck1.types b/tests/baselines/reference/generatorTypeCheck1.types new file mode 100644 index 00000000000..3f02fe4b095 --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck1.types @@ -0,0 +1,5 @@ +=== tests/cases/conformance/es6/yieldExpressions/generatorTypeCheck1.ts === +function* g1(): Iterator { } +>g1 : () => Iterator +>Iterator : Iterator + diff --git a/tests/baselines/reference/generatorTypeCheck10.js b/tests/baselines/reference/generatorTypeCheck10.js new file mode 100644 index 00000000000..252f3011613 --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck10.js @@ -0,0 +1,9 @@ +//// [generatorTypeCheck10.ts] +function* g(): IterableIterator { + return; +} + +//// [generatorTypeCheck10.js] +function* g() { + return; +} diff --git a/tests/baselines/reference/generatorTypeCheck10.symbols b/tests/baselines/reference/generatorTypeCheck10.symbols new file mode 100644 index 00000000000..c6eeb6b4a3d --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck10.symbols @@ -0,0 +1,7 @@ +=== tests/cases/conformance/es6/yieldExpressions/generatorTypeCheck10.ts === +function* g(): IterableIterator { +>g : Symbol(g, Decl(generatorTypeCheck10.ts, 0, 0)) +>IterableIterator : Symbol(IterableIterator, Decl(lib.d.ts, 1672, 1)) + + return; +} diff --git a/tests/baselines/reference/generatorTypeCheck10.types b/tests/baselines/reference/generatorTypeCheck10.types new file mode 100644 index 00000000000..f9304e3b168 --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck10.types @@ -0,0 +1,7 @@ +=== tests/cases/conformance/es6/yieldExpressions/generatorTypeCheck10.ts === +function* g(): IterableIterator { +>g : () => IterableIterator +>IterableIterator : IterableIterator + + return; +} diff --git a/tests/baselines/reference/generatorTypeCheck11.js b/tests/baselines/reference/generatorTypeCheck11.js new file mode 100644 index 00000000000..4898f661f26 --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck11.js @@ -0,0 +1,9 @@ +//// [generatorTypeCheck11.ts] +function* g(): IterableIterator { + return 0; +} + +//// [generatorTypeCheck11.js] +function* g() { + return 0; +} diff --git a/tests/baselines/reference/generatorTypeCheck11.symbols b/tests/baselines/reference/generatorTypeCheck11.symbols new file mode 100644 index 00000000000..b904dfb446b --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck11.symbols @@ -0,0 +1,7 @@ +=== tests/cases/conformance/es6/yieldExpressions/generatorTypeCheck11.ts === +function* g(): IterableIterator { +>g : Symbol(g, Decl(generatorTypeCheck11.ts, 0, 0)) +>IterableIterator : Symbol(IterableIterator, Decl(lib.d.ts, 1672, 1)) + + return 0; +} diff --git a/tests/baselines/reference/generatorTypeCheck11.types b/tests/baselines/reference/generatorTypeCheck11.types new file mode 100644 index 00000000000..ce47d497851 --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck11.types @@ -0,0 +1,8 @@ +=== tests/cases/conformance/es6/yieldExpressions/generatorTypeCheck11.ts === +function* g(): IterableIterator { +>g : () => IterableIterator +>IterableIterator : IterableIterator + + return 0; +>0 : number +} diff --git a/tests/baselines/reference/generatorTypeCheck12.js b/tests/baselines/reference/generatorTypeCheck12.js new file mode 100644 index 00000000000..058b0a0772d --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck12.js @@ -0,0 +1,9 @@ +//// [generatorTypeCheck12.ts] +function* g(): IterableIterator { + return ""; +} + +//// [generatorTypeCheck12.js] +function* g() { + return ""; +} diff --git a/tests/baselines/reference/generatorTypeCheck12.symbols b/tests/baselines/reference/generatorTypeCheck12.symbols new file mode 100644 index 00000000000..e596203b9eb --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck12.symbols @@ -0,0 +1,7 @@ +=== tests/cases/conformance/es6/yieldExpressions/generatorTypeCheck12.ts === +function* g(): IterableIterator { +>g : Symbol(g, Decl(generatorTypeCheck12.ts, 0, 0)) +>IterableIterator : Symbol(IterableIterator, Decl(lib.d.ts, 1672, 1)) + + return ""; +} diff --git a/tests/baselines/reference/generatorTypeCheck12.types b/tests/baselines/reference/generatorTypeCheck12.types new file mode 100644 index 00000000000..3dd3c20f18d --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck12.types @@ -0,0 +1,8 @@ +=== tests/cases/conformance/es6/yieldExpressions/generatorTypeCheck12.ts === +function* g(): IterableIterator { +>g : () => IterableIterator +>IterableIterator : IterableIterator + + return ""; +>"" : string +} diff --git a/tests/baselines/reference/generatorTypeCheck13.js b/tests/baselines/reference/generatorTypeCheck13.js new file mode 100644 index 00000000000..26308b0ac7e --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck13.js @@ -0,0 +1,11 @@ +//// [generatorTypeCheck13.ts] +function* g(): IterableIterator { + yield 0; + return ""; +} + +//// [generatorTypeCheck13.js] +function* g() { + yield 0; + return ""; +} diff --git a/tests/baselines/reference/generatorTypeCheck13.symbols b/tests/baselines/reference/generatorTypeCheck13.symbols new file mode 100644 index 00000000000..84e42a06cfd --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck13.symbols @@ -0,0 +1,8 @@ +=== tests/cases/conformance/es6/yieldExpressions/generatorTypeCheck13.ts === +function* g(): IterableIterator { +>g : Symbol(g, Decl(generatorTypeCheck13.ts, 0, 0)) +>IterableIterator : Symbol(IterableIterator, Decl(lib.d.ts, 1672, 1)) + + yield 0; + return ""; +} diff --git a/tests/baselines/reference/generatorTypeCheck13.types b/tests/baselines/reference/generatorTypeCheck13.types new file mode 100644 index 00000000000..d77b630ae72 --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck13.types @@ -0,0 +1,12 @@ +=== tests/cases/conformance/es6/yieldExpressions/generatorTypeCheck13.ts === +function* g(): IterableIterator { +>g : () => IterableIterator +>IterableIterator : IterableIterator + + yield 0; +>yield 0 : any +>0 : number + + return ""; +>"" : string +} diff --git a/tests/baselines/reference/generatorTypeCheck14.js b/tests/baselines/reference/generatorTypeCheck14.js new file mode 100644 index 00000000000..a7dcc87a3a9 --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck14.js @@ -0,0 +1,11 @@ +//// [generatorTypeCheck14.ts] +function* g() { + yield 0; + return ""; +} + +//// [generatorTypeCheck14.js] +function* g() { + yield 0; + return ""; +} diff --git a/tests/baselines/reference/generatorTypeCheck14.symbols b/tests/baselines/reference/generatorTypeCheck14.symbols new file mode 100644 index 00000000000..36d10d88545 --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck14.symbols @@ -0,0 +1,7 @@ +=== tests/cases/conformance/es6/yieldExpressions/generatorTypeCheck14.ts === +function* g() { +>g : Symbol(g, Decl(generatorTypeCheck14.ts, 0, 0)) + + yield 0; + return ""; +} diff --git a/tests/baselines/reference/generatorTypeCheck14.types b/tests/baselines/reference/generatorTypeCheck14.types new file mode 100644 index 00000000000..db1b5bde19a --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck14.types @@ -0,0 +1,11 @@ +=== tests/cases/conformance/es6/yieldExpressions/generatorTypeCheck14.ts === +function* g() { +>g : () => IterableIterator + + yield 0; +>yield 0 : any +>0 : number + + return ""; +>"" : string +} diff --git a/tests/baselines/reference/generatorTypeCheck15.js b/tests/baselines/reference/generatorTypeCheck15.js new file mode 100644 index 00000000000..d359c100486 --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck15.js @@ -0,0 +1,9 @@ +//// [generatorTypeCheck15.ts] +function* g() { + return ""; +} + +//// [generatorTypeCheck15.js] +function* g() { + return ""; +} diff --git a/tests/baselines/reference/generatorTypeCheck15.symbols b/tests/baselines/reference/generatorTypeCheck15.symbols new file mode 100644 index 00000000000..3d914d0bd6f --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck15.symbols @@ -0,0 +1,6 @@ +=== tests/cases/conformance/es6/yieldExpressions/generatorTypeCheck15.ts === +function* g() { +>g : Symbol(g, Decl(generatorTypeCheck15.ts, 0, 0)) + + return ""; +} diff --git a/tests/baselines/reference/generatorTypeCheck15.types b/tests/baselines/reference/generatorTypeCheck15.types new file mode 100644 index 00000000000..4437d78572d --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck15.types @@ -0,0 +1,7 @@ +=== tests/cases/conformance/es6/yieldExpressions/generatorTypeCheck15.ts === +function* g() { +>g : () => IterableIterator + + return ""; +>"" : string +} diff --git a/tests/baselines/reference/generatorTypeCheck16.js b/tests/baselines/reference/generatorTypeCheck16.js new file mode 100644 index 00000000000..7b8b93deabd --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck16.js @@ -0,0 +1,9 @@ +//// [generatorTypeCheck16.ts] +function* g() { + return; +} + +//// [generatorTypeCheck16.js] +function* g() { + return; +} diff --git a/tests/baselines/reference/generatorTypeCheck16.symbols b/tests/baselines/reference/generatorTypeCheck16.symbols new file mode 100644 index 00000000000..bbc22cc4a2d --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck16.symbols @@ -0,0 +1,6 @@ +=== tests/cases/conformance/es6/yieldExpressions/generatorTypeCheck16.ts === +function* g() { +>g : Symbol(g, Decl(generatorTypeCheck16.ts, 0, 0)) + + return; +} diff --git a/tests/baselines/reference/generatorTypeCheck16.types b/tests/baselines/reference/generatorTypeCheck16.types new file mode 100644 index 00000000000..a607ad851c1 --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck16.types @@ -0,0 +1,6 @@ +=== tests/cases/conformance/es6/yieldExpressions/generatorTypeCheck16.ts === +function* g() { +>g : () => IterableIterator + + return; +} diff --git a/tests/baselines/reference/generatorTypeCheck17.js b/tests/baselines/reference/generatorTypeCheck17.js new file mode 100644 index 00000000000..8c3ebb59ea6 --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck17.js @@ -0,0 +1,17 @@ +//// [generatorTypeCheck17.ts] +class Foo { x: number } +class Bar extends Foo { y: string } +function* g(): IterableIterator { + yield; + yield new Bar; +} + +//// [generatorTypeCheck17.js] +class Foo { +} +class Bar extends Foo { +} +function* g() { + yield; + yield new Bar; +} diff --git a/tests/baselines/reference/generatorTypeCheck17.symbols b/tests/baselines/reference/generatorTypeCheck17.symbols new file mode 100644 index 00000000000..9e689d9df42 --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck17.symbols @@ -0,0 +1,19 @@ +=== tests/cases/conformance/es6/yieldExpressions/generatorTypeCheck17.ts === +class Foo { x: number } +>Foo : Symbol(Foo, Decl(generatorTypeCheck17.ts, 0, 0)) +>x : Symbol(x, Decl(generatorTypeCheck17.ts, 0, 11)) + +class Bar extends Foo { y: string } +>Bar : Symbol(Bar, Decl(generatorTypeCheck17.ts, 0, 23)) +>Foo : Symbol(Foo, Decl(generatorTypeCheck17.ts, 0, 0)) +>y : Symbol(y, Decl(generatorTypeCheck17.ts, 1, 23)) + +function* g(): IterableIterator { +>g : Symbol(g, Decl(generatorTypeCheck17.ts, 1, 35)) +>IterableIterator : Symbol(IterableIterator, Decl(lib.d.ts, 1672, 1)) +>Foo : Symbol(Foo, Decl(generatorTypeCheck17.ts, 0, 0)) + + yield; + yield new Bar; +>Bar : Symbol(Bar, Decl(generatorTypeCheck17.ts, 0, 23)) +} diff --git a/tests/baselines/reference/generatorTypeCheck17.types b/tests/baselines/reference/generatorTypeCheck17.types new file mode 100644 index 00000000000..0ea7212040b --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck17.types @@ -0,0 +1,23 @@ +=== tests/cases/conformance/es6/yieldExpressions/generatorTypeCheck17.ts === +class Foo { x: number } +>Foo : Foo +>x : number + +class Bar extends Foo { y: string } +>Bar : Bar +>Foo : Foo +>y : string + +function* g(): IterableIterator { +>g : () => IterableIterator +>IterableIterator : IterableIterator +>Foo : Foo + + yield; +>yield : any + + yield new Bar; +>yield new Bar : any +>new Bar : Bar +>Bar : typeof Bar +} diff --git a/tests/baselines/reference/generatorTypeCheck18.errors.txt b/tests/baselines/reference/generatorTypeCheck18.errors.txt new file mode 100644 index 00000000000..2c6deab9821 --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck18.errors.txt @@ -0,0 +1,14 @@ +tests/cases/conformance/es6/yieldExpressions/generatorTypeCheck18.ts(5,11): error TS2322: Type 'Baz' is not assignable to type 'Foo'. + Property 'x' is missing in type 'Baz'. + + +==== tests/cases/conformance/es6/yieldExpressions/generatorTypeCheck18.ts (1 errors) ==== + class Foo { x: number } + class Baz { z: number } + function* g(): IterableIterator { + yield; + yield new Baz; + ~~~~~~~ +!!! error TS2322: Type 'Baz' is not assignable to type 'Foo'. +!!! error TS2322: Property 'x' is missing in type 'Baz'. + } \ No newline at end of file diff --git a/tests/baselines/reference/generatorTypeCheck18.js b/tests/baselines/reference/generatorTypeCheck18.js new file mode 100644 index 00000000000..5907dd14b29 --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck18.js @@ -0,0 +1,17 @@ +//// [generatorTypeCheck18.ts] +class Foo { x: number } +class Baz { z: number } +function* g(): IterableIterator { + yield; + yield new Baz; +} + +//// [generatorTypeCheck18.js] +class Foo { +} +class Baz { +} +function* g() { + yield; + yield new Baz; +} diff --git a/tests/baselines/reference/generatorTypeCheck19.js b/tests/baselines/reference/generatorTypeCheck19.js new file mode 100644 index 00000000000..375d7b36ecc --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck19.js @@ -0,0 +1,17 @@ +//// [generatorTypeCheck19.ts] +class Foo { x: number } +class Bar extends Foo { y: string } +function* g(): IterableIterator { + yield; + yield * [new Bar]; +} + +//// [generatorTypeCheck19.js] +class Foo { +} +class Bar extends Foo { +} +function* g() { + yield; + yield* [new Bar]; +} diff --git a/tests/baselines/reference/generatorTypeCheck19.symbols b/tests/baselines/reference/generatorTypeCheck19.symbols new file mode 100644 index 00000000000..2edec8fd21a --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck19.symbols @@ -0,0 +1,19 @@ +=== tests/cases/conformance/es6/yieldExpressions/generatorTypeCheck19.ts === +class Foo { x: number } +>Foo : Symbol(Foo, Decl(generatorTypeCheck19.ts, 0, 0)) +>x : Symbol(x, Decl(generatorTypeCheck19.ts, 0, 11)) + +class Bar extends Foo { y: string } +>Bar : Symbol(Bar, Decl(generatorTypeCheck19.ts, 0, 23)) +>Foo : Symbol(Foo, Decl(generatorTypeCheck19.ts, 0, 0)) +>y : Symbol(y, Decl(generatorTypeCheck19.ts, 1, 23)) + +function* g(): IterableIterator { +>g : Symbol(g, Decl(generatorTypeCheck19.ts, 1, 35)) +>IterableIterator : Symbol(IterableIterator, Decl(lib.d.ts, 1672, 1)) +>Foo : Symbol(Foo, Decl(generatorTypeCheck19.ts, 0, 0)) + + yield; + yield * [new Bar]; +>Bar : Symbol(Bar, Decl(generatorTypeCheck19.ts, 0, 23)) +} diff --git a/tests/baselines/reference/generatorTypeCheck19.types b/tests/baselines/reference/generatorTypeCheck19.types new file mode 100644 index 00000000000..2b4f1396c2e --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck19.types @@ -0,0 +1,24 @@ +=== tests/cases/conformance/es6/yieldExpressions/generatorTypeCheck19.ts === +class Foo { x: number } +>Foo : Foo +>x : number + +class Bar extends Foo { y: string } +>Bar : Bar +>Foo : Foo +>y : string + +function* g(): IterableIterator { +>g : () => IterableIterator +>IterableIterator : IterableIterator +>Foo : Foo + + yield; +>yield : any + + yield * [new Bar]; +>yield * [new Bar] : any +>[new Bar] : Bar[] +>new Bar : Bar +>Bar : typeof Bar +} diff --git a/tests/baselines/reference/generatorTypeCheck2.js b/tests/baselines/reference/generatorTypeCheck2.js new file mode 100644 index 00000000000..559946b0fcb --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck2.js @@ -0,0 +1,5 @@ +//// [generatorTypeCheck2.ts] +function* g1(): Iterable { } + +//// [generatorTypeCheck2.js] +function* g1() { } diff --git a/tests/baselines/reference/generatorTypeCheck2.symbols b/tests/baselines/reference/generatorTypeCheck2.symbols new file mode 100644 index 00000000000..e0668786598 --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck2.symbols @@ -0,0 +1,5 @@ +=== tests/cases/conformance/es6/yieldExpressions/generatorTypeCheck2.ts === +function* g1(): Iterable { } +>g1 : Symbol(g1, Decl(generatorTypeCheck2.ts, 0, 0)) +>Iterable : Symbol(Iterable, Decl(lib.d.ts, 1668, 1)) + diff --git a/tests/baselines/reference/generatorTypeCheck2.types b/tests/baselines/reference/generatorTypeCheck2.types new file mode 100644 index 00000000000..882367fa3d4 --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck2.types @@ -0,0 +1,5 @@ +=== tests/cases/conformance/es6/yieldExpressions/generatorTypeCheck2.ts === +function* g1(): Iterable { } +>g1 : () => Iterable +>Iterable : Iterable + diff --git a/tests/baselines/reference/generatorTypeCheck20.errors.txt b/tests/baselines/reference/generatorTypeCheck20.errors.txt new file mode 100644 index 00000000000..c6e8200d106 --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck20.errors.txt @@ -0,0 +1,14 @@ +tests/cases/conformance/es6/yieldExpressions/generatorTypeCheck20.ts(5,13): error TS2322: Type 'Baz' is not assignable to type 'Foo'. + Property 'x' is missing in type 'Baz'. + + +==== tests/cases/conformance/es6/yieldExpressions/generatorTypeCheck20.ts (1 errors) ==== + class Foo { x: number } + class Baz { z: number } + function* g(): IterableIterator { + yield; + yield * [new Baz]; + ~~~~~~~~~ +!!! error TS2322: Type 'Baz' is not assignable to type 'Foo'. +!!! error TS2322: Property 'x' is missing in type 'Baz'. + } \ No newline at end of file diff --git a/tests/baselines/reference/generatorTypeCheck20.js b/tests/baselines/reference/generatorTypeCheck20.js new file mode 100644 index 00000000000..c7336079bf0 --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck20.js @@ -0,0 +1,17 @@ +//// [generatorTypeCheck20.ts] +class Foo { x: number } +class Baz { z: number } +function* g(): IterableIterator { + yield; + yield * [new Baz]; +} + +//// [generatorTypeCheck20.js] +class Foo { +} +class Baz { +} +function* g() { + yield; + yield* [new Baz]; +} diff --git a/tests/baselines/reference/generatorTypeCheck21.errors.txt b/tests/baselines/reference/generatorTypeCheck21.errors.txt new file mode 100644 index 00000000000..0ef66aa1bd7 --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck21.errors.txt @@ -0,0 +1,12 @@ +tests/cases/conformance/es6/yieldExpressions/generatorTypeCheck21.ts(5,13): error TS2488: Type must have a '[Symbol.iterator]()' method that returns an iterator. + + +==== tests/cases/conformance/es6/yieldExpressions/generatorTypeCheck21.ts (1 errors) ==== + class Foo { x: number } + class Bar extends Foo { y: string } + function* g(): IterableIterator { + yield; + yield * new Bar; + ~~~~~~~ +!!! error TS2488: Type must have a '[Symbol.iterator]()' method that returns an iterator. + } \ No newline at end of file diff --git a/tests/baselines/reference/generatorTypeCheck21.js b/tests/baselines/reference/generatorTypeCheck21.js new file mode 100644 index 00000000000..83d1007a2c2 --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck21.js @@ -0,0 +1,17 @@ +//// [generatorTypeCheck21.ts] +class Foo { x: number } +class Bar extends Foo { y: string } +function* g(): IterableIterator { + yield; + yield * new Bar; +} + +//// [generatorTypeCheck21.js] +class Foo { +} +class Bar extends Foo { +} +function* g() { + yield; + yield* new Bar; +} diff --git a/tests/baselines/reference/generatorTypeCheck22.errors.txt b/tests/baselines/reference/generatorTypeCheck22.errors.txt new file mode 100644 index 00000000000..ab2b3de4f42 --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck22.errors.txt @@ -0,0 +1,16 @@ +tests/cases/conformance/es6/yieldExpressions/generatorTypeCheck22.ts(4,11): error TS2504: No best common type exists among yield expressions. + + +==== tests/cases/conformance/es6/yieldExpressions/generatorTypeCheck22.ts (1 errors) ==== + class Foo { x: number } + class Bar extends Foo { y: string } + class Baz { z: number } + function* g3() { + ~~ +!!! error TS2504: No best common type exists among yield expressions. + yield; + yield new Bar; + yield new Baz; + yield *[new Bar]; + yield *[new Baz]; + } \ No newline at end of file diff --git a/tests/baselines/reference/generatorTypeCheck22.js b/tests/baselines/reference/generatorTypeCheck22.js new file mode 100644 index 00000000000..0045e115e6f --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck22.js @@ -0,0 +1,26 @@ +//// [generatorTypeCheck22.ts] +class Foo { x: number } +class Bar extends Foo { y: string } +class Baz { z: number } +function* g3() { + yield; + yield new Bar; + yield new Baz; + yield *[new Bar]; + yield *[new Baz]; +} + +//// [generatorTypeCheck22.js] +class Foo { +} +class Bar extends Foo { +} +class Baz { +} +function* g3() { + yield; + yield new Bar; + yield new Baz; + yield* [new Bar]; + yield* [new Baz]; +} diff --git a/tests/baselines/reference/generatorTypeCheck23.errors.txt b/tests/baselines/reference/generatorTypeCheck23.errors.txt new file mode 100644 index 00000000000..9e85117a0a8 --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck23.errors.txt @@ -0,0 +1,17 @@ +tests/cases/conformance/es6/yieldExpressions/generatorTypeCheck23.ts(4,11): error TS2504: No best common type exists among yield expressions. + + +==== tests/cases/conformance/es6/yieldExpressions/generatorTypeCheck23.ts (1 errors) ==== + class Foo { x: number } + class Bar extends Foo { y: string } + class Baz { z: number } + function* g3() { + ~~ +!!! error TS2504: No best common type exists among yield expressions. + yield; + yield new Foo; + yield new Bar; + yield new Baz; + yield *[new Bar]; + yield *[new Baz]; + } \ No newline at end of file diff --git a/tests/baselines/reference/generatorTypeCheck23.js b/tests/baselines/reference/generatorTypeCheck23.js new file mode 100644 index 00000000000..37c2c239e2c --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck23.js @@ -0,0 +1,28 @@ +//// [generatorTypeCheck23.ts] +class Foo { x: number } +class Bar extends Foo { y: string } +class Baz { z: number } +function* g3() { + yield; + yield new Foo; + yield new Bar; + yield new Baz; + yield *[new Bar]; + yield *[new Baz]; +} + +//// [generatorTypeCheck23.js] +class Foo { +} +class Bar extends Foo { +} +class Baz { +} +function* g3() { + yield; + yield new Foo; + yield new Bar; + yield new Baz; + yield* [new Bar]; + yield* [new Baz]; +} diff --git a/tests/baselines/reference/generatorTypeCheck24.errors.txt b/tests/baselines/reference/generatorTypeCheck24.errors.txt new file mode 100644 index 00000000000..b4ca13c14c2 --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck24.errors.txt @@ -0,0 +1,17 @@ +tests/cases/conformance/es6/yieldExpressions/generatorTypeCheck24.ts(4,11): error TS2504: No best common type exists among yield expressions. + + +==== tests/cases/conformance/es6/yieldExpressions/generatorTypeCheck24.ts (1 errors) ==== + class Foo { x: number } + class Bar extends Foo { y: string } + class Baz { z: number } + function* g3() { + ~~ +!!! error TS2504: No best common type exists among yield expressions. + yield; + yield * [new Foo]; + yield new Bar; + yield new Baz; + yield *[new Bar]; + yield *[new Baz]; + } \ No newline at end of file diff --git a/tests/baselines/reference/generatorTypeCheck24.js b/tests/baselines/reference/generatorTypeCheck24.js new file mode 100644 index 00000000000..8b6018243ca --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck24.js @@ -0,0 +1,28 @@ +//// [generatorTypeCheck24.ts] +class Foo { x: number } +class Bar extends Foo { y: string } +class Baz { z: number } +function* g3() { + yield; + yield * [new Foo]; + yield new Bar; + yield new Baz; + yield *[new Bar]; + yield *[new Baz]; +} + +//// [generatorTypeCheck24.js] +class Foo { +} +class Bar extends Foo { +} +class Baz { +} +function* g3() { + yield; + yield* [new Foo]; + yield new Bar; + yield new Baz; + yield* [new Bar]; + yield* [new Baz]; +} diff --git a/tests/baselines/reference/generatorTypeCheck25.errors.txt b/tests/baselines/reference/generatorTypeCheck25.errors.txt new file mode 100644 index 00000000000..8d414c7c471 --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck25.errors.txt @@ -0,0 +1,36 @@ +tests/cases/conformance/es6/yieldExpressions/generatorTypeCheck25.ts(4,5): error TS2322: Type '() => IterableIterator' is not assignable to type '() => Iterable'. + Type 'IterableIterator' is not assignable to type 'Iterable'. + Types of property '[Symbol.iterator]' are incompatible. + Type '() => IterableIterator' is not assignable to type '() => Iterator'. + Type 'IterableIterator' is not assignable to type 'Iterator'. + Types of property 'next' are incompatible. + Type '(value?: any) => IteratorResult' is not assignable to type '(value?: any) => IteratorResult'. + Type 'IteratorResult' is not assignable to type 'IteratorResult'. + Type 'Bar | Baz' is not assignable to type 'Foo'. + Type 'Baz' is not assignable to type 'Foo'. + Property 'x' is missing in type 'Baz'. + + +==== tests/cases/conformance/es6/yieldExpressions/generatorTypeCheck25.ts (1 errors) ==== + class Foo { x: number } + class Bar extends Foo { y: string } + class Baz { z: number } + var g3: () => Iterable = function* () { + ~~ +!!! error TS2322: Type '() => IterableIterator' is not assignable to type '() => Iterable'. +!!! error TS2322: Type 'IterableIterator' is not assignable to type 'Iterable'. +!!! error TS2322: Types of property '[Symbol.iterator]' are incompatible. +!!! error TS2322: Type '() => IterableIterator' is not assignable to type '() => Iterator'. +!!! error TS2322: Type 'IterableIterator' is not assignable to type 'Iterator'. +!!! error TS2322: Types of property 'next' are incompatible. +!!! error TS2322: Type '(value?: any) => IteratorResult' is not assignable to type '(value?: any) => IteratorResult'. +!!! error TS2322: Type 'IteratorResult' is not assignable to type 'IteratorResult'. +!!! error TS2322: Type 'Bar | Baz' is not assignable to type 'Foo'. +!!! error TS2322: Type 'Baz' is not assignable to type 'Foo'. +!!! error TS2322: Property 'x' is missing in type 'Baz'. + yield; + yield new Bar; + yield new Baz; + yield *[new Bar]; + yield *[new Baz]; + } \ No newline at end of file diff --git a/tests/baselines/reference/generatorTypeCheck25.js b/tests/baselines/reference/generatorTypeCheck25.js new file mode 100644 index 00000000000..894561bcc93 --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck25.js @@ -0,0 +1,26 @@ +//// [generatorTypeCheck25.ts] +class Foo { x: number } +class Bar extends Foo { y: string } +class Baz { z: number } +var g3: () => Iterable = function* () { + yield; + yield new Bar; + yield new Baz; + yield *[new Bar]; + yield *[new Baz]; +} + +//// [generatorTypeCheck25.js] +class Foo { +} +class Bar extends Foo { +} +class Baz { +} +var g3 = function* () { + yield; + yield new Bar; + yield new Baz; + yield* [new Bar]; + yield* [new Baz]; +}; diff --git a/tests/baselines/reference/generatorTypeCheck26.js b/tests/baselines/reference/generatorTypeCheck26.js new file mode 100644 index 00000000000..d5c1a4c7947 --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck26.js @@ -0,0 +1,13 @@ +//// [generatorTypeCheck26.ts] +function* g(): IterableIterator<(x: string) => number> { + yield x => x.length; + yield *[x => x.length]; + return x => x.length; +} + +//// [generatorTypeCheck26.js] +function* g() { + yield x => x.length; + yield* [x => x.length]; + return x => x.length; +} diff --git a/tests/baselines/reference/generatorTypeCheck26.symbols b/tests/baselines/reference/generatorTypeCheck26.symbols new file mode 100644 index 00000000000..4d3ad862565 --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck26.symbols @@ -0,0 +1,22 @@ +=== tests/cases/conformance/es6/yieldExpressions/generatorTypeCheck26.ts === +function* g(): IterableIterator<(x: string) => number> { +>g : Symbol(g, Decl(generatorTypeCheck26.ts, 0, 0)) +>IterableIterator : Symbol(IterableIterator, Decl(lib.d.ts, 1672, 1)) +>x : Symbol(x, Decl(generatorTypeCheck26.ts, 0, 33)) + + yield x => x.length; +>x : Symbol(x, Decl(generatorTypeCheck26.ts, 1, 9)) +>x.length : Symbol(String.length, Decl(lib.d.ts, 414, 19)) +>x : Symbol(x, Decl(generatorTypeCheck26.ts, 1, 9)) +>length : Symbol(String.length, Decl(lib.d.ts, 414, 19)) + + yield *[x => x.length]; +>x : Symbol(x, Decl(generatorTypeCheck26.ts, 2, 12)) +>x.length : Symbol(String.length, Decl(lib.d.ts, 414, 19)) +>x : Symbol(x, Decl(generatorTypeCheck26.ts, 2, 12)) +>length : Symbol(String.length, Decl(lib.d.ts, 414, 19)) + + return x => x.length; +>x : Symbol(x, Decl(generatorTypeCheck26.ts, 3, 10)) +>x : Symbol(x, Decl(generatorTypeCheck26.ts, 3, 10)) +} diff --git a/tests/baselines/reference/generatorTypeCheck26.types b/tests/baselines/reference/generatorTypeCheck26.types new file mode 100644 index 00000000000..8141a866c8e --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck26.types @@ -0,0 +1,30 @@ +=== tests/cases/conformance/es6/yieldExpressions/generatorTypeCheck26.ts === +function* g(): IterableIterator<(x: string) => number> { +>g : () => IterableIterator<(x: string) => number> +>IterableIterator : IterableIterator +>x : string + + yield x => x.length; +>yield x => x.length : any +>x => x.length : (x: string) => number +>x : string +>x.length : number +>x : string +>length : number + + yield *[x => x.length]; +>yield *[x => x.length] : any +>[x => x.length] : ((x: string) => number)[] +>x => x.length : (x: string) => number +>x : string +>x.length : number +>x : string +>length : number + + return x => x.length; +>x => x.length : (x: any) => any +>x : any +>x.length : any +>x : any +>length : any +} diff --git a/tests/baselines/reference/generatorTypeCheck27.js b/tests/baselines/reference/generatorTypeCheck27.js new file mode 100644 index 00000000000..528d510bed2 --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck27.js @@ -0,0 +1,13 @@ +//// [generatorTypeCheck27.ts] +function* g(): IterableIterator<(x: string) => number> { + yield * function* () { + yield x => x.length; + } (); +} + +//// [generatorTypeCheck27.js] +function* g() { + yield* function* () { + yield x => x.length; + }(); +} diff --git a/tests/baselines/reference/generatorTypeCheck27.symbols b/tests/baselines/reference/generatorTypeCheck27.symbols new file mode 100644 index 00000000000..bfff5f9e10a --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck27.symbols @@ -0,0 +1,13 @@ +=== tests/cases/conformance/es6/yieldExpressions/generatorTypeCheck27.ts === +function* g(): IterableIterator<(x: string) => number> { +>g : Symbol(g, Decl(generatorTypeCheck27.ts, 0, 0)) +>IterableIterator : Symbol(IterableIterator, Decl(lib.d.ts, 1672, 1)) +>x : Symbol(x, Decl(generatorTypeCheck27.ts, 0, 33)) + + yield * function* () { + yield x => x.length; +>x : Symbol(x, Decl(generatorTypeCheck27.ts, 2, 13)) +>x : Symbol(x, Decl(generatorTypeCheck27.ts, 2, 13)) + + } (); +} diff --git a/tests/baselines/reference/generatorTypeCheck27.types b/tests/baselines/reference/generatorTypeCheck27.types new file mode 100644 index 00000000000..7b120cfffc4 --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck27.types @@ -0,0 +1,21 @@ +=== tests/cases/conformance/es6/yieldExpressions/generatorTypeCheck27.ts === +function* g(): IterableIterator<(x: string) => number> { +>g : () => IterableIterator<(x: string) => number> +>IterableIterator : IterableIterator +>x : string + + yield * function* () { +>yield * function* () { yield x => x.length; } () : any +>function* () { yield x => x.length; } () : IterableIterator<(x: any) => any> +>function* () { yield x => x.length; } : () => IterableIterator<(x: any) => any> + + yield x => x.length; +>yield x => x.length : any +>x => x.length : (x: any) => any +>x : any +>x.length : any +>x : any +>length : any + + } (); +} diff --git a/tests/baselines/reference/generatorTypeCheck28.js b/tests/baselines/reference/generatorTypeCheck28.js new file mode 100644 index 00000000000..e94fd9b7e38 --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck28.js @@ -0,0 +1,17 @@ +//// [generatorTypeCheck28.ts] +function* g(): IterableIterator<(x: string) => number> { + yield * { + *[Symbol.iterator]() { + yield x => x.length; + } + }; +} + +//// [generatorTypeCheck28.js] +function* g() { + yield* { + *[Symbol.iterator]() { + yield x => x.length; + } + }; +} diff --git a/tests/baselines/reference/generatorTypeCheck28.symbols b/tests/baselines/reference/generatorTypeCheck28.symbols new file mode 100644 index 00000000000..e1bbbd96b40 --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck28.symbols @@ -0,0 +1,20 @@ +=== tests/cases/conformance/es6/yieldExpressions/generatorTypeCheck28.ts === +function* g(): IterableIterator<(x: string) => number> { +>g : Symbol(g, Decl(generatorTypeCheck28.ts, 0, 0)) +>IterableIterator : Symbol(IterableIterator, Decl(lib.d.ts, 1672, 1)) +>x : Symbol(x, Decl(generatorTypeCheck28.ts, 0, 33)) + + yield * { + *[Symbol.iterator]() { +>Symbol.iterator : Symbol(SymbolConstructor.iterator, Decl(lib.d.ts, 1236, 31)) +>Symbol : Symbol(Symbol, Decl(lib.d.ts, 1186, 52), Decl(lib.d.ts, 1292, 11)) +>iterator : Symbol(SymbolConstructor.iterator, Decl(lib.d.ts, 1236, 31)) + + yield x => x.length; +>x : Symbol(x, Decl(generatorTypeCheck28.ts, 3, 17)) +>x.length : Symbol(String.length, Decl(lib.d.ts, 414, 19)) +>x : Symbol(x, Decl(generatorTypeCheck28.ts, 3, 17)) +>length : Symbol(String.length, Decl(lib.d.ts, 414, 19)) + } + }; +} diff --git a/tests/baselines/reference/generatorTypeCheck28.types b/tests/baselines/reference/generatorTypeCheck28.types new file mode 100644 index 00000000000..1afae072758 --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck28.types @@ -0,0 +1,25 @@ +=== tests/cases/conformance/es6/yieldExpressions/generatorTypeCheck28.ts === +function* g(): IterableIterator<(x: string) => number> { +>g : () => IterableIterator<(x: string) => number> +>IterableIterator : IterableIterator +>x : string + + yield * { +>yield * { *[Symbol.iterator]() { yield x => x.length; } } : any +>{ *[Symbol.iterator]() { yield x => x.length; } } : { [Symbol.iterator](): IterableIterator<(x: string) => number>; } + + *[Symbol.iterator]() { +>Symbol.iterator : symbol +>Symbol : SymbolConstructor +>iterator : symbol + + yield x => x.length; +>yield x => x.length : any +>x => x.length : (x: string) => number +>x : string +>x.length : number +>x : string +>length : number + } + }; +} diff --git a/tests/baselines/reference/generatorTypeCheck29.js b/tests/baselines/reference/generatorTypeCheck29.js new file mode 100644 index 00000000000..4f5204f89fc --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck29.js @@ -0,0 +1,13 @@ +//// [generatorTypeCheck29.ts] +function* g2(): Iterator number>> { + yield function* () { + yield x => x.length; + } () +} + +//// [generatorTypeCheck29.js] +function* g2() { + yield function* () { + yield x => x.length; + }(); +} diff --git a/tests/baselines/reference/generatorTypeCheck29.symbols b/tests/baselines/reference/generatorTypeCheck29.symbols new file mode 100644 index 00000000000..57790d5b700 --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck29.symbols @@ -0,0 +1,14 @@ +=== tests/cases/conformance/es6/yieldExpressions/generatorTypeCheck29.ts === +function* g2(): Iterator number>> { +>g2 : Symbol(g2, Decl(generatorTypeCheck29.ts, 0, 0)) +>Iterator : Symbol(Iterator, Decl(lib.d.ts, 1662, 1)) +>Iterable : Symbol(Iterable, Decl(lib.d.ts, 1668, 1)) +>x : Symbol(x, Decl(generatorTypeCheck29.ts, 0, 35)) + + yield function* () { + yield x => x.length; +>x : Symbol(x, Decl(generatorTypeCheck29.ts, 2, 13)) +>x : Symbol(x, Decl(generatorTypeCheck29.ts, 2, 13)) + + } () +} diff --git a/tests/baselines/reference/generatorTypeCheck29.types b/tests/baselines/reference/generatorTypeCheck29.types new file mode 100644 index 00000000000..85cb32e5759 --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck29.types @@ -0,0 +1,22 @@ +=== tests/cases/conformance/es6/yieldExpressions/generatorTypeCheck29.ts === +function* g2(): Iterator number>> { +>g2 : () => Iterator number>> +>Iterator : Iterator +>Iterable : Iterable +>x : string + + yield function* () { +>yield function* () { yield x => x.length; } () : any +>function* () { yield x => x.length; } () : IterableIterator<(x: any) => any> +>function* () { yield x => x.length; } : () => IterableIterator<(x: any) => any> + + yield x => x.length; +>yield x => x.length : any +>x => x.length : (x: any) => any +>x : any +>x.length : any +>x : any +>length : any + + } () +} diff --git a/tests/baselines/reference/generatorTypeCheck3.js b/tests/baselines/reference/generatorTypeCheck3.js new file mode 100644 index 00000000000..9d884a92f5e --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck3.js @@ -0,0 +1,5 @@ +//// [generatorTypeCheck3.ts] +function* g1(): IterableIterator { } + +//// [generatorTypeCheck3.js] +function* g1() { } diff --git a/tests/baselines/reference/generatorTypeCheck3.symbols b/tests/baselines/reference/generatorTypeCheck3.symbols new file mode 100644 index 00000000000..2f5d2405507 --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck3.symbols @@ -0,0 +1,5 @@ +=== tests/cases/conformance/es6/yieldExpressions/generatorTypeCheck3.ts === +function* g1(): IterableIterator { } +>g1 : Symbol(g1, Decl(generatorTypeCheck3.ts, 0, 0)) +>IterableIterator : Symbol(IterableIterator, Decl(lib.d.ts, 1672, 1)) + diff --git a/tests/baselines/reference/generatorTypeCheck3.types b/tests/baselines/reference/generatorTypeCheck3.types new file mode 100644 index 00000000000..9d2fb9d517d --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck3.types @@ -0,0 +1,5 @@ +=== tests/cases/conformance/es6/yieldExpressions/generatorTypeCheck3.ts === +function* g1(): IterableIterator { } +>g1 : () => IterableIterator +>IterableIterator : IterableIterator + diff --git a/tests/baselines/reference/generatorTypeCheck30.js b/tests/baselines/reference/generatorTypeCheck30.js new file mode 100644 index 00000000000..e652dd1b55f --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck30.js @@ -0,0 +1,13 @@ +//// [generatorTypeCheck30.ts] +function* g2(): Iterator number>> { + yield function* () { + yield x => x.length; + } () +} + +//// [generatorTypeCheck30.js] +function* g2() { + yield function* () { + yield x => x.length; + }(); +} diff --git a/tests/baselines/reference/generatorTypeCheck30.symbols b/tests/baselines/reference/generatorTypeCheck30.symbols new file mode 100644 index 00000000000..49c43ce135f --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck30.symbols @@ -0,0 +1,14 @@ +=== tests/cases/conformance/es6/yieldExpressions/generatorTypeCheck30.ts === +function* g2(): Iterator number>> { +>g2 : Symbol(g2, Decl(generatorTypeCheck30.ts, 0, 0)) +>Iterator : Symbol(Iterator, Decl(lib.d.ts, 1662, 1)) +>Iterable : Symbol(Iterable, Decl(lib.d.ts, 1668, 1)) +>x : Symbol(x, Decl(generatorTypeCheck30.ts, 0, 35)) + + yield function* () { + yield x => x.length; +>x : Symbol(x, Decl(generatorTypeCheck30.ts, 2, 13)) +>x : Symbol(x, Decl(generatorTypeCheck30.ts, 2, 13)) + + } () +} diff --git a/tests/baselines/reference/generatorTypeCheck30.types b/tests/baselines/reference/generatorTypeCheck30.types new file mode 100644 index 00000000000..2ed94dff531 --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck30.types @@ -0,0 +1,22 @@ +=== tests/cases/conformance/es6/yieldExpressions/generatorTypeCheck30.ts === +function* g2(): Iterator number>> { +>g2 : () => Iterator number>> +>Iterator : Iterator +>Iterable : Iterable +>x : string + + yield function* () { +>yield function* () { yield x => x.length; } () : any +>function* () { yield x => x.length; } () : IterableIterator<(x: any) => any> +>function* () { yield x => x.length; } : () => IterableIterator<(x: any) => any> + + yield x => x.length; +>yield x => x.length : any +>x => x.length : (x: any) => any +>x : any +>x.length : any +>x : any +>length : any + + } () +} diff --git a/tests/baselines/reference/generatorTypeCheck31.errors.txt b/tests/baselines/reference/generatorTypeCheck31.errors.txt new file mode 100644 index 00000000000..a0336b464a4 --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck31.errors.txt @@ -0,0 +1,13 @@ +tests/cases/conformance/es6/yieldExpressions/generatorTypeCheck31.ts(2,11): error TS2322: Type 'IterableIterator<(x: any) => any>' is not assignable to type '() => Iterable<(x: string) => number>'. + + +==== tests/cases/conformance/es6/yieldExpressions/generatorTypeCheck31.ts (1 errors) ==== + function* g2(): Iterator<() => Iterable<(x: string) => number>> { + yield function* () { + ~~~~~~~~~~~~~~ + yield x => x.length; + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + } () + ~~~~~~~~ +!!! error TS2322: Type 'IterableIterator<(x: any) => any>' is not assignable to type '() => Iterable<(x: string) => number>'. + } \ No newline at end of file diff --git a/tests/baselines/reference/generatorTypeCheck31.js b/tests/baselines/reference/generatorTypeCheck31.js new file mode 100644 index 00000000000..2037b0ec621 --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck31.js @@ -0,0 +1,13 @@ +//// [generatorTypeCheck31.ts] +function* g2(): Iterator<() => Iterable<(x: string) => number>> { + yield function* () { + yield x => x.length; + } () +} + +//// [generatorTypeCheck31.js] +function* g2() { + yield function* () { + yield x => x.length; + }(); +} diff --git a/tests/baselines/reference/generatorTypeCheck32.errors.txt b/tests/baselines/reference/generatorTypeCheck32.errors.txt new file mode 100644 index 00000000000..9312371d7eb --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck32.errors.txt @@ -0,0 +1,8 @@ +tests/cases/conformance/es6/yieldExpressions/generatorTypeCheck32.ts(2,29): error TS1163: A 'yield' expression is only allowed in a generator body. + + +==== tests/cases/conformance/es6/yieldExpressions/generatorTypeCheck32.ts (1 errors) ==== + var s: string; + var f: () => number = () => yield s; + ~~~~~ +!!! error TS1163: A 'yield' expression is only allowed in a generator body. \ No newline at end of file diff --git a/tests/baselines/reference/generatorTypeCheck32.js b/tests/baselines/reference/generatorTypeCheck32.js new file mode 100644 index 00000000000..5ec8e9214f3 --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck32.js @@ -0,0 +1,7 @@ +//// [generatorTypeCheck32.ts] +var s: string; +var f: () => number = () => yield s; + +//// [generatorTypeCheck32.js] +var s; +var f = () => yield s; diff --git a/tests/baselines/reference/generatorTypeCheck33.js b/tests/baselines/reference/generatorTypeCheck33.js new file mode 100644 index 00000000000..256e4c94be7 --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck33.js @@ -0,0 +1,15 @@ +//// [generatorTypeCheck33.ts] +function* g() { + yield 0; + function* g2() { + yield ""; + } +} + +//// [generatorTypeCheck33.js] +function* g() { + yield 0; + function* g2() { + yield ""; + } +} diff --git a/tests/baselines/reference/generatorTypeCheck33.symbols b/tests/baselines/reference/generatorTypeCheck33.symbols new file mode 100644 index 00000000000..b1bda8808f2 --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck33.symbols @@ -0,0 +1,11 @@ +=== tests/cases/conformance/es6/yieldExpressions/generatorTypeCheck33.ts === +function* g() { +>g : Symbol(g, Decl(generatorTypeCheck33.ts, 0, 0)) + + yield 0; + function* g2() { +>g2 : Symbol(g2, Decl(generatorTypeCheck33.ts, 1, 12)) + + yield ""; + } +} diff --git a/tests/baselines/reference/generatorTypeCheck33.types b/tests/baselines/reference/generatorTypeCheck33.types new file mode 100644 index 00000000000..f3b8af225d1 --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck33.types @@ -0,0 +1,16 @@ +=== tests/cases/conformance/es6/yieldExpressions/generatorTypeCheck33.ts === +function* g() { +>g : () => IterableIterator + + yield 0; +>yield 0 : any +>0 : number + + function* g2() { +>g2 : () => IterableIterator + + yield ""; +>yield "" : any +>"" : string + } +} diff --git a/tests/baselines/reference/generatorTypeCheck34.js b/tests/baselines/reference/generatorTypeCheck34.js new file mode 100644 index 00000000000..20b88b9a090 --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck34.js @@ -0,0 +1,15 @@ +//// [generatorTypeCheck34.ts] +function* g() { + yield 0; + function* g2() { + return ""; + } +} + +//// [generatorTypeCheck34.js] +function* g() { + yield 0; + function* g2() { + return ""; + } +} diff --git a/tests/baselines/reference/generatorTypeCheck34.symbols b/tests/baselines/reference/generatorTypeCheck34.symbols new file mode 100644 index 00000000000..343b68c3bda --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck34.symbols @@ -0,0 +1,11 @@ +=== tests/cases/conformance/es6/yieldExpressions/generatorTypeCheck34.ts === +function* g() { +>g : Symbol(g, Decl(generatorTypeCheck34.ts, 0, 0)) + + yield 0; + function* g2() { +>g2 : Symbol(g2, Decl(generatorTypeCheck34.ts, 1, 12)) + + return ""; + } +} diff --git a/tests/baselines/reference/generatorTypeCheck34.types b/tests/baselines/reference/generatorTypeCheck34.types new file mode 100644 index 00000000000..35063e988eb --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck34.types @@ -0,0 +1,15 @@ +=== tests/cases/conformance/es6/yieldExpressions/generatorTypeCheck34.ts === +function* g() { +>g : () => IterableIterator + + yield 0; +>yield 0 : any +>0 : number + + function* g2() { +>g2 : () => IterableIterator + + return ""; +>"" : string + } +} diff --git a/tests/baselines/reference/generatorTypeCheck35.js b/tests/baselines/reference/generatorTypeCheck35.js new file mode 100644 index 00000000000..e2b1c10850a --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck35.js @@ -0,0 +1,15 @@ +//// [generatorTypeCheck35.ts] +function* g() { + yield 0; + function g2() { + return ""; + } +} + +//// [generatorTypeCheck35.js] +function* g() { + yield 0; + function g2() { + return ""; + } +} diff --git a/tests/baselines/reference/generatorTypeCheck35.symbols b/tests/baselines/reference/generatorTypeCheck35.symbols new file mode 100644 index 00000000000..43271b79e9e --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck35.symbols @@ -0,0 +1,11 @@ +=== tests/cases/conformance/es6/yieldExpressions/generatorTypeCheck35.ts === +function* g() { +>g : Symbol(g, Decl(generatorTypeCheck35.ts, 0, 0)) + + yield 0; + function g2() { +>g2 : Symbol(g2, Decl(generatorTypeCheck35.ts, 1, 12)) + + return ""; + } +} diff --git a/tests/baselines/reference/generatorTypeCheck35.types b/tests/baselines/reference/generatorTypeCheck35.types new file mode 100644 index 00000000000..0bfc22ab3f0 --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck35.types @@ -0,0 +1,15 @@ +=== tests/cases/conformance/es6/yieldExpressions/generatorTypeCheck35.ts === +function* g() { +>g : () => IterableIterator + + yield 0; +>yield 0 : any +>0 : number + + function g2() { +>g2 : () => string + + return ""; +>"" : string + } +} diff --git a/tests/baselines/reference/generatorTypeCheck36.js b/tests/baselines/reference/generatorTypeCheck36.js new file mode 100644 index 00000000000..a207860603b --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck36.js @@ -0,0 +1,9 @@ +//// [generatorTypeCheck36.ts] +function* g() { + yield yield 0; +} + +//// [generatorTypeCheck36.js] +function* g() { + yield yield 0; +} diff --git a/tests/baselines/reference/generatorTypeCheck36.symbols b/tests/baselines/reference/generatorTypeCheck36.symbols new file mode 100644 index 00000000000..dc7eb37fe30 --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck36.symbols @@ -0,0 +1,6 @@ +=== tests/cases/conformance/es6/yieldExpressions/generatorTypeCheck36.ts === +function* g() { +>g : Symbol(g, Decl(generatorTypeCheck36.ts, 0, 0)) + + yield yield 0; +} diff --git a/tests/baselines/reference/generatorTypeCheck36.types b/tests/baselines/reference/generatorTypeCheck36.types new file mode 100644 index 00000000000..110a4d3e02e --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck36.types @@ -0,0 +1,9 @@ +=== tests/cases/conformance/es6/yieldExpressions/generatorTypeCheck36.ts === +function* g() { +>g : () => IterableIterator + + yield yield 0; +>yield yield 0 : any +>yield 0 : any +>0 : number +} diff --git a/tests/baselines/reference/generatorTypeCheck37.js b/tests/baselines/reference/generatorTypeCheck37.js new file mode 100644 index 00000000000..4c73dfe558a --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck37.js @@ -0,0 +1,9 @@ +//// [generatorTypeCheck37.ts] +function* g() { + return yield yield 0; +} + +//// [generatorTypeCheck37.js] +function* g() { + return yield yield 0; +} diff --git a/tests/baselines/reference/generatorTypeCheck37.symbols b/tests/baselines/reference/generatorTypeCheck37.symbols new file mode 100644 index 00000000000..8939c5382e2 --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck37.symbols @@ -0,0 +1,6 @@ +=== tests/cases/conformance/es6/yieldExpressions/generatorTypeCheck37.ts === +function* g() { +>g : Symbol(g, Decl(generatorTypeCheck37.ts, 0, 0)) + + return yield yield 0; +} diff --git a/tests/baselines/reference/generatorTypeCheck37.types b/tests/baselines/reference/generatorTypeCheck37.types new file mode 100644 index 00000000000..e8611ec167a --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck37.types @@ -0,0 +1,9 @@ +=== tests/cases/conformance/es6/yieldExpressions/generatorTypeCheck37.ts === +function* g() { +>g : () => IterableIterator + + return yield yield 0; +>yield yield 0 : any +>yield 0 : any +>0 : number +} diff --git a/tests/baselines/reference/generatorTypeCheck38.js b/tests/baselines/reference/generatorTypeCheck38.js new file mode 100644 index 00000000000..de5258db785 --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck38.js @@ -0,0 +1,13 @@ +//// [generatorTypeCheck38.ts] +var yield; +function* g() { + yield 0; + var v: typeof yield; +} + +//// [generatorTypeCheck38.js] +var yield; +function* g() { + yield 0; + var v; +} diff --git a/tests/baselines/reference/generatorTypeCheck38.symbols b/tests/baselines/reference/generatorTypeCheck38.symbols new file mode 100644 index 00000000000..83410159b1a --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck38.symbols @@ -0,0 +1,12 @@ +=== tests/cases/conformance/es6/yieldExpressions/generatorTypeCheck38.ts === +var yield; +>yield : Symbol(yield, Decl(generatorTypeCheck38.ts, 0, 3)) + +function* g() { +>g : Symbol(g, Decl(generatorTypeCheck38.ts, 0, 10)) + + yield 0; + var v: typeof yield; +>v : Symbol(v, Decl(generatorTypeCheck38.ts, 3, 7)) +>yield : Symbol(yield, Decl(generatorTypeCheck38.ts, 0, 3)) +} diff --git a/tests/baselines/reference/generatorTypeCheck38.types b/tests/baselines/reference/generatorTypeCheck38.types new file mode 100644 index 00000000000..08503e8640f --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck38.types @@ -0,0 +1,15 @@ +=== tests/cases/conformance/es6/yieldExpressions/generatorTypeCheck38.ts === +var yield; +>yield : any + +function* g() { +>g : () => IterableIterator + + yield 0; +>yield 0 : any +>0 : number + + var v: typeof yield; +>v : any +>yield : any +} diff --git a/tests/baselines/reference/generatorTypeCheck39.errors.txt b/tests/baselines/reference/generatorTypeCheck39.errors.txt new file mode 100644 index 00000000000..ae24837f712 --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck39.errors.txt @@ -0,0 +1,21 @@ +tests/cases/conformance/es6/yieldExpressions/generatorTypeCheck39.ts(5,16): error TS1163: A 'yield' expression is only allowed in a generator body. +tests/cases/conformance/es6/yieldExpressions/generatorTypeCheck39.ts(6,11): error TS1219: Experimental support for decorators is a feature that is subject to change in a future release. Specify '--experimentalDecorators' to remove this warning. +tests/cases/conformance/es6/yieldExpressions/generatorTypeCheck39.ts(7,13): error TS1163: A 'yield' expression is only allowed in a generator body. + + +==== tests/cases/conformance/es6/yieldExpressions/generatorTypeCheck39.ts (3 errors) ==== + function decorator(x: any) { + return y => { }; + } + function* g() { + @decorator(yield 0) + ~~~~~ +!!! error TS1163: A 'yield' expression is only allowed in a generator body. + class C { + ~ +!!! error TS1219: Experimental support for decorators is a feature that is subject to change in a future release. Specify '--experimentalDecorators' to remove this warning. + x = yield 0; + ~~~~~ +!!! error TS1163: A 'yield' expression is only allowed in a generator body. + } + } \ No newline at end of file diff --git a/tests/baselines/reference/generatorTypeCheck39.js b/tests/baselines/reference/generatorTypeCheck39.js new file mode 100644 index 00000000000..e6d25045a7e --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck39.js @@ -0,0 +1,33 @@ +//// [generatorTypeCheck39.ts] +function decorator(x: any) { + return y => { }; +} +function* g() { + @decorator(yield 0) + class C { + x = yield 0; + } +} + +//// [generatorTypeCheck39.js] +var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") return Reflect.decorate(decorators, target, key, desc); + switch (arguments.length) { + case 2: return decorators.reduceRight(function(o, d) { return (d && d(o)) || o; }, target); + case 3: return decorators.reduceRight(function(o, d) { return (d && d(target, key)), void 0; }, void 0); + case 4: return decorators.reduceRight(function(o, d) { return (d && d(target, key, o)) || o; }, desc); + } +}; +function decorator(x) { + return y => { }; +} +function* g() { + let C = class { + constructor() { + this.x = yield 0; + } + }; + C = __decorate([ + decorator(yield 0) + ], C); +} diff --git a/tests/baselines/reference/generatorTypeCheck4.js b/tests/baselines/reference/generatorTypeCheck4.js new file mode 100644 index 00000000000..8c0d7aeddd1 --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck4.js @@ -0,0 +1,5 @@ +//// [generatorTypeCheck4.ts] +function* g1(): {} { } + +//// [generatorTypeCheck4.js] +function* g1() { } diff --git a/tests/baselines/reference/generatorTypeCheck4.symbols b/tests/baselines/reference/generatorTypeCheck4.symbols new file mode 100644 index 00000000000..fb7cd93e0d9 --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck4.symbols @@ -0,0 +1,4 @@ +=== tests/cases/conformance/es6/yieldExpressions/generatorTypeCheck4.ts === +function* g1(): {} { } +>g1 : Symbol(g1, Decl(generatorTypeCheck4.ts, 0, 0)) + diff --git a/tests/baselines/reference/generatorTypeCheck4.types b/tests/baselines/reference/generatorTypeCheck4.types new file mode 100644 index 00000000000..c90fda0c0fc --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck4.types @@ -0,0 +1,4 @@ +=== tests/cases/conformance/es6/yieldExpressions/generatorTypeCheck4.ts === +function* g1(): {} { } +>g1 : () => {} + diff --git a/tests/baselines/reference/generatorTypeCheck40.errors.txt b/tests/baselines/reference/generatorTypeCheck40.errors.txt new file mode 100644 index 00000000000..ba93862c8d5 --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck40.errors.txt @@ -0,0 +1,12 @@ +tests/cases/conformance/es6/yieldExpressions/generatorTypeCheck40.ts(2,21): error TS2507: Type 'any' is not a constructor function type. +tests/cases/conformance/es6/yieldExpressions/generatorTypeCheck40.ts(2,22): error TS1163: A 'yield' expression is only allowed in a generator body. + + +==== tests/cases/conformance/es6/yieldExpressions/generatorTypeCheck40.ts (2 errors) ==== + function* g() { + class C extends (yield 0) { } + ~~~~~~~~~ +!!! error TS2507: Type 'any' is not a constructor function type. + ~~~~~ +!!! error TS1163: A 'yield' expression is only allowed in a generator body. + } \ No newline at end of file diff --git a/tests/baselines/reference/generatorTypeCheck40.js b/tests/baselines/reference/generatorTypeCheck40.js new file mode 100644 index 00000000000..fe9bb797d77 --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck40.js @@ -0,0 +1,10 @@ +//// [generatorTypeCheck40.ts] +function* g() { + class C extends (yield 0) { } +} + +//// [generatorTypeCheck40.js] +function* g() { + class C extends (yield 0) { + } +} diff --git a/tests/baselines/reference/generatorTypeCheck41.js b/tests/baselines/reference/generatorTypeCheck41.js new file mode 100644 index 00000000000..51c5ce3d416 --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck41.js @@ -0,0 +1,13 @@ +//// [generatorTypeCheck41.ts] +function* g() { + let x = { + [yield 0]: 0 + } +} + +//// [generatorTypeCheck41.js] +function* g() { + let x = { + [yield 0]: 0 + }; +} diff --git a/tests/baselines/reference/generatorTypeCheck41.symbols b/tests/baselines/reference/generatorTypeCheck41.symbols new file mode 100644 index 00000000000..9111affa875 --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck41.symbols @@ -0,0 +1,10 @@ +=== tests/cases/conformance/es6/yieldExpressions/generatorTypeCheck41.ts === +function* g() { +>g : Symbol(g, Decl(generatorTypeCheck41.ts, 0, 0)) + + let x = { +>x : Symbol(x, Decl(generatorTypeCheck41.ts, 1, 7)) + + [yield 0]: 0 + } +} diff --git a/tests/baselines/reference/generatorTypeCheck41.types b/tests/baselines/reference/generatorTypeCheck41.types new file mode 100644 index 00000000000..926aef95ce5 --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck41.types @@ -0,0 +1,14 @@ +=== tests/cases/conformance/es6/yieldExpressions/generatorTypeCheck41.ts === +function* g() { +>g : () => IterableIterator + + let x = { +>x : {} +>{ [yield 0]: 0 } : {} + + [yield 0]: 0 +>yield 0 : any +>0 : number +>0 : number + } +} diff --git a/tests/baselines/reference/generatorTypeCheck42.js b/tests/baselines/reference/generatorTypeCheck42.js new file mode 100644 index 00000000000..c58802b1a81 --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck42.js @@ -0,0 +1,16 @@ +//// [generatorTypeCheck42.ts] +function* g() { + let x = { + [yield 0]() { + + } + } +} + +//// [generatorTypeCheck42.js] +function* g() { + let x = { + [yield 0]() { + } + }; +} diff --git a/tests/baselines/reference/generatorTypeCheck42.symbols b/tests/baselines/reference/generatorTypeCheck42.symbols new file mode 100644 index 00000000000..a49534fd211 --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck42.symbols @@ -0,0 +1,12 @@ +=== tests/cases/conformance/es6/yieldExpressions/generatorTypeCheck42.ts === +function* g() { +>g : Symbol(g, Decl(generatorTypeCheck42.ts, 0, 0)) + + let x = { +>x : Symbol(x, Decl(generatorTypeCheck42.ts, 1, 7)) + + [yield 0]() { + + } + } +} diff --git a/tests/baselines/reference/generatorTypeCheck42.types b/tests/baselines/reference/generatorTypeCheck42.types new file mode 100644 index 00000000000..855c4697f40 --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck42.types @@ -0,0 +1,15 @@ +=== tests/cases/conformance/es6/yieldExpressions/generatorTypeCheck42.ts === +function* g() { +>g : () => IterableIterator + + let x = { +>x : {} +>{ [yield 0]() { } } : {} + + [yield 0]() { +>yield 0 : any +>0 : number + + } + } +} diff --git a/tests/baselines/reference/generatorTypeCheck43.js b/tests/baselines/reference/generatorTypeCheck43.js new file mode 100644 index 00000000000..c7dc2dad393 --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck43.js @@ -0,0 +1,16 @@ +//// [generatorTypeCheck43.ts] +function* g() { + let x = { + *[yield 0]() { + + } + } +} + +//// [generatorTypeCheck43.js] +function* g() { + let x = { + *[yield 0]() { + } + }; +} diff --git a/tests/baselines/reference/generatorTypeCheck43.symbols b/tests/baselines/reference/generatorTypeCheck43.symbols new file mode 100644 index 00000000000..f5f7b6c359f --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck43.symbols @@ -0,0 +1,12 @@ +=== tests/cases/conformance/es6/yieldExpressions/generatorTypeCheck43.ts === +function* g() { +>g : Symbol(g, Decl(generatorTypeCheck43.ts, 0, 0)) + + let x = { +>x : Symbol(x, Decl(generatorTypeCheck43.ts, 1, 7)) + + *[yield 0]() { + + } + } +} diff --git a/tests/baselines/reference/generatorTypeCheck43.types b/tests/baselines/reference/generatorTypeCheck43.types new file mode 100644 index 00000000000..50fc7e30c86 --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck43.types @@ -0,0 +1,15 @@ +=== tests/cases/conformance/es6/yieldExpressions/generatorTypeCheck43.ts === +function* g() { +>g : () => IterableIterator + + let x = { +>x : {} +>{ *[yield 0]() { } } : {} + + *[yield 0]() { +>yield 0 : any +>0 : number + + } + } +} diff --git a/tests/baselines/reference/generatorTypeCheck44.js b/tests/baselines/reference/generatorTypeCheck44.js new file mode 100644 index 00000000000..238998ad974 --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck44.js @@ -0,0 +1,17 @@ +//// [generatorTypeCheck44.ts] +function* g() { + let x = { + get [yield 0]() { + return 0; + } + } +} + +//// [generatorTypeCheck44.js] +function* g() { + let x = { + get [yield 0]() { + return 0; + } + }; +} diff --git a/tests/baselines/reference/generatorTypeCheck44.symbols b/tests/baselines/reference/generatorTypeCheck44.symbols new file mode 100644 index 00000000000..b6606064c43 --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck44.symbols @@ -0,0 +1,12 @@ +=== tests/cases/conformance/es6/yieldExpressions/generatorTypeCheck44.ts === +function* g() { +>g : Symbol(g, Decl(generatorTypeCheck44.ts, 0, 0)) + + let x = { +>x : Symbol(x, Decl(generatorTypeCheck44.ts, 1, 7)) + + get [yield 0]() { + return 0; + } + } +} diff --git a/tests/baselines/reference/generatorTypeCheck44.types b/tests/baselines/reference/generatorTypeCheck44.types new file mode 100644 index 00000000000..2fc67f90556 --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck44.types @@ -0,0 +1,17 @@ +=== tests/cases/conformance/es6/yieldExpressions/generatorTypeCheck44.ts === +function* g() { +>g : () => IterableIterator + + let x = { +>x : {} +>{ get [yield 0]() { return 0; } } : {} + + get [yield 0]() { +>yield 0 : any +>0 : number + + return 0; +>0 : number + } + } +} diff --git a/tests/baselines/reference/generatorTypeCheck45.js b/tests/baselines/reference/generatorTypeCheck45.js new file mode 100644 index 00000000000..20f64e53c9d --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck45.js @@ -0,0 +1,7 @@ +//// [generatorTypeCheck45.ts] +declare function foo(x: T, fun: () => Iterator<(x: T) => U>, fun2: (y: U) => T): T; + +foo("", function* () { yield x => x.length }, p => undefined); // T is fixed, should be string + +//// [generatorTypeCheck45.js] +foo("", function* () { yield x => x.length; }, p => undefined); // T is fixed, should be string diff --git a/tests/baselines/reference/generatorTypeCheck45.symbols b/tests/baselines/reference/generatorTypeCheck45.symbols new file mode 100644 index 00000000000..06340925fec --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck45.symbols @@ -0,0 +1,27 @@ +=== tests/cases/conformance/es6/yieldExpressions/generatorTypeCheck45.ts === +declare function foo(x: T, fun: () => Iterator<(x: T) => U>, fun2: (y: U) => T): T; +>foo : Symbol(foo, Decl(generatorTypeCheck45.ts, 0, 0)) +>T : Symbol(T, Decl(generatorTypeCheck45.ts, 0, 21)) +>U : Symbol(U, Decl(generatorTypeCheck45.ts, 0, 23)) +>x : Symbol(x, Decl(generatorTypeCheck45.ts, 0, 27)) +>T : Symbol(T, Decl(generatorTypeCheck45.ts, 0, 21)) +>fun : Symbol(fun, Decl(generatorTypeCheck45.ts, 0, 32)) +>Iterator : Symbol(Iterator, Decl(lib.d.ts, 1662, 1)) +>x : Symbol(x, Decl(generatorTypeCheck45.ts, 0, 54)) +>T : Symbol(T, Decl(generatorTypeCheck45.ts, 0, 21)) +>U : Symbol(U, Decl(generatorTypeCheck45.ts, 0, 23)) +>fun2 : Symbol(fun2, Decl(generatorTypeCheck45.ts, 0, 66)) +>y : Symbol(y, Decl(generatorTypeCheck45.ts, 0, 74)) +>U : Symbol(U, Decl(generatorTypeCheck45.ts, 0, 23)) +>T : Symbol(T, Decl(generatorTypeCheck45.ts, 0, 21)) +>T : Symbol(T, Decl(generatorTypeCheck45.ts, 0, 21)) + +foo("", function* () { yield x => x.length }, p => undefined); // T is fixed, should be string +>foo : Symbol(foo, Decl(generatorTypeCheck45.ts, 0, 0)) +>x : Symbol(x, Decl(generatorTypeCheck45.ts, 2, 28)) +>x.length : Symbol(String.length, Decl(lib.d.ts, 414, 19)) +>x : Symbol(x, Decl(generatorTypeCheck45.ts, 2, 28)) +>length : Symbol(String.length, Decl(lib.d.ts, 414, 19)) +>p : Symbol(p, Decl(generatorTypeCheck45.ts, 2, 45)) +>undefined : Symbol(undefined) + diff --git a/tests/baselines/reference/generatorTypeCheck45.types b/tests/baselines/reference/generatorTypeCheck45.types new file mode 100644 index 00000000000..7ea442420d6 --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck45.types @@ -0,0 +1,33 @@ +=== tests/cases/conformance/es6/yieldExpressions/generatorTypeCheck45.ts === +declare function foo(x: T, fun: () => Iterator<(x: T) => U>, fun2: (y: U) => T): T; +>foo : (x: T, fun: () => Iterator<(x: T) => U>, fun2: (y: U) => T) => T +>T : T +>U : U +>x : T +>T : T +>fun : () => Iterator<(x: T) => U> +>Iterator : Iterator +>x : T +>T : T +>U : U +>fun2 : (y: U) => T +>y : U +>U : U +>T : T +>T : T + +foo("", function* () { yield x => x.length }, p => undefined); // T is fixed, should be string +>foo("", function* () { yield x => x.length }, p => undefined) : string +>foo : (x: T, fun: () => Iterator<(x: T) => U>, fun2: (y: U) => T) => T +>"" : string +>function* () { yield x => x.length } : () => IterableIterator<(x: string) => number> +>yield x => x.length : any +>x => x.length : (x: string) => number +>x : string +>x.length : number +>x : string +>length : number +>p => undefined : (p: number) => any +>p : number +>undefined : undefined + diff --git a/tests/baselines/reference/generatorTypeCheck46.js b/tests/baselines/reference/generatorTypeCheck46.js new file mode 100644 index 00000000000..0270f9e3a33 --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck46.js @@ -0,0 +1,19 @@ +//// [generatorTypeCheck46.ts] +declare function foo(x: T, fun: () => Iterable<(x: T) => U>, fun2: (y: U) => T): T; + +foo("", function* () { + yield* { + *[Symbol.iterator]() { + yield x => x.length + } + } +}, p => undefined); // T is fixed, should be string + +//// [generatorTypeCheck46.js] +foo("", function* () { + yield* { + *[Symbol.iterator]() { + yield x => x.length; + } + }; +}, p => undefined); // T is fixed, should be string diff --git a/tests/baselines/reference/generatorTypeCheck46.symbols b/tests/baselines/reference/generatorTypeCheck46.symbols new file mode 100644 index 00000000000..aa0b237d1f2 --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck46.symbols @@ -0,0 +1,38 @@ +=== tests/cases/conformance/es6/yieldExpressions/generatorTypeCheck46.ts === +declare function foo(x: T, fun: () => Iterable<(x: T) => U>, fun2: (y: U) => T): T; +>foo : Symbol(foo, Decl(generatorTypeCheck46.ts, 0, 0)) +>T : Symbol(T, Decl(generatorTypeCheck46.ts, 0, 21)) +>U : Symbol(U, Decl(generatorTypeCheck46.ts, 0, 23)) +>x : Symbol(x, Decl(generatorTypeCheck46.ts, 0, 27)) +>T : Symbol(T, Decl(generatorTypeCheck46.ts, 0, 21)) +>fun : Symbol(fun, Decl(generatorTypeCheck46.ts, 0, 32)) +>Iterable : Symbol(Iterable, Decl(lib.d.ts, 1668, 1)) +>x : Symbol(x, Decl(generatorTypeCheck46.ts, 0, 54)) +>T : Symbol(T, Decl(generatorTypeCheck46.ts, 0, 21)) +>U : Symbol(U, Decl(generatorTypeCheck46.ts, 0, 23)) +>fun2 : Symbol(fun2, Decl(generatorTypeCheck46.ts, 0, 66)) +>y : Symbol(y, Decl(generatorTypeCheck46.ts, 0, 74)) +>U : Symbol(U, Decl(generatorTypeCheck46.ts, 0, 23)) +>T : Symbol(T, Decl(generatorTypeCheck46.ts, 0, 21)) +>T : Symbol(T, Decl(generatorTypeCheck46.ts, 0, 21)) + +foo("", function* () { +>foo : Symbol(foo, Decl(generatorTypeCheck46.ts, 0, 0)) + + yield* { + *[Symbol.iterator]() { +>Symbol.iterator : Symbol(SymbolConstructor.iterator, Decl(lib.d.ts, 1236, 31)) +>Symbol : Symbol(Symbol, Decl(lib.d.ts, 1186, 52), Decl(lib.d.ts, 1292, 11)) +>iterator : Symbol(SymbolConstructor.iterator, Decl(lib.d.ts, 1236, 31)) + + yield x => x.length +>x : Symbol(x, Decl(generatorTypeCheck46.ts, 5, 17)) +>x.length : Symbol(String.length, Decl(lib.d.ts, 414, 19)) +>x : Symbol(x, Decl(generatorTypeCheck46.ts, 5, 17)) +>length : Symbol(String.length, Decl(lib.d.ts, 414, 19)) + } + } +}, p => undefined); // T is fixed, should be string +>p : Symbol(p, Decl(generatorTypeCheck46.ts, 8, 2)) +>undefined : Symbol(undefined) + diff --git a/tests/baselines/reference/generatorTypeCheck46.types b/tests/baselines/reference/generatorTypeCheck46.types new file mode 100644 index 00000000000..daf0d67b6ec --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck46.types @@ -0,0 +1,47 @@ +=== tests/cases/conformance/es6/yieldExpressions/generatorTypeCheck46.ts === +declare function foo(x: T, fun: () => Iterable<(x: T) => U>, fun2: (y: U) => T): T; +>foo : (x: T, fun: () => Iterable<(x: T) => U>, fun2: (y: U) => T) => T +>T : T +>U : U +>x : T +>T : T +>fun : () => Iterable<(x: T) => U> +>Iterable : Iterable +>x : T +>T : T +>U : U +>fun2 : (y: U) => T +>y : U +>U : U +>T : T +>T : T + +foo("", function* () { +>foo("", function* () { yield* { *[Symbol.iterator]() { yield x => x.length } }}, p => undefined) : string +>foo : (x: T, fun: () => Iterable<(x: T) => U>, fun2: (y: U) => T) => T +>"" : string +>function* () { yield* { *[Symbol.iterator]() { yield x => x.length } }} : () => IterableIterator<(x: string) => number> + + yield* { +>yield* { *[Symbol.iterator]() { yield x => x.length } } : any +>{ *[Symbol.iterator]() { yield x => x.length } } : { [Symbol.iterator](): IterableIterator<(x: string) => number>; } + + *[Symbol.iterator]() { +>Symbol.iterator : symbol +>Symbol : SymbolConstructor +>iterator : symbol + + yield x => x.length +>yield x => x.length : any +>x => x.length : (x: string) => number +>x : string +>x.length : number +>x : string +>length : number + } + } +}, p => undefined); // T is fixed, should be string +>p => undefined : (p: number) => any +>p : number +>undefined : undefined + diff --git a/tests/baselines/reference/generatorTypeCheck47.errors.txt b/tests/baselines/reference/generatorTypeCheck47.errors.txt new file mode 100644 index 00000000000..f5264f7ce96 --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck47.errors.txt @@ -0,0 +1,8 @@ +tests/cases/conformance/es6/yieldExpressions/generatorTypeCheck47.ts(2,9): error TS7025: Generator implicitly has type 'IterableIterator' because it does not yield any values. Consider supplying a return type. + + +==== tests/cases/conformance/es6/yieldExpressions/generatorTypeCheck47.ts (1 errors) ==== + + function* g() { } + ~ +!!! error TS7025: Generator implicitly has type 'IterableIterator' because it does not yield any values. Consider supplying a return type. \ No newline at end of file diff --git a/tests/baselines/reference/generatorTypeCheck47.js b/tests/baselines/reference/generatorTypeCheck47.js new file mode 100644 index 00000000000..b06fb96b435 --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck47.js @@ -0,0 +1,6 @@ +//// [generatorTypeCheck47.ts] + +function* g() { } + +//// [generatorTypeCheck47.js] +function* g() { } diff --git a/tests/baselines/reference/generatorTypeCheck48.errors.txt b/tests/baselines/reference/generatorTypeCheck48.errors.txt new file mode 100644 index 00000000000..c91626cd813 --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck48.errors.txt @@ -0,0 +1,10 @@ +tests/cases/conformance/es6/yieldExpressions/generatorTypeCheck48.ts(2,9): error TS7025: Generator implicitly has type 'IterableIterator' because it does not yield any values. Consider supplying a return type. + + +==== tests/cases/conformance/es6/yieldExpressions/generatorTypeCheck48.ts (1 errors) ==== + + function* g() { + ~ +!!! error TS7025: Generator implicitly has type 'IterableIterator' because it does not yield any values. Consider supplying a return type. + yield; + } \ No newline at end of file diff --git a/tests/baselines/reference/generatorTypeCheck48.js b/tests/baselines/reference/generatorTypeCheck48.js new file mode 100644 index 00000000000..579d6dcf0e1 --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck48.js @@ -0,0 +1,10 @@ +//// [generatorTypeCheck48.ts] + +function* g() { + yield; +} + +//// [generatorTypeCheck48.js] +function* g() { + yield; +} diff --git a/tests/baselines/reference/generatorTypeCheck49.js b/tests/baselines/reference/generatorTypeCheck49.js new file mode 100644 index 00000000000..b544c7e4225 --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck49.js @@ -0,0 +1,10 @@ +//// [generatorTypeCheck49.ts] + +function* g() { + yield 0; +} + +//// [generatorTypeCheck49.js] +function* g() { + yield 0; +} diff --git a/tests/baselines/reference/generatorTypeCheck49.symbols b/tests/baselines/reference/generatorTypeCheck49.symbols new file mode 100644 index 00000000000..d24deed3d80 --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck49.symbols @@ -0,0 +1,7 @@ +=== tests/cases/conformance/es6/yieldExpressions/generatorTypeCheck49.ts === + +function* g() { +>g : Symbol(g, Decl(generatorTypeCheck49.ts, 0, 0)) + + yield 0; +} diff --git a/tests/baselines/reference/generatorTypeCheck49.types b/tests/baselines/reference/generatorTypeCheck49.types new file mode 100644 index 00000000000..f56cca33438 --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck49.types @@ -0,0 +1,9 @@ +=== tests/cases/conformance/es6/yieldExpressions/generatorTypeCheck49.ts === + +function* g() { +>g : () => IterableIterator + + yield 0; +>yield 0 : any +>0 : number +} diff --git a/tests/baselines/reference/generatorTypeCheck5.js b/tests/baselines/reference/generatorTypeCheck5.js new file mode 100644 index 00000000000..1acfc110578 --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck5.js @@ -0,0 +1,5 @@ +//// [generatorTypeCheck5.ts] +function* g1(): any { } + +//// [generatorTypeCheck5.js] +function* g1() { } diff --git a/tests/baselines/reference/generatorTypeCheck5.symbols b/tests/baselines/reference/generatorTypeCheck5.symbols new file mode 100644 index 00000000000..3f889e3cadf --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck5.symbols @@ -0,0 +1,4 @@ +=== tests/cases/conformance/es6/yieldExpressions/generatorTypeCheck5.ts === +function* g1(): any { } +>g1 : Symbol(g1, Decl(generatorTypeCheck5.ts, 0, 0)) + diff --git a/tests/baselines/reference/generatorTypeCheck5.types b/tests/baselines/reference/generatorTypeCheck5.types new file mode 100644 index 00000000000..6918a00663c --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck5.types @@ -0,0 +1,4 @@ +=== tests/cases/conformance/es6/yieldExpressions/generatorTypeCheck5.ts === +function* g1(): any { } +>g1 : () => any + diff --git a/tests/baselines/reference/generatorTypeCheck50.js b/tests/baselines/reference/generatorTypeCheck50.js new file mode 100644 index 00000000000..856e3867ab6 --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck50.js @@ -0,0 +1,10 @@ +//// [generatorTypeCheck50.ts] + +function* g() { + yield yield; +} + +//// [generatorTypeCheck50.js] +function* g() { + yield yield; +} diff --git a/tests/baselines/reference/generatorTypeCheck50.symbols b/tests/baselines/reference/generatorTypeCheck50.symbols new file mode 100644 index 00000000000..412a1ac1ea7 --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck50.symbols @@ -0,0 +1,7 @@ +=== tests/cases/conformance/es6/yieldExpressions/generatorTypeCheck50.ts === + +function* g() { +>g : Symbol(g, Decl(generatorTypeCheck50.ts, 0, 0)) + + yield yield; +} diff --git a/tests/baselines/reference/generatorTypeCheck50.types b/tests/baselines/reference/generatorTypeCheck50.types new file mode 100644 index 00000000000..342d7406dce --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck50.types @@ -0,0 +1,9 @@ +=== tests/cases/conformance/es6/yieldExpressions/generatorTypeCheck50.ts === + +function* g() { +>g : () => IterableIterator + + yield yield; +>yield yield : any +>yield : any +} diff --git a/tests/baselines/reference/generatorTypeCheck51.errors.txt b/tests/baselines/reference/generatorTypeCheck51.errors.txt new file mode 100644 index 00000000000..f4fc5723a5e --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck51.errors.txt @@ -0,0 +1,12 @@ +tests/cases/conformance/es6/yieldExpressions/generatorTypeCheck51.ts(2,9): error TS7025: Generator implicitly has type 'IterableIterator' because it does not yield any values. Consider supplying a return type. + + +==== tests/cases/conformance/es6/yieldExpressions/generatorTypeCheck51.ts (1 errors) ==== + + function* g() { + ~ +!!! error TS7025: Generator implicitly has type 'IterableIterator' because it does not yield any values. Consider supplying a return type. + function* h() { + yield 0; + } + } \ No newline at end of file diff --git a/tests/baselines/reference/generatorTypeCheck51.js b/tests/baselines/reference/generatorTypeCheck51.js new file mode 100644 index 00000000000..f3519065c3d --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck51.js @@ -0,0 +1,14 @@ +//// [generatorTypeCheck51.ts] + +function* g() { + function* h() { + yield 0; + } +} + +//// [generatorTypeCheck51.js] +function* g() { + function* h() { + yield 0; + } +} diff --git a/tests/baselines/reference/generatorTypeCheck52.errors.txt b/tests/baselines/reference/generatorTypeCheck52.errors.txt new file mode 100644 index 00000000000..8dc280bb8c9 --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck52.errors.txt @@ -0,0 +1,12 @@ +tests/cases/conformance/es6/yieldExpressions/generatorTypeCheck52.ts(3,11): error TS2504: No best common type exists among yield expressions. + + +==== tests/cases/conformance/es6/yieldExpressions/generatorTypeCheck52.ts (1 errors) ==== + class Foo { x: number } + class Baz { z: number } + function* g() { + ~ +!!! error TS2504: No best common type exists among yield expressions. + yield new Foo; + yield new Baz; + } \ No newline at end of file diff --git a/tests/baselines/reference/generatorTypeCheck52.js b/tests/baselines/reference/generatorTypeCheck52.js new file mode 100644 index 00000000000..751e12c471f --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck52.js @@ -0,0 +1,17 @@ +//// [generatorTypeCheck52.ts] +class Foo { x: number } +class Baz { z: number } +function* g() { + yield new Foo; + yield new Baz; +} + +//// [generatorTypeCheck52.js] +class Foo { +} +class Baz { +} +function* g() { + yield new Foo; + yield new Baz; +} diff --git a/tests/baselines/reference/generatorTypeCheck53.errors.txt b/tests/baselines/reference/generatorTypeCheck53.errors.txt new file mode 100644 index 00000000000..ee3512f34c5 --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck53.errors.txt @@ -0,0 +1,12 @@ +tests/cases/conformance/es6/yieldExpressions/generatorTypeCheck53.ts(3,11): error TS2504: No best common type exists among yield expressions. + + +==== tests/cases/conformance/es6/yieldExpressions/generatorTypeCheck53.ts (1 errors) ==== + class Foo { x: number } + class Baz { z: number } + function* g() { + ~ +!!! error TS2504: No best common type exists among yield expressions. + yield new Foo; + yield* [new Baz]; + } \ No newline at end of file diff --git a/tests/baselines/reference/generatorTypeCheck53.js b/tests/baselines/reference/generatorTypeCheck53.js new file mode 100644 index 00000000000..f26b3b60806 --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck53.js @@ -0,0 +1,17 @@ +//// [generatorTypeCheck53.ts] +class Foo { x: number } +class Baz { z: number } +function* g() { + yield new Foo; + yield* [new Baz]; +} + +//// [generatorTypeCheck53.js] +class Foo { +} +class Baz { +} +function* g() { + yield new Foo; + yield* [new Baz]; +} diff --git a/tests/baselines/reference/generatorTypeCheck54.errors.txt b/tests/baselines/reference/generatorTypeCheck54.errors.txt new file mode 100644 index 00000000000..de22dbfc6e8 --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck54.errors.txt @@ -0,0 +1,12 @@ +tests/cases/conformance/es6/yieldExpressions/generatorTypeCheck54.ts(3,11): error TS2504: No best common type exists among yield expressions. + + +==== tests/cases/conformance/es6/yieldExpressions/generatorTypeCheck54.ts (1 errors) ==== + class Foo { x: number } + class Baz { z: number } + function* g() { + ~ +!!! error TS2504: No best common type exists among yield expressions. + yield* [new Foo]; + yield* [new Baz]; + } \ No newline at end of file diff --git a/tests/baselines/reference/generatorTypeCheck54.js b/tests/baselines/reference/generatorTypeCheck54.js new file mode 100644 index 00000000000..f53215404ef --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck54.js @@ -0,0 +1,17 @@ +//// [generatorTypeCheck54.ts] +class Foo { x: number } +class Baz { z: number } +function* g() { + yield* [new Foo]; + yield* [new Baz]; +} + +//// [generatorTypeCheck54.js] +class Foo { +} +class Baz { +} +function* g() { + yield* [new Foo]; + yield* [new Baz]; +} diff --git a/tests/baselines/reference/generatorTypeCheck55.errors.txt b/tests/baselines/reference/generatorTypeCheck55.errors.txt new file mode 100644 index 00000000000..0846d1c28ad --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck55.errors.txt @@ -0,0 +1,9 @@ +tests/cases/conformance/es6/yieldExpressions/generatorTypeCheck55.ts(2,19): error TS9003: 'class' expressions are not currently supported. + + +==== tests/cases/conformance/es6/yieldExpressions/generatorTypeCheck55.ts (1 errors) ==== + function* g() { + var x = class C extends (yield) {}; + ~ +!!! error TS9003: 'class' expressions are not currently supported. + } \ No newline at end of file diff --git a/tests/baselines/reference/generatorTypeCheck55.js b/tests/baselines/reference/generatorTypeCheck55.js new file mode 100644 index 00000000000..dd7cd33af29 --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck55.js @@ -0,0 +1,11 @@ +//// [generatorTypeCheck55.ts] +function* g() { + var x = class C extends (yield) {}; +} + +//// [generatorTypeCheck55.js] +function* g() { + var x = class C extends (yield) { + } + ; +} diff --git a/tests/baselines/reference/generatorTypeCheck56.errors.txt b/tests/baselines/reference/generatorTypeCheck56.errors.txt new file mode 100644 index 00000000000..99e3b00de41 --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck56.errors.txt @@ -0,0 +1,16 @@ +tests/cases/conformance/es6/yieldExpressions/generatorTypeCheck56.ts(2,19): error TS9003: 'class' expressions are not currently supported. +tests/cases/conformance/es6/yieldExpressions/generatorTypeCheck56.ts(3,11): error TS1163: A 'yield' expression is only allowed in a generator body. + + +==== tests/cases/conformance/es6/yieldExpressions/generatorTypeCheck56.ts (2 errors) ==== + function* g() { + var x = class C { + ~ +!!! error TS9003: 'class' expressions are not currently supported. + *[yield 0]() { + ~~~~~ +!!! error TS1163: A 'yield' expression is only allowed in a generator body. + yield 0; + } + }; + } \ No newline at end of file diff --git a/tests/baselines/reference/generatorTypeCheck56.js b/tests/baselines/reference/generatorTypeCheck56.js new file mode 100644 index 00000000000..c1b0f98f5e7 --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck56.js @@ -0,0 +1,18 @@ +//// [generatorTypeCheck56.ts] +function* g() { + var x = class C { + *[yield 0]() { + yield 0; + } + }; +} + +//// [generatorTypeCheck56.js] +function* g() { + var x = class C { + *[yield 0]() { + yield 0; + } + } + ; +} diff --git a/tests/baselines/reference/generatorTypeCheck57.errors.txt b/tests/baselines/reference/generatorTypeCheck57.errors.txt new file mode 100644 index 00000000000..aa39e534d62 --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck57.errors.txt @@ -0,0 +1,11 @@ +tests/cases/conformance/es6/yieldExpressions/generatorTypeCheck57.ts(3,13): error TS1163: A 'yield' expression is only allowed in a generator body. + + +==== tests/cases/conformance/es6/yieldExpressions/generatorTypeCheck57.ts (1 errors) ==== + function* g() { + class C { + x = yield 0; + ~~~~~ +!!! error TS1163: A 'yield' expression is only allowed in a generator body. + }; + } \ No newline at end of file diff --git a/tests/baselines/reference/generatorTypeCheck57.js b/tests/baselines/reference/generatorTypeCheck57.js new file mode 100644 index 00000000000..740df492867 --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck57.js @@ -0,0 +1,16 @@ +//// [generatorTypeCheck57.ts] +function* g() { + class C { + x = yield 0; + }; +} + +//// [generatorTypeCheck57.js] +function* g() { + class C { + constructor() { + this.x = yield 0; + } + } + ; +} diff --git a/tests/baselines/reference/generatorTypeCheck58.errors.txt b/tests/baselines/reference/generatorTypeCheck58.errors.txt new file mode 100644 index 00000000000..7407c83b34b --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck58.errors.txt @@ -0,0 +1,11 @@ +tests/cases/conformance/es6/yieldExpressions/generatorTypeCheck58.ts(3,20): error TS1163: A 'yield' expression is only allowed in a generator body. + + +==== tests/cases/conformance/es6/yieldExpressions/generatorTypeCheck58.ts (1 errors) ==== + function* g() { + class C { + static x = yield 0; + ~~~~~ +!!! error TS1163: A 'yield' expression is only allowed in a generator body. + }; + } \ No newline at end of file diff --git a/tests/baselines/reference/generatorTypeCheck58.js b/tests/baselines/reference/generatorTypeCheck58.js new file mode 100644 index 00000000000..925fc2b76d2 --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck58.js @@ -0,0 +1,14 @@ +//// [generatorTypeCheck58.ts] +function* g() { + class C { + static x = yield 0; + }; +} + +//// [generatorTypeCheck58.js] +function* g() { + class C { + } + C.x = yield 0; + ; +} diff --git a/tests/baselines/reference/generatorTypeCheck59.errors.txt b/tests/baselines/reference/generatorTypeCheck59.errors.txt new file mode 100644 index 00000000000..d8d532a430a --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck59.errors.txt @@ -0,0 +1,16 @@ +tests/cases/conformance/es6/yieldExpressions/generatorTypeCheck59.ts(3,9): error TS1219: Experimental support for decorators is a feature that is subject to change in a future release. Specify '--experimentalDecorators' to remove this warning. +tests/cases/conformance/es6/yieldExpressions/generatorTypeCheck59.ts(3,11): error TS1163: A 'yield' expression is only allowed in a generator body. + + +==== tests/cases/conformance/es6/yieldExpressions/generatorTypeCheck59.ts (2 errors) ==== + function* g() { + class C { + @(yield "") + ~~~~~~~~~~~ + ~~~~~ +!!! error TS1163: A 'yield' expression is only allowed in a generator body. + m() { } + ~~~~~~~~~~~~~~~ +!!! error TS1219: Experimental support for decorators is a feature that is subject to change in a future release. Specify '--experimentalDecorators' to remove this warning. + }; + } \ No newline at end of file diff --git a/tests/baselines/reference/generatorTypeCheck59.js b/tests/baselines/reference/generatorTypeCheck59.js new file mode 100644 index 00000000000..5b3b70386f8 --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck59.js @@ -0,0 +1,27 @@ +//// [generatorTypeCheck59.ts] +function* g() { + class C { + @(yield "") + m() { } + }; +} + +//// [generatorTypeCheck59.js] +var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") return Reflect.decorate(decorators, target, key, desc); + switch (arguments.length) { + case 2: return decorators.reduceRight(function(o, d) { return (d && d(o)) || o; }, target); + case 3: return decorators.reduceRight(function(o, d) { return (d && d(target, key)), void 0; }, void 0); + case 4: return decorators.reduceRight(function(o, d) { return (d && d(target, key, o)) || o; }, desc); + } +}; +function* g() { + class C { + m() { } + } + Object.defineProperty(C.prototype, "m", + __decorate([ + (yield "") + ], C.prototype, "m", Object.getOwnPropertyDescriptor(C.prototype, "m"))); + ; +} diff --git a/tests/baselines/reference/generatorTypeCheck6.errors.txt b/tests/baselines/reference/generatorTypeCheck6.errors.txt new file mode 100644 index 00000000000..35f2cc2016d --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck6.errors.txt @@ -0,0 +1,7 @@ +tests/cases/conformance/es6/yieldExpressions/generatorTypeCheck6.ts(1,17): error TS2322: Type 'IterableIterator' is not assignable to type 'number'. + + +==== tests/cases/conformance/es6/yieldExpressions/generatorTypeCheck6.ts (1 errors) ==== + function* g1(): number { } + ~~~~~~ +!!! error TS2322: Type 'IterableIterator' is not assignable to type 'number'. \ No newline at end of file diff --git a/tests/baselines/reference/generatorTypeCheck6.js b/tests/baselines/reference/generatorTypeCheck6.js new file mode 100644 index 00000000000..de0f92f77f1 --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck6.js @@ -0,0 +1,5 @@ +//// [generatorTypeCheck6.ts] +function* g1(): number { } + +//// [generatorTypeCheck6.js] +function* g1() { } diff --git a/tests/baselines/reference/generatorTypeCheck60.errors.txt b/tests/baselines/reference/generatorTypeCheck60.errors.txt new file mode 100644 index 00000000000..5330cd186b7 --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck60.errors.txt @@ -0,0 +1,12 @@ +tests/cases/conformance/es6/yieldExpressions/generatorTypeCheck60.ts(2,21): error TS2507: Type 'any' is not a constructor function type. +tests/cases/conformance/es6/yieldExpressions/generatorTypeCheck60.ts(2,22): error TS1163: A 'yield' expression is only allowed in a generator body. + + +==== tests/cases/conformance/es6/yieldExpressions/generatorTypeCheck60.ts (2 errors) ==== + function* g() { + class C extends (yield) {}; + ~~~~~~~ +!!! error TS2507: Type 'any' is not a constructor function type. + ~~~~~ +!!! error TS1163: A 'yield' expression is only allowed in a generator body. + } \ No newline at end of file diff --git a/tests/baselines/reference/generatorTypeCheck60.js b/tests/baselines/reference/generatorTypeCheck60.js new file mode 100644 index 00000000000..cb7c65cf081 --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck60.js @@ -0,0 +1,11 @@ +//// [generatorTypeCheck60.ts] +function* g() { + class C extends (yield) {}; +} + +//// [generatorTypeCheck60.js] +function* g() { + class C extends (yield) { + } + ; +} diff --git a/tests/baselines/reference/generatorTypeCheck61.errors.txt b/tests/baselines/reference/generatorTypeCheck61.errors.txt new file mode 100644 index 00000000000..b38e96d31ce --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck61.errors.txt @@ -0,0 +1,13 @@ +tests/cases/conformance/es6/yieldExpressions/generatorTypeCheck61.ts(2,7): error TS1163: A 'yield' expression is only allowed in a generator body. +tests/cases/conformance/es6/yieldExpressions/generatorTypeCheck61.ts(3,11): error TS1219: Experimental support for decorators is a feature that is subject to change in a future release. Specify '--experimentalDecorators' to remove this warning. + + +==== tests/cases/conformance/es6/yieldExpressions/generatorTypeCheck61.ts (2 errors) ==== + function * g() { + @(yield 0) + ~~~~~ +!!! error TS1163: A 'yield' expression is only allowed in a generator body. + class C {}; + ~ +!!! error TS1219: Experimental support for decorators is a feature that is subject to change in a future release. Specify '--experimentalDecorators' to remove this warning. + } \ No newline at end of file diff --git a/tests/baselines/reference/generatorTypeCheck61.js b/tests/baselines/reference/generatorTypeCheck61.js new file mode 100644 index 00000000000..9e2f067f9fb --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck61.js @@ -0,0 +1,23 @@ +//// [generatorTypeCheck61.ts] +function * g() { + @(yield 0) + class C {}; +} + +//// [generatorTypeCheck61.js] +var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") return Reflect.decorate(decorators, target, key, desc); + switch (arguments.length) { + case 2: return decorators.reduceRight(function(o, d) { return (d && d(o)) || o; }, target); + case 3: return decorators.reduceRight(function(o, d) { return (d && d(target, key)), void 0; }, void 0); + case 4: return decorators.reduceRight(function(o, d) { return (d && d(target, key, o)) || o; }, desc); + } +}; +function* g() { + let C = class { + }; + C = __decorate([ + (yield 0) + ], C); + ; +} diff --git a/tests/baselines/reference/generatorTypeCheck7.errors.txt b/tests/baselines/reference/generatorTypeCheck7.errors.txt new file mode 100644 index 00000000000..2653ecf8cd5 --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck7.errors.txt @@ -0,0 +1,12 @@ +tests/cases/conformance/es6/yieldExpressions/generatorTypeCheck7.ts(4,17): error TS2322: Type 'IterableIterator' is not assignable to type 'WeirdIter'. + Property 'hello' is missing in type 'IterableIterator'. + + +==== tests/cases/conformance/es6/yieldExpressions/generatorTypeCheck7.ts (1 errors) ==== + interface WeirdIter extends IterableIterator { + hello: string; + } + function* g1(): WeirdIter { } + ~~~~~~~~~ +!!! error TS2322: Type 'IterableIterator' is not assignable to type 'WeirdIter'. +!!! error TS2322: Property 'hello' is missing in type 'IterableIterator'. \ No newline at end of file diff --git a/tests/baselines/reference/generatorTypeCheck7.js b/tests/baselines/reference/generatorTypeCheck7.js new file mode 100644 index 00000000000..c2d47f9483c --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck7.js @@ -0,0 +1,8 @@ +//// [generatorTypeCheck7.ts] +interface WeirdIter extends IterableIterator { + hello: string; +} +function* g1(): WeirdIter { } + +//// [generatorTypeCheck7.js] +function* g1() { } diff --git a/tests/baselines/reference/generatorTypeCheck8.errors.txt b/tests/baselines/reference/generatorTypeCheck8.errors.txt new file mode 100644 index 00000000000..cedfecda60b --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck8.errors.txt @@ -0,0 +1,16 @@ +tests/cases/conformance/es6/yieldExpressions/generatorTypeCheck8.ts(2,17): error TS2322: Type 'IterableIterator' is not assignable to type 'BadGenerator'. + Types of property 'next' are incompatible. + Type '(value?: any) => IteratorResult' is not assignable to type '(value?: any) => IteratorResult'. + Type 'IteratorResult' is not assignable to type 'IteratorResult'. + Type 'string' is not assignable to type 'number'. + + +==== tests/cases/conformance/es6/yieldExpressions/generatorTypeCheck8.ts (1 errors) ==== + interface BadGenerator extends Iterator, Iterable { } + function* g3(): BadGenerator { } + ~~~~~~~~~~~~ +!!! error TS2322: Type 'IterableIterator' is not assignable to type 'BadGenerator'. +!!! error TS2322: Types of property 'next' are incompatible. +!!! error TS2322: Type '(value?: any) => IteratorResult' is not assignable to type '(value?: any) => IteratorResult'. +!!! error TS2322: Type 'IteratorResult' is not assignable to type 'IteratorResult'. +!!! error TS2322: Type 'string' is not assignable to type 'number'. \ No newline at end of file diff --git a/tests/baselines/reference/generatorTypeCheck8.js b/tests/baselines/reference/generatorTypeCheck8.js new file mode 100644 index 00000000000..97058c2eaa0 --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck8.js @@ -0,0 +1,6 @@ +//// [generatorTypeCheck8.ts] +interface BadGenerator extends Iterator, Iterable { } +function* g3(): BadGenerator { } + +//// [generatorTypeCheck8.js] +function* g3() { } diff --git a/tests/baselines/reference/generatorTypeCheck9.errors.txt b/tests/baselines/reference/generatorTypeCheck9.errors.txt new file mode 100644 index 00000000000..3b4e0c654fb --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck9.errors.txt @@ -0,0 +1,7 @@ +tests/cases/conformance/es6/yieldExpressions/generatorTypeCheck9.ts(1,17): error TS2505: A generator cannot have a 'void' type annotation. + + +==== tests/cases/conformance/es6/yieldExpressions/generatorTypeCheck9.ts (1 errors) ==== + function* g3(): void { } + ~~~~ +!!! error TS2505: A generator cannot have a 'void' type annotation. \ No newline at end of file diff --git a/tests/baselines/reference/generatorTypeCheck9.js b/tests/baselines/reference/generatorTypeCheck9.js new file mode 100644 index 00000000000..3bdeec0a4a9 --- /dev/null +++ b/tests/baselines/reference/generatorTypeCheck9.js @@ -0,0 +1,5 @@ +//// [generatorTypeCheck9.ts] +function* g3(): void { } + +//// [generatorTypeCheck9.js] +function* g3() { } diff --git a/tests/baselines/reference/genericBaseClassLiteralProperty.js b/tests/baselines/reference/genericBaseClassLiteralProperty.js index 5e365531461..f8a5f78e753 100644 --- a/tests/baselines/reference/genericBaseClassLiteralProperty.js +++ b/tests/baselines/reference/genericBaseClassLiteralProperty.js @@ -16,8 +16,7 @@ class SubClass extends BaseClass { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var BaseClass = (function () { function BaseClass() { diff --git a/tests/baselines/reference/genericBaseClassLiteralProperty.types b/tests/baselines/reference/genericBaseClassLiteralProperty.types index 51246348ded..87f1c55c42d 100644 --- a/tests/baselines/reference/genericBaseClassLiteralProperty.types +++ b/tests/baselines/reference/genericBaseClassLiteralProperty.types @@ -14,7 +14,7 @@ class BaseClass { class SubClass extends BaseClass { >SubClass : SubClass ->BaseClass : BaseClass +>BaseClass : BaseClass public Error(): void { >Error : () => void diff --git a/tests/baselines/reference/genericBaseClassLiteralProperty2.js b/tests/baselines/reference/genericBaseClassLiteralProperty2.js index 8a19d857bb6..d5c480955d8 100644 --- a/tests/baselines/reference/genericBaseClassLiteralProperty2.js +++ b/tests/baselines/reference/genericBaseClassLiteralProperty2.js @@ -19,8 +19,7 @@ class DataView2 extends BaseCollection2 { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var CollectionItem2 = (function () { function CollectionItem2() { diff --git a/tests/baselines/reference/genericBaseClassLiteralProperty2.types b/tests/baselines/reference/genericBaseClassLiteralProperty2.types index 4576ffb05de..271aa190037 100644 --- a/tests/baselines/reference/genericBaseClassLiteralProperty2.types +++ b/tests/baselines/reference/genericBaseClassLiteralProperty2.types @@ -24,7 +24,7 @@ class BaseCollection2 { class DataView2 extends BaseCollection2 { >DataView2 : DataView2 ->BaseCollection2 : BaseCollection2 +>BaseCollection2 : BaseCollection2 >CollectionItem2 : CollectionItem2 fillItems(item: CollectionItem2) { diff --git a/tests/baselines/reference/genericCallWithConstraintsTypeArgumentInference.js b/tests/baselines/reference/genericCallWithConstraintsTypeArgumentInference.js index f00468dcbc5..9df55756ee2 100644 --- a/tests/baselines/reference/genericCallWithConstraintsTypeArgumentInference.js +++ b/tests/baselines/reference/genericCallWithConstraintsTypeArgumentInference.js @@ -112,8 +112,7 @@ var r11 = i.foo8(); // Base var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var Base = (function () { function Base() { diff --git a/tests/baselines/reference/genericCallWithObjectTypeArgs2.js b/tests/baselines/reference/genericCallWithObjectTypeArgs2.js index 910e3860b49..bded01ead69 100644 --- a/tests/baselines/reference/genericCallWithObjectTypeArgs2.js +++ b/tests/baselines/reference/genericCallWithObjectTypeArgs2.js @@ -36,8 +36,7 @@ var r4 = f2(i); // Base => Derived var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var Base = (function () { function Base() { diff --git a/tests/baselines/reference/genericCallWithObjectTypeArgsAndConstraints2.js b/tests/baselines/reference/genericCallWithObjectTypeArgsAndConstraints2.js index 9cb2425f9d0..96c2f9300db 100644 --- a/tests/baselines/reference/genericCallWithObjectTypeArgsAndConstraints2.js +++ b/tests/baselines/reference/genericCallWithObjectTypeArgsAndConstraints2.js @@ -44,8 +44,7 @@ var r7 = f3(null, x => x); // any var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var Base = (function () { function Base() { diff --git a/tests/baselines/reference/genericCallWithObjectTypeArgsAndConstraints3.js b/tests/baselines/reference/genericCallWithObjectTypeArgsAndConstraints3.js index 3c5a4c24b53..daaa2f5c0eb 100644 --- a/tests/baselines/reference/genericCallWithObjectTypeArgsAndConstraints3.js +++ b/tests/baselines/reference/genericCallWithObjectTypeArgsAndConstraints3.js @@ -42,8 +42,7 @@ var r6 = f3(x => x, null); var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var Base = (function () { function Base() { diff --git a/tests/baselines/reference/genericCallbacksAndClassHierarchy.js b/tests/baselines/reference/genericCallbacksAndClassHierarchy.js index 16abb2683e7..093757d513d 100644 --- a/tests/baselines/reference/genericCallbacksAndClassHierarchy.js +++ b/tests/baselines/reference/genericCallbacksAndClassHierarchy.js @@ -27,8 +27,7 @@ module M { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var M; (function (M) { diff --git a/tests/baselines/reference/genericCallbacksAndClassHierarchy.types b/tests/baselines/reference/genericCallbacksAndClassHierarchy.types index 97e584dca3f..cb12737a937 100644 --- a/tests/baselines/reference/genericCallbacksAndClassHierarchy.types +++ b/tests/baselines/reference/genericCallbacksAndClassHierarchy.types @@ -31,7 +31,7 @@ module M { export class B extends C1> { } >B : B >T : T ->C1 : C1 +>C1 : C1> >A : A >T : T diff --git a/tests/baselines/reference/genericClassInheritsConstructorFromNonGenericClass.js b/tests/baselines/reference/genericClassInheritsConstructorFromNonGenericClass.js index 22bb975e7d7..f77f60a2fb9 100644 --- a/tests/baselines/reference/genericClassInheritsConstructorFromNonGenericClass.js +++ b/tests/baselines/reference/genericClassInheritsConstructorFromNonGenericClass.js @@ -9,8 +9,7 @@ class C { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var A = (function (_super) { __extends(A, _super); diff --git a/tests/baselines/reference/genericClassInheritsConstructorFromNonGenericClass.types b/tests/baselines/reference/genericClassInheritsConstructorFromNonGenericClass.types index 800b215f123..28daf6d38ee 100644 --- a/tests/baselines/reference/genericClassInheritsConstructorFromNonGenericClass.types +++ b/tests/baselines/reference/genericClassInheritsConstructorFromNonGenericClass.types @@ -1,7 +1,7 @@ === tests/cases/compiler/genericClassInheritsConstructorFromNonGenericClass.ts === class A extends B { } >A : A ->B : B +>B : B class B extends C { } >B : B diff --git a/tests/baselines/reference/genericClassPropertyInheritanceSpecialization.js b/tests/baselines/reference/genericClassPropertyInheritanceSpecialization.js index 43d1e53a615..69261747244 100644 --- a/tests/baselines/reference/genericClassPropertyInheritanceSpecialization.js +++ b/tests/baselines/reference/genericClassPropertyInheritanceSpecialization.js @@ -79,8 +79,7 @@ class ViewModel implements Contract { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var Portal; (function (Portal) { diff --git a/tests/baselines/reference/genericClassPropertyInheritanceSpecialization.types b/tests/baselines/reference/genericClassPropertyInheritanceSpecialization.types index 6ba27a66399..88ef74283ae 100644 --- a/tests/baselines/reference/genericClassPropertyInheritanceSpecialization.types +++ b/tests/baselines/reference/genericClassPropertyInheritanceSpecialization.types @@ -192,13 +192,13 @@ module PortalFx.ViewModels.Controls.Validators { export class Validator extends Portal.Controls.Validators.Validator { >Validator : Validator >TValue : TValue ->Portal.Controls.Validators.Validator : any +>Portal.Controls.Validators.Validator : Portal.Controls.Validators.Validator >Portal.Controls.Validators : typeof Portal.Controls.Validators >Portal.Controls : typeof Portal.Controls >Portal : typeof Portal >Controls : typeof Portal.Controls >Validators : typeof Portal.Controls.Validators ->Validator : Portal.Controls.Validators.Validator +>Validator : typeof Portal.Controls.Validators.Validator >TValue : TValue constructor(message?: string) { diff --git a/tests/baselines/reference/genericClassStaticMethod.js b/tests/baselines/reference/genericClassStaticMethod.js index 23e1874c0ed..aed721aa7d5 100644 --- a/tests/baselines/reference/genericClassStaticMethod.js +++ b/tests/baselines/reference/genericClassStaticMethod.js @@ -14,8 +14,7 @@ class Bar extends Foo { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var Foo = (function () { function Foo() { diff --git a/tests/baselines/reference/genericClasses3.js b/tests/baselines/reference/genericClasses3.js index 373052d78e3..14ffab2f6f6 100644 --- a/tests/baselines/reference/genericClasses3.js +++ b/tests/baselines/reference/genericClasses3.js @@ -21,8 +21,7 @@ var z = v2.b; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var B = (function () { function B() { diff --git a/tests/baselines/reference/genericConstraintOnExtendedBuiltinTypes.js b/tests/baselines/reference/genericConstraintOnExtendedBuiltinTypes.js index 561c24cd50e..b4e56933775 100644 --- a/tests/baselines/reference/genericConstraintOnExtendedBuiltinTypes.js +++ b/tests/baselines/reference/genericConstraintOnExtendedBuiltinTypes.js @@ -30,8 +30,7 @@ module EndGate.Tweening { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var EndGate; (function (EndGate) { diff --git a/tests/baselines/reference/genericConstraintOnExtendedBuiltinTypes.types b/tests/baselines/reference/genericConstraintOnExtendedBuiltinTypes.types index f1041cfa80f..9a4b209bc97 100644 --- a/tests/baselines/reference/genericConstraintOnExtendedBuiltinTypes.types +++ b/tests/baselines/reference/genericConstraintOnExtendedBuiltinTypes.types @@ -53,7 +53,7 @@ module EndGate.Tweening { export class NumberTween extends Tween{ >NumberTween : NumberTween ->Tween : Tween +>Tween : Tween constructor(from: number) { >from : number diff --git a/tests/baselines/reference/genericConstraintOnExtendedBuiltinTypes2.js b/tests/baselines/reference/genericConstraintOnExtendedBuiltinTypes2.js index 2420e082e3d..54a807a8e87 100644 --- a/tests/baselines/reference/genericConstraintOnExtendedBuiltinTypes2.js +++ b/tests/baselines/reference/genericConstraintOnExtendedBuiltinTypes2.js @@ -29,8 +29,7 @@ module EndGate.Tweening { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var EndGate; (function (EndGate) { diff --git a/tests/baselines/reference/genericConstraintOnExtendedBuiltinTypes2.types b/tests/baselines/reference/genericConstraintOnExtendedBuiltinTypes2.types index 92ffa7c5c03..ba42e42ae0c 100644 --- a/tests/baselines/reference/genericConstraintOnExtendedBuiltinTypes2.types +++ b/tests/baselines/reference/genericConstraintOnExtendedBuiltinTypes2.types @@ -52,7 +52,7 @@ module EndGate.Tweening { export class NumberTween extends Tween{ >NumberTween : NumberTween ->Tween : Tween +>Tween : Tween >Number : Number constructor(from: number) { diff --git a/tests/baselines/reference/genericDerivedTypeWithSpecializedBase.js b/tests/baselines/reference/genericDerivedTypeWithSpecializedBase.js index 69ae509bf54..eb27365ebc5 100644 --- a/tests/baselines/reference/genericDerivedTypeWithSpecializedBase.js +++ b/tests/baselines/reference/genericDerivedTypeWithSpecializedBase.js @@ -16,8 +16,7 @@ x = y; // error var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var A = (function () { function A() { diff --git a/tests/baselines/reference/genericDerivedTypeWithSpecializedBase2.js b/tests/baselines/reference/genericDerivedTypeWithSpecializedBase2.js index 1c4f27b5ebe..be94a778858 100644 --- a/tests/baselines/reference/genericDerivedTypeWithSpecializedBase2.js +++ b/tests/baselines/reference/genericDerivedTypeWithSpecializedBase2.js @@ -16,8 +16,7 @@ x = y; // error var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var A = (function () { function A() { diff --git a/tests/baselines/reference/genericPrototypeProperty2.js b/tests/baselines/reference/genericPrototypeProperty2.js index b91b345481e..cbe33431ca4 100644 --- a/tests/baselines/reference/genericPrototypeProperty2.js +++ b/tests/baselines/reference/genericPrototypeProperty2.js @@ -19,8 +19,7 @@ class MyEventWrapper extends BaseEventWrapper { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var BaseEvent = (function () { function BaseEvent() { diff --git a/tests/baselines/reference/genericPrototypeProperty3.js b/tests/baselines/reference/genericPrototypeProperty3.js index de093886ea4..6447a4e0ac2 100644 --- a/tests/baselines/reference/genericPrototypeProperty3.js +++ b/tests/baselines/reference/genericPrototypeProperty3.js @@ -18,8 +18,7 @@ class MyEventWrapper extends BaseEventWrapper { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var BaseEvent = (function () { function BaseEvent() { diff --git a/tests/baselines/reference/genericRecursiveImplicitConstructorErrors2.js b/tests/baselines/reference/genericRecursiveImplicitConstructorErrors2.js index b73239626d0..a1f7566f1c0 100644 --- a/tests/baselines/reference/genericRecursiveImplicitConstructorErrors2.js +++ b/tests/baselines/reference/genericRecursiveImplicitConstructorErrors2.js @@ -30,8 +30,7 @@ module TypeScript2 { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var TypeScript2; (function (TypeScript2) { diff --git a/tests/baselines/reference/genericRecursiveImplicitConstructorErrors3.errors.txt b/tests/baselines/reference/genericRecursiveImplicitConstructorErrors3.errors.txt index 760d1561113..1a04e356296 100644 --- a/tests/baselines/reference/genericRecursiveImplicitConstructorErrors3.errors.txt +++ b/tests/baselines/reference/genericRecursiveImplicitConstructorErrors3.errors.txt @@ -1,5 +1,4 @@ tests/cases/compiler/genericRecursiveImplicitConstructorErrors3.ts(3,66): error TS2314: Generic type 'MemberName' requires 3 type argument(s). -tests/cases/compiler/genericRecursiveImplicitConstructorErrors3.ts(3,66): error TS2355: A function whose declared type is neither 'void' nor 'any' must return a value or consist of a single 'throw' statement. tests/cases/compiler/genericRecursiveImplicitConstructorErrors3.ts(10,22): error TS2314: Generic type 'PullTypeSymbol' requires 3 type argument(s). tests/cases/compiler/genericRecursiveImplicitConstructorErrors3.ts(12,48): error TS2314: Generic type 'PullSymbol' requires 3 type argument(s). tests/cases/compiler/genericRecursiveImplicitConstructorErrors3.ts(13,31): error TS2314: Generic type 'PullTypeSymbol' requires 3 type argument(s). @@ -8,14 +7,12 @@ tests/cases/compiler/genericRecursiveImplicitConstructorErrors3.ts(18,53): error tests/cases/compiler/genericRecursiveImplicitConstructorErrors3.ts(19,22): error TS2339: Property 'isArray' does not exist on type 'PullTypeSymbol'. -==== tests/cases/compiler/genericRecursiveImplicitConstructorErrors3.ts (8 errors) ==== +==== tests/cases/compiler/genericRecursiveImplicitConstructorErrors3.ts (7 errors) ==== module TypeScript { export class MemberName { static create(arg1: any, arg2?: any, arg3?: any): MemberName { ~~~~~~~~~~ !!! error TS2314: Generic type 'MemberName' requires 3 type argument(s). - ~~~~~~~~~~ -!!! error TS2355: A function whose declared type is neither 'void' nor 'any' must return a value or consist of a single 'throw' statement. } } } diff --git a/tests/baselines/reference/genericRecursiveImplicitConstructorErrors3.js b/tests/baselines/reference/genericRecursiveImplicitConstructorErrors3.js index 0d4a3315acd..a0229e19925 100644 --- a/tests/baselines/reference/genericRecursiveImplicitConstructorErrors3.js +++ b/tests/baselines/reference/genericRecursiveImplicitConstructorErrors3.js @@ -34,8 +34,7 @@ module TypeScript { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var TypeScript; (function (TypeScript) { diff --git a/tests/baselines/reference/genericTypeAliases.js b/tests/baselines/reference/genericTypeAliases.js new file mode 100644 index 00000000000..8218f5c886c --- /dev/null +++ b/tests/baselines/reference/genericTypeAliases.js @@ -0,0 +1,120 @@ +//// [genericTypeAliases.ts] +type Tree = T | { left: Tree, right: Tree }; + +var tree: Tree = { + left: { + left: 0, + right: { + left: 1, + right: 2 + }, + }, + right: 3 +}; + +type Lazy = T | (() => T); + +var ls: Lazy; +ls = "eager"; +ls = () => "lazy"; + +type Foo = T | { x: Foo }; +type Bar = U | { x: Bar }; + +// Deeply instantiated generics +var x: Foo; +var y: Bar; +x = y; +y = x; + +x = "string"; +x = { x: "hello" }; +x = { x: { x: "world" } }; + +var z: Foo; +z = 42; +z = { x: 42 }; +z = { x: { x: 42 } }; + +type Strange = string; // Type parameter not used +var s: Strange; +s = "hello"; + +interface Tuple { + a: A; + b: B; +} + +type Pair = Tuple; + +interface TaggedPair extends Pair { + tag: string; +} + +var p: TaggedPair; +p.a = 1; +p.b = 2; +p.tag = "test"; + +function f() { + type Foo = T | { x: Foo }; + var x: Foo; + return x; +} + +function g() { + type Bar = U | { x: Bar }; + var x: Bar; + return x; +} + +// Deeply instantiated generics +var a = f(); +var b = g(); +a = b; + + +//// [genericTypeAliases.js] +var tree = { + left: { + left: 0, + right: { + left: 1, + right: 2 + } + }, + right: 3 +}; +var ls; +ls = "eager"; +ls = function () { return "lazy"; }; +// Deeply instantiated generics +var x; +var y; +x = y; +y = x; +x = "string"; +x = { x: "hello" }; +x = { x: { x: "world" } }; +var z; +z = 42; +z = { x: 42 }; +z = { x: { x: 42 } }; +var s; +s = "hello"; +var p; +p.a = 1; +p.b = 2; +p.tag = "test"; +function f() { + var x; + return x; +} +function g() { + var x; + return x; +} +// Deeply instantiated generics +var a = f(); +var b = g(); +a = b; diff --git a/tests/baselines/reference/genericTypeAliases.symbols b/tests/baselines/reference/genericTypeAliases.symbols new file mode 100644 index 00000000000..1a1d0e51487 --- /dev/null +++ b/tests/baselines/reference/genericTypeAliases.symbols @@ -0,0 +1,231 @@ +=== tests/cases/conformance/types/typeAliases/genericTypeAliases.ts === +type Tree = T | { left: Tree, right: Tree }; +>Tree : Symbol(Tree, Decl(genericTypeAliases.ts, 0, 0)) +>T : Symbol(T, Decl(genericTypeAliases.ts, 0, 10)) +>T : Symbol(T, Decl(genericTypeAliases.ts, 0, 10)) +>left : Symbol(left, Decl(genericTypeAliases.ts, 0, 20)) +>Tree : Symbol(Tree, Decl(genericTypeAliases.ts, 0, 0)) +>T : Symbol(T, Decl(genericTypeAliases.ts, 0, 10)) +>right : Symbol(right, Decl(genericTypeAliases.ts, 0, 35)) +>Tree : Symbol(Tree, Decl(genericTypeAliases.ts, 0, 0)) +>T : Symbol(T, Decl(genericTypeAliases.ts, 0, 10)) + +var tree: Tree = { +>tree : Symbol(tree, Decl(genericTypeAliases.ts, 2, 3)) +>Tree : Symbol(Tree, Decl(genericTypeAliases.ts, 0, 0)) + + left: { +>left : Symbol(left, Decl(genericTypeAliases.ts, 2, 26)) + + left: 0, +>left : Symbol(left, Decl(genericTypeAliases.ts, 3, 11)) + + right: { +>right : Symbol(right, Decl(genericTypeAliases.ts, 4, 16)) + + left: 1, +>left : Symbol(left, Decl(genericTypeAliases.ts, 5, 16)) + + right: 2 +>right : Symbol(right, Decl(genericTypeAliases.ts, 6, 20)) + + }, + }, + right: 3 +>right : Symbol(right, Decl(genericTypeAliases.ts, 9, 6)) + +}; + +type Lazy = T | (() => T); +>Lazy : Symbol(Lazy, Decl(genericTypeAliases.ts, 11, 2)) +>T : Symbol(T, Decl(genericTypeAliases.ts, 13, 10)) +>T : Symbol(T, Decl(genericTypeAliases.ts, 13, 10)) +>T : Symbol(T, Decl(genericTypeAliases.ts, 13, 10)) + +var ls: Lazy; +>ls : Symbol(ls, Decl(genericTypeAliases.ts, 15, 3)) +>Lazy : Symbol(Lazy, Decl(genericTypeAliases.ts, 11, 2)) + +ls = "eager"; +>ls : Symbol(ls, Decl(genericTypeAliases.ts, 15, 3)) + +ls = () => "lazy"; +>ls : Symbol(ls, Decl(genericTypeAliases.ts, 15, 3)) + +type Foo = T | { x: Foo }; +>Foo : Symbol(Foo, Decl(genericTypeAliases.ts, 17, 18)) +>T : Symbol(T, Decl(genericTypeAliases.ts, 19, 9)) +>T : Symbol(T, Decl(genericTypeAliases.ts, 19, 9)) +>x : Symbol(x, Decl(genericTypeAliases.ts, 19, 19)) +>Foo : Symbol(Foo, Decl(genericTypeAliases.ts, 17, 18)) +>T : Symbol(T, Decl(genericTypeAliases.ts, 19, 9)) + +type Bar = U | { x: Bar }; +>Bar : Symbol(Bar, Decl(genericTypeAliases.ts, 19, 32)) +>U : Symbol(U, Decl(genericTypeAliases.ts, 20, 9)) +>U : Symbol(U, Decl(genericTypeAliases.ts, 20, 9)) +>x : Symbol(x, Decl(genericTypeAliases.ts, 20, 19)) +>Bar : Symbol(Bar, Decl(genericTypeAliases.ts, 19, 32)) +>U : Symbol(U, Decl(genericTypeAliases.ts, 20, 9)) + +// Deeply instantiated generics +var x: Foo; +>x : Symbol(x, Decl(genericTypeAliases.ts, 23, 3)) +>Foo : Symbol(Foo, Decl(genericTypeAliases.ts, 17, 18)) + +var y: Bar; +>y : Symbol(y, Decl(genericTypeAliases.ts, 24, 3)) +>Bar : Symbol(Bar, Decl(genericTypeAliases.ts, 19, 32)) + +x = y; +>x : Symbol(x, Decl(genericTypeAliases.ts, 23, 3)) +>y : Symbol(y, Decl(genericTypeAliases.ts, 24, 3)) + +y = x; +>y : Symbol(y, Decl(genericTypeAliases.ts, 24, 3)) +>x : Symbol(x, Decl(genericTypeAliases.ts, 23, 3)) + +x = "string"; +>x : Symbol(x, Decl(genericTypeAliases.ts, 23, 3)) + +x = { x: "hello" }; +>x : Symbol(x, Decl(genericTypeAliases.ts, 23, 3)) +>x : Symbol(x, Decl(genericTypeAliases.ts, 29, 5)) + +x = { x: { x: "world" } }; +>x : Symbol(x, Decl(genericTypeAliases.ts, 23, 3)) +>x : Symbol(x, Decl(genericTypeAliases.ts, 30, 5)) +>x : Symbol(x, Decl(genericTypeAliases.ts, 30, 10)) + +var z: Foo; +>z : Symbol(z, Decl(genericTypeAliases.ts, 32, 3)) +>Foo : Symbol(Foo, Decl(genericTypeAliases.ts, 17, 18)) + +z = 42; +>z : Symbol(z, Decl(genericTypeAliases.ts, 32, 3)) + +z = { x: 42 }; +>z : Symbol(z, Decl(genericTypeAliases.ts, 32, 3)) +>x : Symbol(x, Decl(genericTypeAliases.ts, 34, 5)) + +z = { x: { x: 42 } }; +>z : Symbol(z, Decl(genericTypeAliases.ts, 32, 3)) +>x : Symbol(x, Decl(genericTypeAliases.ts, 35, 5)) +>x : Symbol(x, Decl(genericTypeAliases.ts, 35, 10)) + +type Strange = string; // Type parameter not used +>Strange : Symbol(Strange, Decl(genericTypeAliases.ts, 35, 21)) +>T : Symbol(T, Decl(genericTypeAliases.ts, 37, 13)) + +var s: Strange; +>s : Symbol(s, Decl(genericTypeAliases.ts, 38, 3)) +>Strange : Symbol(Strange, Decl(genericTypeAliases.ts, 35, 21)) + +s = "hello"; +>s : Symbol(s, Decl(genericTypeAliases.ts, 38, 3)) + +interface Tuple { +>Tuple : Symbol(Tuple, Decl(genericTypeAliases.ts, 39, 12)) +>A : Symbol(A, Decl(genericTypeAliases.ts, 41, 16)) +>B : Symbol(B, Decl(genericTypeAliases.ts, 41, 18)) + + a: A; +>a : Symbol(a, Decl(genericTypeAliases.ts, 41, 23)) +>A : Symbol(A, Decl(genericTypeAliases.ts, 41, 16)) + + b: B; +>b : Symbol(b, Decl(genericTypeAliases.ts, 42, 9)) +>B : Symbol(B, Decl(genericTypeAliases.ts, 41, 18)) +} + +type Pair = Tuple; +>Pair : Symbol(Pair, Decl(genericTypeAliases.ts, 44, 1)) +>T : Symbol(T, Decl(genericTypeAliases.ts, 46, 10)) +>Tuple : Symbol(Tuple, Decl(genericTypeAliases.ts, 39, 12)) +>T : Symbol(T, Decl(genericTypeAliases.ts, 46, 10)) +>T : Symbol(T, Decl(genericTypeAliases.ts, 46, 10)) + +interface TaggedPair extends Pair { +>TaggedPair : Symbol(TaggedPair, Decl(genericTypeAliases.ts, 46, 27)) +>T : Symbol(T, Decl(genericTypeAliases.ts, 48, 21)) +>Pair : Symbol(Pair, Decl(genericTypeAliases.ts, 44, 1)) +>T : Symbol(T, Decl(genericTypeAliases.ts, 48, 21)) + + tag: string; +>tag : Symbol(tag, Decl(genericTypeAliases.ts, 48, 41)) +} + +var p: TaggedPair; +>p : Symbol(p, Decl(genericTypeAliases.ts, 52, 3)) +>TaggedPair : Symbol(TaggedPair, Decl(genericTypeAliases.ts, 46, 27)) + +p.a = 1; +>p.a : Symbol(Tuple.a, Decl(genericTypeAliases.ts, 41, 23)) +>p : Symbol(p, Decl(genericTypeAliases.ts, 52, 3)) +>a : Symbol(Tuple.a, Decl(genericTypeAliases.ts, 41, 23)) + +p.b = 2; +>p.b : Symbol(Tuple.b, Decl(genericTypeAliases.ts, 42, 9)) +>p : Symbol(p, Decl(genericTypeAliases.ts, 52, 3)) +>b : Symbol(Tuple.b, Decl(genericTypeAliases.ts, 42, 9)) + +p.tag = "test"; +>p.tag : Symbol(TaggedPair.tag, Decl(genericTypeAliases.ts, 48, 41)) +>p : Symbol(p, Decl(genericTypeAliases.ts, 52, 3)) +>tag : Symbol(TaggedPair.tag, Decl(genericTypeAliases.ts, 48, 41)) + +function f() { +>f : Symbol(f, Decl(genericTypeAliases.ts, 55, 15)) +>A : Symbol(A, Decl(genericTypeAliases.ts, 57, 11)) + + type Foo = T | { x: Foo }; +>Foo : Symbol(Foo, Decl(genericTypeAliases.ts, 57, 17)) +>T : Symbol(T, Decl(genericTypeAliases.ts, 58, 13)) +>T : Symbol(T, Decl(genericTypeAliases.ts, 58, 13)) +>x : Symbol(x, Decl(genericTypeAliases.ts, 58, 23)) +>Foo : Symbol(Foo, Decl(genericTypeAliases.ts, 57, 17)) +>T : Symbol(T, Decl(genericTypeAliases.ts, 58, 13)) + + var x: Foo; +>x : Symbol(x, Decl(genericTypeAliases.ts, 59, 7)) +>Foo : Symbol(Foo, Decl(genericTypeAliases.ts, 57, 17)) +>A : Symbol(A, Decl(genericTypeAliases.ts, 57, 11)) + + return x; +>x : Symbol(x, Decl(genericTypeAliases.ts, 59, 7)) +} + +function g() { +>g : Symbol(g, Decl(genericTypeAliases.ts, 61, 1)) +>B : Symbol(B, Decl(genericTypeAliases.ts, 63, 11)) + + type Bar = U | { x: Bar }; +>Bar : Symbol(Bar, Decl(genericTypeAliases.ts, 63, 17)) +>U : Symbol(U, Decl(genericTypeAliases.ts, 64, 13)) +>U : Symbol(U, Decl(genericTypeAliases.ts, 64, 13)) +>x : Symbol(x, Decl(genericTypeAliases.ts, 64, 23)) +>Bar : Symbol(Bar, Decl(genericTypeAliases.ts, 63, 17)) +>U : Symbol(U, Decl(genericTypeAliases.ts, 64, 13)) + + var x: Bar; +>x : Symbol(x, Decl(genericTypeAliases.ts, 65, 7)) +>Bar : Symbol(Bar, Decl(genericTypeAliases.ts, 63, 17)) +>B : Symbol(B, Decl(genericTypeAliases.ts, 63, 11)) + + return x; +>x : Symbol(x, Decl(genericTypeAliases.ts, 65, 7)) +} + +// Deeply instantiated generics +var a = f(); +>a : Symbol(a, Decl(genericTypeAliases.ts, 70, 3)) +>f : Symbol(f, Decl(genericTypeAliases.ts, 55, 15)) + +var b = g(); +>b : Symbol(b, Decl(genericTypeAliases.ts, 71, 3)) +>g : Symbol(g, Decl(genericTypeAliases.ts, 61, 1)) + +a = b; +>a : Symbol(a, Decl(genericTypeAliases.ts, 70, 3)) +>b : Symbol(b, Decl(genericTypeAliases.ts, 71, 3)) + diff --git a/tests/baselines/reference/genericTypeAliases.types b/tests/baselines/reference/genericTypeAliases.types new file mode 100644 index 00000000000..b43e2610725 --- /dev/null +++ b/tests/baselines/reference/genericTypeAliases.types @@ -0,0 +1,274 @@ +=== tests/cases/conformance/types/typeAliases/genericTypeAliases.ts === +type Tree = T | { left: Tree, right: Tree }; +>Tree : T | { left: T | any; right: T | any; } +>T : T +>T : T +>left : T | { left: T | any; right: T | any; } +>Tree : T | { left: T | any; right: T | any; } +>T : T +>right : T | { left: T | any; right: T | any; } +>Tree : T | { left: T | any; right: T | any; } +>T : T + +var tree: Tree = { +>tree : number | { left: number | any; right: number | any; } +>Tree : T | { left: T | any; right: T | any; } +>{ left: { left: 0, right: { left: 1, right: 2 }, }, right: 3} : { left: { left: number; right: { left: number; right: number; }; }; right: number; } + + left: { +>left : { left: number; right: { left: number; right: number; }; } +>{ left: 0, right: { left: 1, right: 2 }, } : { left: number; right: { left: number; right: number; }; } + + left: 0, +>left : number +>0 : number + + right: { +>right : { left: number; right: number; } +>{ left: 1, right: 2 } : { left: number; right: number; } + + left: 1, +>left : number +>1 : number + + right: 2 +>right : number +>2 : number + + }, + }, + right: 3 +>right : number +>3 : number + +}; + +type Lazy = T | (() => T); +>Lazy : T | (() => T) +>T : T +>T : T +>T : T + +var ls: Lazy; +>ls : string | (() => string) +>Lazy : T | (() => T) + +ls = "eager"; +>ls = "eager" : string +>ls : string | (() => string) +>"eager" : string + +ls = () => "lazy"; +>ls = () => "lazy" : () => string +>ls : string | (() => string) +>() => "lazy" : () => string +>"lazy" : string + +type Foo = T | { x: Foo }; +>Foo : T | { x: T | any; } +>T : T +>T : T +>x : T | { x: T | any; } +>Foo : T | { x: T | any; } +>T : T + +type Bar = U | { x: Bar }; +>Bar : U | { x: U | any; } +>U : U +>U : U +>x : U | { x: U | any; } +>Bar : U | { x: U | any; } +>U : U + +// Deeply instantiated generics +var x: Foo; +>x : string | { x: string | any; } +>Foo : T | { x: T | any; } + +var y: Bar; +>y : string | { x: string | any; } +>Bar : U | { x: U | any; } + +x = y; +>x = y : string | { x: string | any; } +>x : string | { x: string | any; } +>y : string | { x: string | any; } + +y = x; +>y = x : string | { x: string | any; } +>y : string | { x: string | any; } +>x : string | { x: string | any; } + +x = "string"; +>x = "string" : string +>x : string | { x: string | any; } +>"string" : string + +x = { x: "hello" }; +>x = { x: "hello" } : { x: string; } +>x : string | { x: string | any; } +>{ x: "hello" } : { x: string; } +>x : string +>"hello" : string + +x = { x: { x: "world" } }; +>x = { x: { x: "world" } } : { x: { x: string; }; } +>x : string | { x: string | any; } +>{ x: { x: "world" } } : { x: { x: string; }; } +>x : { x: string; } +>{ x: "world" } : { x: string; } +>x : string +>"world" : string + +var z: Foo; +>z : number | { x: number | any; } +>Foo : T | { x: T | any; } + +z = 42; +>z = 42 : number +>z : number | { x: number | any; } +>42 : number + +z = { x: 42 }; +>z = { x: 42 } : { x: number; } +>z : number | { x: number | any; } +>{ x: 42 } : { x: number; } +>x : number +>42 : number + +z = { x: { x: 42 } }; +>z = { x: { x: 42 } } : { x: { x: number; }; } +>z : number | { x: number | any; } +>{ x: { x: 42 } } : { x: { x: number; }; } +>x : { x: number; } +>{ x: 42 } : { x: number; } +>x : number +>42 : number + +type Strange = string; // Type parameter not used +>Strange : string +>T : T + +var s: Strange; +>s : string +>Strange : string + +s = "hello"; +>s = "hello" : string +>s : string +>"hello" : string + +interface Tuple { +>Tuple : Tuple +>A : A +>B : B + + a: A; +>a : A +>A : A + + b: B; +>b : B +>B : B +} + +type Pair = Tuple; +>Pair : Tuple +>T : T +>Tuple : Tuple +>T : T +>T : T + +interface TaggedPair extends Pair { +>TaggedPair : TaggedPair +>T : T +>Pair : Tuple +>T : T + + tag: string; +>tag : string +} + +var p: TaggedPair; +>p : TaggedPair +>TaggedPair : TaggedPair + +p.a = 1; +>p.a = 1 : number +>p.a : number +>p : TaggedPair +>a : number +>1 : number + +p.b = 2; +>p.b = 2 : number +>p.b : number +>p : TaggedPair +>b : number +>2 : number + +p.tag = "test"; +>p.tag = "test" : string +>p.tag : string +>p : TaggedPair +>tag : string +>"test" : string + +function f() { +>f : () => A[] | { x: A[] | any; } +>A : A + + type Foo = T | { x: Foo }; +>Foo : T | { x: T | any; } +>T : T +>T : T +>x : T | { x: T | any; } +>Foo : T | { x: T | any; } +>T : T + + var x: Foo; +>x : A[] | { x: A[] | any; } +>Foo : T | { x: T | any; } +>A : A + + return x; +>x : A[] | { x: A[] | any; } +} + +function g() { +>g : () => B[] | { x: B[] | any; } +>B : B + + type Bar = U | { x: Bar }; +>Bar : U | { x: U | any; } +>U : U +>U : U +>x : U | { x: U | any; } +>Bar : U | { x: U | any; } +>U : U + + var x: Bar; +>x : B[] | { x: B[] | any; } +>Bar : U | { x: U | any; } +>B : B + + return x; +>x : B[] | { x: B[] | any; } +} + +// Deeply instantiated generics +var a = f(); +>a : string[] | { x: string[] | any; } +>f() : string[] | { x: string[] | any; } +>f : () => A[] | { x: A[] | any; } + +var b = g(); +>b : string[] | { x: string[] | any; } +>g() : string[] | { x: string[] | any; } +>g : () => B[] | { x: B[] | any; } + +a = b; +>a = b : string[] | { x: string[] | any; } +>a : string[] | { x: string[] | any; } +>b : string[] | { x: string[] | any; } + diff --git a/tests/baselines/reference/genericTypeAssertions2.js b/tests/baselines/reference/genericTypeAssertions2.js index a3b88f599b9..22ff708592e 100644 --- a/tests/baselines/reference/genericTypeAssertions2.js +++ b/tests/baselines/reference/genericTypeAssertions2.js @@ -17,8 +17,7 @@ var r5: A = >[]; // error var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var A = (function () { function A() { diff --git a/tests/baselines/reference/genericTypeAssertions4.js b/tests/baselines/reference/genericTypeAssertions4.js index 95ca5482b2e..d6d8672283c 100644 --- a/tests/baselines/reference/genericTypeAssertions4.js +++ b/tests/baselines/reference/genericTypeAssertions4.js @@ -29,8 +29,7 @@ function foo2(x: T) { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var A = (function () { function A() { diff --git a/tests/baselines/reference/genericTypeAssertions6.js b/tests/baselines/reference/genericTypeAssertions6.js index d19da506680..30a5d5ff5e5 100644 --- a/tests/baselines/reference/genericTypeAssertions6.js +++ b/tests/baselines/reference/genericTypeAssertions6.js @@ -28,8 +28,7 @@ var c: A = >b; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var A = (function () { function A(x) { diff --git a/tests/baselines/reference/genericTypeConstraints.errors.txt b/tests/baselines/reference/genericTypeConstraints.errors.txt new file mode 100644 index 00000000000..ae97572b56a --- /dev/null +++ b/tests/baselines/reference/genericTypeConstraints.errors.txt @@ -0,0 +1,21 @@ +tests/cases/compiler/genericTypeConstraints.ts(9,31): error TS2344: Type 'FooExtended' does not satisfy the constraint 'Foo'. + Property 'fooMethod' is missing in type 'FooExtended'. + + +==== tests/cases/compiler/genericTypeConstraints.ts (1 errors) ==== + class Foo { + fooMethod() {} + } + + class FooExtended { } + + class Bar { } + + class BarExtended extends Bar { + ~~~~~~~~~~~ +!!! error TS2344: Type 'FooExtended' does not satisfy the constraint 'Foo'. +!!! error TS2344: Property 'fooMethod' is missing in type 'FooExtended'. + constructor() { + super(); + } + } \ No newline at end of file diff --git a/tests/baselines/reference/genericTypeConstraints.js b/tests/baselines/reference/genericTypeConstraints.js new file mode 100644 index 00000000000..eb8bed1fb92 --- /dev/null +++ b/tests/baselines/reference/genericTypeConstraints.js @@ -0,0 +1,44 @@ +//// [genericTypeConstraints.ts] +class Foo { + fooMethod() {} +} + +class FooExtended { } + +class Bar { } + +class BarExtended extends Bar { + constructor() { + super(); + } +} + +//// [genericTypeConstraints.js] +var __extends = (this && this.__extends) || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); +}; +var Foo = (function () { + function Foo() { + } + Foo.prototype.fooMethod = function () { }; + return Foo; +})(); +var FooExtended = (function () { + function FooExtended() { + } + return FooExtended; +})(); +var Bar = (function () { + function Bar() { + } + return Bar; +})(); +var BarExtended = (function (_super) { + __extends(BarExtended, _super); + function BarExtended() { + _super.call(this); + } + return BarExtended; +})(Bar); diff --git a/tests/baselines/reference/genericTypeReferenceWithoutTypeArgument.d.errors.txt b/tests/baselines/reference/genericTypeReferenceWithoutTypeArgument.d.errors.txt index 5ae71fa2a89..2f6db48bf2f 100644 --- a/tests/baselines/reference/genericTypeReferenceWithoutTypeArgument.d.errors.txt +++ b/tests/baselines/reference/genericTypeReferenceWithoutTypeArgument.d.errors.txt @@ -8,7 +8,7 @@ tests/cases/conformance/types/specifyingTypes/typeReferences/genericTypeReferenc tests/cases/conformance/types/specifyingTypes/typeReferences/genericTypeReferenceWithoutTypeArgument.d.ts(14,23): error TS2314: Generic type 'C' requires 1 type argument(s). tests/cases/conformance/types/specifyingTypes/typeReferences/genericTypeReferenceWithoutTypeArgument.d.ts(14,27): error TS2314: Generic type 'C' requires 1 type argument(s). tests/cases/conformance/types/specifyingTypes/typeReferences/genericTypeReferenceWithoutTypeArgument.d.ts(16,25): error TS2314: Generic type 'C' requires 1 type argument(s). -tests/cases/conformance/types/specifyingTypes/typeReferences/genericTypeReferenceWithoutTypeArgument.d.ts(22,28): error TS2305: Module 'M' has no exported member 'C'. +tests/cases/conformance/types/specifyingTypes/typeReferences/genericTypeReferenceWithoutTypeArgument.d.ts(22,28): error TS2339: Property 'C' does not exist on type 'typeof M'. tests/cases/conformance/types/specifyingTypes/typeReferences/genericTypeReferenceWithoutTypeArgument.d.ts(23,28): error TS2314: Generic type 'E' requires 1 type argument(s). tests/cases/conformance/types/specifyingTypes/typeReferences/genericTypeReferenceWithoutTypeArgument.d.ts(25,30): error TS2314: Generic type 'C' requires 1 type argument(s). tests/cases/conformance/types/specifyingTypes/typeReferences/genericTypeReferenceWithoutTypeArgument.d.ts(26,30): error TS2314: Generic type 'E' requires 1 type argument(s). @@ -58,7 +58,7 @@ tests/cases/conformance/types/specifyingTypes/typeReferences/genericTypeReferenc declare class D2 extends M.C { } ~ -!!! error TS2305: Module 'M' has no exported member 'C'. +!!! error TS2339: Property 'C' does not exist on type 'typeof M'. declare class D3 { } ~~~ !!! error TS2314: Generic type 'E' requires 1 type argument(s). diff --git a/tests/baselines/reference/genericTypeReferenceWithoutTypeArgument.js b/tests/baselines/reference/genericTypeReferenceWithoutTypeArgument.js index 5ec0a25af3d..0cbf3581706 100644 --- a/tests/baselines/reference/genericTypeReferenceWithoutTypeArgument.js +++ b/tests/baselines/reference/genericTypeReferenceWithoutTypeArgument.js @@ -43,8 +43,7 @@ var k = null; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var C = (function () { function C() { diff --git a/tests/baselines/reference/genericTypeReferenceWithoutTypeArgument2.errors.txt b/tests/baselines/reference/genericTypeReferenceWithoutTypeArgument2.errors.txt index 2949ce52ce0..e590ad42a7d 100644 --- a/tests/baselines/reference/genericTypeReferenceWithoutTypeArgument2.errors.txt +++ b/tests/baselines/reference/genericTypeReferenceWithoutTypeArgument2.errors.txt @@ -13,9 +13,9 @@ tests/cases/conformance/types/specifyingTypes/typeReferences/genericTypeReferenc tests/cases/conformance/types/specifyingTypes/typeReferences/genericTypeReferenceWithoutTypeArgument2.ts(18,23): error TS2314: Generic type 'I' requires 1 type argument(s). tests/cases/conformance/types/specifyingTypes/typeReferences/genericTypeReferenceWithoutTypeArgument2.ts(18,27): error TS2314: Generic type 'I' requires 1 type argument(s). tests/cases/conformance/types/specifyingTypes/typeReferences/genericTypeReferenceWithoutTypeArgument2.ts(18,38): error TS2314: Generic type 'I' requires 1 type argument(s). -tests/cases/conformance/types/specifyingTypes/typeReferences/genericTypeReferenceWithoutTypeArgument2.ts(20,17): error TS2314: Generic type 'I' requires 1 type argument(s). +tests/cases/conformance/types/specifyingTypes/typeReferences/genericTypeReferenceWithoutTypeArgument2.ts(20,17): error TS2304: Cannot find name 'I'. tests/cases/conformance/types/specifyingTypes/typeReferences/genericTypeReferenceWithoutTypeArgument2.ts(23,21): error TS2314: Generic type 'I' requires 1 type argument(s). -tests/cases/conformance/types/specifyingTypes/typeReferences/genericTypeReferenceWithoutTypeArgument2.ts(29,20): error TS2305: Module 'M' has no exported member 'C'. +tests/cases/conformance/types/specifyingTypes/typeReferences/genericTypeReferenceWithoutTypeArgument2.ts(29,18): error TS2304: Cannot find name 'M'. tests/cases/conformance/types/specifyingTypes/typeReferences/genericTypeReferenceWithoutTypeArgument2.ts(30,24): error TS2314: Generic type 'E' requires 1 type argument(s). tests/cases/conformance/types/specifyingTypes/typeReferences/genericTypeReferenceWithoutTypeArgument2.ts(31,24): error TS2305: Module 'M' has no exported member 'C'. tests/cases/conformance/types/specifyingTypes/typeReferences/genericTypeReferenceWithoutTypeArgument2.ts(33,22): error TS2314: Generic type 'I' requires 1 type argument(s). @@ -76,7 +76,7 @@ tests/cases/conformance/types/specifyingTypes/typeReferences/genericTypeReferenc class D extends I { ~ -!!! error TS2314: Generic type 'I' requires 1 type argument(s). +!!! error TS2304: Cannot find name 'I'. } interface U extends I {} @@ -88,8 +88,8 @@ tests/cases/conformance/types/specifyingTypes/typeReferences/genericTypeReferenc } class D2 extends M.C { } - ~ -!!! error TS2305: Module 'M' has no exported member 'C'. + ~ +!!! error TS2304: Cannot find name 'M'. interface D3 { } ~~~ !!! error TS2314: Generic type 'E' requires 1 type argument(s). diff --git a/tests/baselines/reference/genericTypeReferenceWithoutTypeArgument2.js b/tests/baselines/reference/genericTypeReferenceWithoutTypeArgument2.js index 2f36a74de76..355030caa1b 100644 --- a/tests/baselines/reference/genericTypeReferenceWithoutTypeArgument2.js +++ b/tests/baselines/reference/genericTypeReferenceWithoutTypeArgument2.js @@ -43,8 +43,7 @@ var k = null; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var c; var a; diff --git a/tests/baselines/reference/genericTypeReferenceWithoutTypeArgument3.errors.txt b/tests/baselines/reference/genericTypeReferenceWithoutTypeArgument3.errors.txt index c0e41374527..95857c925be 100644 --- a/tests/baselines/reference/genericTypeReferenceWithoutTypeArgument3.errors.txt +++ b/tests/baselines/reference/genericTypeReferenceWithoutTypeArgument3.errors.txt @@ -8,7 +8,7 @@ tests/cases/conformance/types/specifyingTypes/typeReferences/genericTypeReferenc tests/cases/conformance/types/specifyingTypes/typeReferences/genericTypeReferenceWithoutTypeArgument3.ts(14,23): error TS2314: Generic type 'C' requires 1 type argument(s). tests/cases/conformance/types/specifyingTypes/typeReferences/genericTypeReferenceWithoutTypeArgument3.ts(14,27): error TS2314: Generic type 'C' requires 1 type argument(s). tests/cases/conformance/types/specifyingTypes/typeReferences/genericTypeReferenceWithoutTypeArgument3.ts(16,25): error TS2314: Generic type 'C' requires 1 type argument(s). -tests/cases/conformance/types/specifyingTypes/typeReferences/genericTypeReferenceWithoutTypeArgument3.ts(22,28): error TS2305: Module 'M' has no exported member 'C'. +tests/cases/conformance/types/specifyingTypes/typeReferences/genericTypeReferenceWithoutTypeArgument3.ts(22,28): error TS2339: Property 'C' does not exist on type 'typeof M'. tests/cases/conformance/types/specifyingTypes/typeReferences/genericTypeReferenceWithoutTypeArgument3.ts(23,28): error TS2314: Generic type 'E' requires 1 type argument(s). tests/cases/conformance/types/specifyingTypes/typeReferences/genericTypeReferenceWithoutTypeArgument3.ts(25,30): error TS2314: Generic type 'C' requires 1 type argument(s). tests/cases/conformance/types/specifyingTypes/typeReferences/genericTypeReferenceWithoutTypeArgument3.ts(26,30): error TS2314: Generic type 'E' requires 1 type argument(s). @@ -58,7 +58,7 @@ tests/cases/conformance/types/specifyingTypes/typeReferences/genericTypeReferenc declare class D2 extends M.C { } ~ -!!! error TS2305: Module 'M' has no exported member 'C'. +!!! error TS2339: Property 'C' does not exist on type 'typeof M'. declare class D3 { } ~~~ !!! error TS2314: Generic type 'E' requires 1 type argument(s). diff --git a/tests/baselines/reference/genericWithIndexerOfTypeParameterType2.js b/tests/baselines/reference/genericWithIndexerOfTypeParameterType2.js index 8142cd86407..2457d4a534e 100644 --- a/tests/baselines/reference/genericWithIndexerOfTypeParameterType2.js +++ b/tests/baselines/reference/genericWithIndexerOfTypeParameterType2.js @@ -18,8 +18,7 @@ export class ListItem extends CollectionItem { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; define(["require", "exports"], function (require, exports) { var Collection = (function () { diff --git a/tests/baselines/reference/genericWithIndexerOfTypeParameterType2.types b/tests/baselines/reference/genericWithIndexerOfTypeParameterType2.types index e1cdfa85f13..2005604c83c 100644 --- a/tests/baselines/reference/genericWithIndexerOfTypeParameterType2.types +++ b/tests/baselines/reference/genericWithIndexerOfTypeParameterType2.types @@ -12,7 +12,7 @@ export class Collection { export class List extends Collection{ >List : List ->Collection : Collection +>Collection : Collection >ListItem : ListItem Bar() {} diff --git a/tests/baselines/reference/generics1.errors.txt b/tests/baselines/reference/generics1.errors.txt index 81d250a2ef4..6279c0dcd63 100644 --- a/tests/baselines/reference/generics1.errors.txt +++ b/tests/baselines/reference/generics1.errors.txt @@ -1,4 +1,4 @@ -tests/cases/compiler/generics1.ts(10,9): error TS2344: Type 'A' does not satisfy the constraint 'B'. +tests/cases/compiler/generics1.ts(10,14): error TS2344: Type 'A' does not satisfy the constraint 'B'. Property 'b' is missing in type 'A'. tests/cases/compiler/generics1.ts(13,9): error TS2314: Generic type 'G' requires 2 type argument(s). tests/cases/compiler/generics1.ts(14,9): error TS2314: Generic type 'G' requires 2 type argument(s). @@ -15,7 +15,7 @@ tests/cases/compiler/generics1.ts(14,9): error TS2314: Generic type 'G' re var v1: G; // Ok var v2: G<{ a: string }, C>; // Ok, equivalent to G var v3: G; // Error, A not valid argument for U - ~~~~~~~ + ~ !!! error TS2344: Type 'A' does not satisfy the constraint 'B'. !!! error TS2344: Property 'b' is missing in type 'A'. var v4: G, C>; // Ok diff --git a/tests/baselines/reference/generics2.errors.txt b/tests/baselines/reference/generics2.errors.txt index a0380eee753..d44bc7baad8 100644 --- a/tests/baselines/reference/generics2.errors.txt +++ b/tests/baselines/reference/generics2.errors.txt @@ -1,4 +1,4 @@ -tests/cases/compiler/generics2.ts(17,9): error TS2344: Type 'A' does not satisfy the constraint 'B'. +tests/cases/compiler/generics2.ts(17,14): error TS2344: Type 'A' does not satisfy the constraint 'B'. Property 'b' is missing in type 'A'. tests/cases/compiler/generics2.ts(20,9): error TS2314: Generic type 'G' requires 2 type argument(s). tests/cases/compiler/generics2.ts(21,9): error TS2314: Generic type 'G' requires 2 type argument(s). @@ -22,7 +22,7 @@ tests/cases/compiler/generics2.ts(21,9): error TS2314: Generic type 'G' re var v2: G<{ a: string }, C>; // Ok, equivalent to G var v3: G; // Error, A not valid argument for U - ~~~~~~~ + ~ !!! error TS2344: Type 'A' does not satisfy the constraint 'B'. !!! error TS2344: Property 'b' is missing in type 'A'. var v4: G, C>; // Ok diff --git a/tests/baselines/reference/generics5.errors.txt b/tests/baselines/reference/generics5.errors.txt index 17aeea63df2..fd21a705436 100644 --- a/tests/baselines/reference/generics5.errors.txt +++ b/tests/baselines/reference/generics5.errors.txt @@ -1,4 +1,4 @@ -tests/cases/compiler/generics5.ts(10,9): error TS2344: Type 'A' does not satisfy the constraint 'B'. +tests/cases/compiler/generics5.ts(10,14): error TS2344: Type 'A' does not satisfy the constraint 'B'. Property 'b' is missing in type 'A'. @@ -13,7 +13,7 @@ tests/cases/compiler/generics5.ts(10,9): error TS2344: Type 'A' does not satisfy } var v3: G; // Error, A not valid argument for U - ~~~~~~~ + ~ !!! error TS2344: Type 'A' does not satisfy the constraint 'B'. !!! error TS2344: Property 'b' is missing in type 'A'. diff --git a/tests/baselines/reference/heterogeneousArrayLiterals.js b/tests/baselines/reference/heterogeneousArrayLiterals.js index 26d1b09a6fc..45ea6429979 100644 --- a/tests/baselines/reference/heterogeneousArrayLiterals.js +++ b/tests/baselines/reference/heterogeneousArrayLiterals.js @@ -136,8 +136,7 @@ function foo4(t: T, u: U) { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var a = [1, '']; // {}[] var b = [1, null]; // number[] diff --git a/tests/baselines/reference/heterogeneousArrayLiterals.types b/tests/baselines/reference/heterogeneousArrayLiterals.types index 81fa915ab03..ecfbf75e864 100644 --- a/tests/baselines/reference/heterogeneousArrayLiterals.types +++ b/tests/baselines/reference/heterogeneousArrayLiterals.types @@ -40,8 +40,8 @@ var f = [[], [1]]; // number[][] >1 : number var g = [[1], ['']]; // {}[] ->g : (string[] | number[])[] ->[[1], ['']] : (string[] | number[])[] +>g : (number[] | string[])[] +>[[1], ['']] : (number[] | string[])[] >[1] : number[] >1 : number >[''] : string[] diff --git a/tests/baselines/reference/ifDoWhileStatements.js b/tests/baselines/reference/ifDoWhileStatements.js index d389f705707..020d3f053d1 100644 --- a/tests/baselines/reference/ifDoWhileStatements.js +++ b/tests/baselines/reference/ifDoWhileStatements.js @@ -166,8 +166,7 @@ do { }while(fn) var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var C = (function () { function C() { diff --git a/tests/baselines/reference/illegalSuperCallsInConstructor.js b/tests/baselines/reference/illegalSuperCallsInConstructor.js index 57a382fe625..c3a52473744 100644 --- a/tests/baselines/reference/illegalSuperCallsInConstructor.js +++ b/tests/baselines/reference/illegalSuperCallsInConstructor.js @@ -24,8 +24,7 @@ class Derived extends Base { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var Base = (function () { function Base() { diff --git a/tests/baselines/reference/implementClausePrecedingExtends.js b/tests/baselines/reference/implementClausePrecedingExtends.js index 7501c231dc8..a929c2fb966 100644 --- a/tests/baselines/reference/implementClausePrecedingExtends.js +++ b/tests/baselines/reference/implementClausePrecedingExtends.js @@ -6,8 +6,7 @@ class D implements C extends C { } var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var C = (function () { function C() { diff --git a/tests/baselines/reference/implementingAnInterfaceExtendingClassWithPrivates2.js b/tests/baselines/reference/implementingAnInterfaceExtendingClassWithPrivates2.js index 3d80d344850..cfa5ccf4150 100644 --- a/tests/baselines/reference/implementingAnInterfaceExtendingClassWithPrivates2.js +++ b/tests/baselines/reference/implementingAnInterfaceExtendingClassWithPrivates2.js @@ -89,8 +89,7 @@ module M2 { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var Foo = (function () { function Foo() { diff --git a/tests/baselines/reference/implementingAnInterfaceExtendingClassWithProtecteds.js b/tests/baselines/reference/implementingAnInterfaceExtendingClassWithProtecteds.js index 1fa40bf7aa2..39f30424321 100644 --- a/tests/baselines/reference/implementingAnInterfaceExtendingClassWithProtecteds.js +++ b/tests/baselines/reference/implementingAnInterfaceExtendingClassWithProtecteds.js @@ -45,8 +45,7 @@ class Bar8 extends Foo implements I { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var Foo = (function () { function Foo() { diff --git a/tests/baselines/reference/implicitAnyFromCircularInference.errors.txt b/tests/baselines/reference/implicitAnyFromCircularInference.errors.txt index 8d0aaf04c03..36538aef4f3 100644 --- a/tests/baselines/reference/implicitAnyFromCircularInference.errors.txt +++ b/tests/baselines/reference/implicitAnyFromCircularInference.errors.txt @@ -7,7 +7,7 @@ tests/cases/compiler/implicitAnyFromCircularInference.ts(18,10): error TS7024: F tests/cases/compiler/implicitAnyFromCircularInference.ts(23,10): error TS7024: 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. tests/cases/compiler/implicitAnyFromCircularInference.ts(26,10): error TS7023: 'h' 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. tests/cases/compiler/implicitAnyFromCircularInference.ts(28,14): error TS7023: 'foo' 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. -tests/cases/compiler/implicitAnyFromCircularInference.ts(41,5): error TS7022: 's' implicitly has type 'any' because it is does not have a type annotation and is referenced directly or indirectly in its own initializer. +tests/cases/compiler/implicitAnyFromCircularInference.ts(41,5): error TS7022: 's' implicitly has type 'any' because it does not have a type annotation and is referenced directly or indirectly in its own initializer. tests/cases/compiler/implicitAnyFromCircularInference.ts(46,5): error TS7023: 'x' 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. @@ -72,7 +72,7 @@ tests/cases/compiler/implicitAnyFromCircularInference.ts(46,5): error TS7023: 'x // Error expected s = foo(this); ~~~~~~~~~~~~~~ -!!! error TS7022: 's' implicitly has type 'any' because it is does not have a type annotation and is referenced directly or indirectly in its own initializer. +!!! error TS7022: 's' implicitly has type 'any' because it does not have a type annotation and is referenced directly or indirectly in its own initializer. } class D { diff --git a/tests/baselines/reference/importAsBaseClass.errors.txt b/tests/baselines/reference/importAsBaseClass.errors.txt index f09eb55561b..835fd143f70 100644 --- a/tests/baselines/reference/importAsBaseClass.errors.txt +++ b/tests/baselines/reference/importAsBaseClass.errors.txt @@ -1,11 +1,11 @@ -tests/cases/compiler/importAsBaseClass_1.ts(2,21): error TS2304: Cannot find name 'Greeter'. +tests/cases/compiler/importAsBaseClass_1.ts(2,21): error TS2507: Type 'typeof "tests/cases/compiler/importAsBaseClass_0"' is not a constructor function type. ==== tests/cases/compiler/importAsBaseClass_1.ts (1 errors) ==== import Greeter = require("importAsBaseClass_0"); class Hello extends Greeter { } ~~~~~~~ -!!! error TS2304: Cannot find name 'Greeter'. +!!! error TS2507: Type 'typeof "tests/cases/compiler/importAsBaseClass_0"' is not a constructor function type. ==== tests/cases/compiler/importAsBaseClass_0.ts (0 errors) ==== export class Greeter { diff --git a/tests/baselines/reference/importAsBaseClass.js b/tests/baselines/reference/importAsBaseClass.js index 24f7e0477d6..b79905911b1 100644 --- a/tests/baselines/reference/importAsBaseClass.js +++ b/tests/baselines/reference/importAsBaseClass.js @@ -22,9 +22,9 @@ exports.Greeter = Greeter; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; +var Greeter = require("importAsBaseClass_0"); var Hello = (function (_super) { __extends(Hello, _super); function Hello() { diff --git a/tests/baselines/reference/importShadowsGlobalName.js b/tests/baselines/reference/importShadowsGlobalName.js index 6db46eb41b1..fe37e938a5a 100644 --- a/tests/baselines/reference/importShadowsGlobalName.js +++ b/tests/baselines/reference/importShadowsGlobalName.js @@ -23,8 +23,7 @@ define(["require", "exports"], function (require, exports) { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; define(["require", "exports", 'Foo'], function (require, exports, Error) { var Bar = (function (_super) { diff --git a/tests/baselines/reference/importUsedInExtendsList1.js b/tests/baselines/reference/importUsedInExtendsList1.js index 3e07ee084f3..e86b1a41456 100644 --- a/tests/baselines/reference/importUsedInExtendsList1.js +++ b/tests/baselines/reference/importUsedInExtendsList1.js @@ -22,8 +22,7 @@ exports.Super = Super; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; /// var foo = require('importUsedInExtendsList1_require'); diff --git a/tests/baselines/reference/importUsedInExtendsList1.types b/tests/baselines/reference/importUsedInExtendsList1.types index 74737c4db96..3c1b69f5a83 100644 --- a/tests/baselines/reference/importUsedInExtendsList1.types +++ b/tests/baselines/reference/importUsedInExtendsList1.types @@ -5,9 +5,9 @@ import foo = require('importUsedInExtendsList1_require'); class Sub extends foo.Super { } >Sub : Sub ->foo.Super : any +>foo.Super : foo.Super >foo : typeof foo ->Super : foo.Super +>Super : typeof foo.Super var s: Sub; >s : Sub diff --git a/tests/baselines/reference/indexerConstraints2.js b/tests/baselines/reference/indexerConstraints2.js index 7d3966688db..7e662bc66cc 100644 --- a/tests/baselines/reference/indexerConstraints2.js +++ b/tests/baselines/reference/indexerConstraints2.js @@ -32,8 +32,7 @@ class K extends J { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var A = (function () { function A() { diff --git a/tests/baselines/reference/indirectSelfReference.errors.txt b/tests/baselines/reference/indirectSelfReference.errors.txt index e7c5a00d421..3f7d3d47f12 100644 --- a/tests/baselines/reference/indirectSelfReference.errors.txt +++ b/tests/baselines/reference/indirectSelfReference.errors.txt @@ -1,8 +1,11 @@ -tests/cases/compiler/indirectSelfReference.ts(1,7): error TS2310: Type 'a' recursively references itself as a base type. +tests/cases/compiler/indirectSelfReference.ts(1,7): error TS2506: 'a' is referenced directly or indirectly in its own base expression. +tests/cases/compiler/indirectSelfReference.ts(2,7): error TS2506: 'b' is referenced directly or indirectly in its own base expression. -==== tests/cases/compiler/indirectSelfReference.ts (1 errors) ==== +==== tests/cases/compiler/indirectSelfReference.ts (2 errors) ==== class a extends b{ } ~ -!!! error TS2310: Type 'a' recursively references itself as a base type. - class b extends a{ } \ No newline at end of file +!!! error TS2506: 'a' is referenced directly or indirectly in its own base expression. + class b extends a{ } + ~ +!!! error TS2506: 'b' is referenced directly or indirectly in its own base expression. \ No newline at end of file diff --git a/tests/baselines/reference/indirectSelfReference.js b/tests/baselines/reference/indirectSelfReference.js index 3652d2962d0..bd838ed8810 100644 --- a/tests/baselines/reference/indirectSelfReference.js +++ b/tests/baselines/reference/indirectSelfReference.js @@ -6,8 +6,7 @@ class b extends a{ } var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var a = (function (_super) { __extends(a, _super); diff --git a/tests/baselines/reference/indirectSelfReferenceGeneric.errors.txt b/tests/baselines/reference/indirectSelfReferenceGeneric.errors.txt index 765112f0e99..5a6aeed5de1 100644 --- a/tests/baselines/reference/indirectSelfReferenceGeneric.errors.txt +++ b/tests/baselines/reference/indirectSelfReferenceGeneric.errors.txt @@ -1,8 +1,11 @@ -tests/cases/compiler/indirectSelfReferenceGeneric.ts(1,7): error TS2310: Type 'a' recursively references itself as a base type. +tests/cases/compiler/indirectSelfReferenceGeneric.ts(1,7): error TS2506: 'a' is referenced directly or indirectly in its own base expression. +tests/cases/compiler/indirectSelfReferenceGeneric.ts(2,7): error TS2506: 'b' is referenced directly or indirectly in its own base expression. -==== tests/cases/compiler/indirectSelfReferenceGeneric.ts (1 errors) ==== +==== tests/cases/compiler/indirectSelfReferenceGeneric.ts (2 errors) ==== class a extends b { } ~ -!!! error TS2310: Type 'a' recursively references itself as a base type. - class b extends a { } \ No newline at end of file +!!! error TS2506: 'a' is referenced directly or indirectly in its own base expression. + class b extends a { } + ~ +!!! error TS2506: 'b' is referenced directly or indirectly in its own base expression. \ No newline at end of file diff --git a/tests/baselines/reference/indirectSelfReferenceGeneric.js b/tests/baselines/reference/indirectSelfReferenceGeneric.js index 079a37dc201..c9b4478ec13 100644 --- a/tests/baselines/reference/indirectSelfReferenceGeneric.js +++ b/tests/baselines/reference/indirectSelfReferenceGeneric.js @@ -6,8 +6,7 @@ class b extends a { } var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var a = (function (_super) { __extends(a, _super); diff --git a/tests/baselines/reference/inferentialTypingObjectLiteralMethod1.js b/tests/baselines/reference/inferentialTypingObjectLiteralMethod1.js new file mode 100644 index 00000000000..a5cf75ae7f3 --- /dev/null +++ b/tests/baselines/reference/inferentialTypingObjectLiteralMethod1.js @@ -0,0 +1,9 @@ +//// [inferentialTypingObjectLiteralMethod1.ts] +interface Int { + method(x: T): U; +} +declare function foo(x: T, y: Int, z: Int): T; +foo("", { method(p1) { return p1.length } }, { method(p2) { return undefined } }); + +//// [inferentialTypingObjectLiteralMethod1.js] +foo("", { method: function (p1) { return p1.length; } }, { method: function (p2) { return undefined; } }); diff --git a/tests/baselines/reference/inferentialTypingObjectLiteralMethod1.symbols b/tests/baselines/reference/inferentialTypingObjectLiteralMethod1.symbols new file mode 100644 index 00000000000..3fee48fc837 --- /dev/null +++ b/tests/baselines/reference/inferentialTypingObjectLiteralMethod1.symbols @@ -0,0 +1,39 @@ +=== tests/cases/compiler/inferentialTypingObjectLiteralMethod1.ts === +interface Int { +>Int : Symbol(Int, Decl(inferentialTypingObjectLiteralMethod1.ts, 0, 0)) +>T : Symbol(T, Decl(inferentialTypingObjectLiteralMethod1.ts, 0, 14)) +>U : Symbol(U, Decl(inferentialTypingObjectLiteralMethod1.ts, 0, 16)) + + method(x: T): U; +>method : Symbol(method, Decl(inferentialTypingObjectLiteralMethod1.ts, 0, 21)) +>x : Symbol(x, Decl(inferentialTypingObjectLiteralMethod1.ts, 1, 11)) +>T : Symbol(T, Decl(inferentialTypingObjectLiteralMethod1.ts, 0, 14)) +>U : Symbol(U, Decl(inferentialTypingObjectLiteralMethod1.ts, 0, 16)) +} +declare function foo(x: T, y: Int, z: Int): T; +>foo : Symbol(foo, Decl(inferentialTypingObjectLiteralMethod1.ts, 2, 1)) +>T : Symbol(T, Decl(inferentialTypingObjectLiteralMethod1.ts, 3, 21)) +>U : Symbol(U, Decl(inferentialTypingObjectLiteralMethod1.ts, 3, 23)) +>x : Symbol(x, Decl(inferentialTypingObjectLiteralMethod1.ts, 3, 27)) +>T : Symbol(T, Decl(inferentialTypingObjectLiteralMethod1.ts, 3, 21)) +>y : Symbol(y, Decl(inferentialTypingObjectLiteralMethod1.ts, 3, 32)) +>Int : Symbol(Int, Decl(inferentialTypingObjectLiteralMethod1.ts, 0, 0)) +>T : Symbol(T, Decl(inferentialTypingObjectLiteralMethod1.ts, 3, 21)) +>U : Symbol(U, Decl(inferentialTypingObjectLiteralMethod1.ts, 3, 23)) +>z : Symbol(z, Decl(inferentialTypingObjectLiteralMethod1.ts, 3, 46)) +>Int : Symbol(Int, Decl(inferentialTypingObjectLiteralMethod1.ts, 0, 0)) +>U : Symbol(U, Decl(inferentialTypingObjectLiteralMethod1.ts, 3, 23)) +>T : Symbol(T, Decl(inferentialTypingObjectLiteralMethod1.ts, 3, 21)) +>T : Symbol(T, Decl(inferentialTypingObjectLiteralMethod1.ts, 3, 21)) + +foo("", { method(p1) { return p1.length } }, { method(p2) { return undefined } }); +>foo : Symbol(foo, Decl(inferentialTypingObjectLiteralMethod1.ts, 2, 1)) +>method : Symbol(method, Decl(inferentialTypingObjectLiteralMethod1.ts, 4, 9)) +>p1 : Symbol(p1, Decl(inferentialTypingObjectLiteralMethod1.ts, 4, 17)) +>p1.length : Symbol(String.length, Decl(lib.d.ts, 414, 19)) +>p1 : Symbol(p1, Decl(inferentialTypingObjectLiteralMethod1.ts, 4, 17)) +>length : Symbol(String.length, Decl(lib.d.ts, 414, 19)) +>method : Symbol(method, Decl(inferentialTypingObjectLiteralMethod1.ts, 4, 46)) +>p2 : Symbol(p2, Decl(inferentialTypingObjectLiteralMethod1.ts, 4, 54)) +>undefined : Symbol(undefined) + diff --git a/tests/baselines/reference/inferentialTypingObjectLiteralMethod1.types b/tests/baselines/reference/inferentialTypingObjectLiteralMethod1.types new file mode 100644 index 00000000000..da2fa24060f --- /dev/null +++ b/tests/baselines/reference/inferentialTypingObjectLiteralMethod1.types @@ -0,0 +1,43 @@ +=== tests/cases/compiler/inferentialTypingObjectLiteralMethod1.ts === +interface Int { +>Int : Int +>T : T +>U : U + + method(x: T): U; +>method : (x: T) => U +>x : T +>T : T +>U : U +} +declare function foo(x: T, y: Int, z: Int): T; +>foo : (x: T, y: Int, z: Int) => T +>T : T +>U : U +>x : T +>T : T +>y : Int +>Int : Int +>T : T +>U : U +>z : Int +>Int : Int +>U : U +>T : T +>T : T + +foo("", { method(p1) { return p1.length } }, { method(p2) { return undefined } }); +>foo("", { method(p1) { return p1.length } }, { method(p2) { return undefined } }) : string +>foo : (x: T, y: Int, z: Int) => T +>"" : string +>{ method(p1) { return p1.length } } : { method(p1: string): number; } +>method : (p1: string) => number +>p1 : string +>p1.length : number +>p1 : string +>length : number +>{ method(p2) { return undefined } } : { method(p2: number): any; } +>method : (p2: number) => any +>p2 : number +>undefined : undefined + diff --git a/tests/baselines/reference/inferentialTypingObjectLiteralMethod2.js b/tests/baselines/reference/inferentialTypingObjectLiteralMethod2.js new file mode 100644 index 00000000000..fe53a619acd --- /dev/null +++ b/tests/baselines/reference/inferentialTypingObjectLiteralMethod2.js @@ -0,0 +1,9 @@ +//// [inferentialTypingObjectLiteralMethod2.ts] +interface Int { + [s: string]: (x: T) => U; +} +declare function foo(x: T, y: Int, z: Int): T; +foo("", { method(p1) { return p1.length } }, { method(p2) { return undefined } }); + +//// [inferentialTypingObjectLiteralMethod2.js] +foo("", { method: function (p1) { return p1.length; } }, { method: function (p2) { return undefined; } }); diff --git a/tests/baselines/reference/inferentialTypingObjectLiteralMethod2.symbols b/tests/baselines/reference/inferentialTypingObjectLiteralMethod2.symbols new file mode 100644 index 00000000000..fc8d39858b6 --- /dev/null +++ b/tests/baselines/reference/inferentialTypingObjectLiteralMethod2.symbols @@ -0,0 +1,39 @@ +=== tests/cases/compiler/inferentialTypingObjectLiteralMethod2.ts === +interface Int { +>Int : Symbol(Int, Decl(inferentialTypingObjectLiteralMethod2.ts, 0, 0)) +>T : Symbol(T, Decl(inferentialTypingObjectLiteralMethod2.ts, 0, 14)) +>U : Symbol(U, Decl(inferentialTypingObjectLiteralMethod2.ts, 0, 16)) + + [s: string]: (x: T) => U; +>s : Symbol(s, Decl(inferentialTypingObjectLiteralMethod2.ts, 1, 5)) +>x : Symbol(x, Decl(inferentialTypingObjectLiteralMethod2.ts, 1, 18)) +>T : Symbol(T, Decl(inferentialTypingObjectLiteralMethod2.ts, 0, 14)) +>U : Symbol(U, Decl(inferentialTypingObjectLiteralMethod2.ts, 0, 16)) +} +declare function foo(x: T, y: Int, z: Int): T; +>foo : Symbol(foo, Decl(inferentialTypingObjectLiteralMethod2.ts, 2, 1)) +>T : Symbol(T, Decl(inferentialTypingObjectLiteralMethod2.ts, 3, 21)) +>U : Symbol(U, Decl(inferentialTypingObjectLiteralMethod2.ts, 3, 23)) +>x : Symbol(x, Decl(inferentialTypingObjectLiteralMethod2.ts, 3, 27)) +>T : Symbol(T, Decl(inferentialTypingObjectLiteralMethod2.ts, 3, 21)) +>y : Symbol(y, Decl(inferentialTypingObjectLiteralMethod2.ts, 3, 32)) +>Int : Symbol(Int, Decl(inferentialTypingObjectLiteralMethod2.ts, 0, 0)) +>T : Symbol(T, Decl(inferentialTypingObjectLiteralMethod2.ts, 3, 21)) +>U : Symbol(U, Decl(inferentialTypingObjectLiteralMethod2.ts, 3, 23)) +>z : Symbol(z, Decl(inferentialTypingObjectLiteralMethod2.ts, 3, 46)) +>Int : Symbol(Int, Decl(inferentialTypingObjectLiteralMethod2.ts, 0, 0)) +>U : Symbol(U, Decl(inferentialTypingObjectLiteralMethod2.ts, 3, 23)) +>T : Symbol(T, Decl(inferentialTypingObjectLiteralMethod2.ts, 3, 21)) +>T : Symbol(T, Decl(inferentialTypingObjectLiteralMethod2.ts, 3, 21)) + +foo("", { method(p1) { return p1.length } }, { method(p2) { return undefined } }); +>foo : Symbol(foo, Decl(inferentialTypingObjectLiteralMethod2.ts, 2, 1)) +>method : Symbol(method, Decl(inferentialTypingObjectLiteralMethod2.ts, 4, 9)) +>p1 : Symbol(p1, Decl(inferentialTypingObjectLiteralMethod2.ts, 4, 17)) +>p1.length : Symbol(String.length, Decl(lib.d.ts, 414, 19)) +>p1 : Symbol(p1, Decl(inferentialTypingObjectLiteralMethod2.ts, 4, 17)) +>length : Symbol(String.length, Decl(lib.d.ts, 414, 19)) +>method : Symbol(method, Decl(inferentialTypingObjectLiteralMethod2.ts, 4, 46)) +>p2 : Symbol(p2, Decl(inferentialTypingObjectLiteralMethod2.ts, 4, 54)) +>undefined : Symbol(undefined) + diff --git a/tests/baselines/reference/inferentialTypingObjectLiteralMethod2.types b/tests/baselines/reference/inferentialTypingObjectLiteralMethod2.types new file mode 100644 index 00000000000..be937410cef --- /dev/null +++ b/tests/baselines/reference/inferentialTypingObjectLiteralMethod2.types @@ -0,0 +1,43 @@ +=== tests/cases/compiler/inferentialTypingObjectLiteralMethod2.ts === +interface Int { +>Int : Int +>T : T +>U : U + + [s: string]: (x: T) => U; +>s : string +>x : T +>T : T +>U : U +} +declare function foo(x: T, y: Int, z: Int): T; +>foo : (x: T, y: Int, z: Int) => T +>T : T +>U : U +>x : T +>T : T +>y : Int +>Int : Int +>T : T +>U : U +>z : Int +>Int : Int +>U : U +>T : T +>T : T + +foo("", { method(p1) { return p1.length } }, { method(p2) { return undefined } }); +>foo("", { method(p1) { return p1.length } }, { method(p2) { return undefined } }) : string +>foo : (x: T, y: Int, z: Int) => T +>"" : string +>{ method(p1) { return p1.length } } : { [x: string]: (p1: string) => number; method(p1: string): number; } +>method : (p1: string) => number +>p1 : string +>p1.length : number +>p1 : string +>length : number +>{ method(p2) { return undefined } } : { [x: string]: (p2: number) => any; method(p2: number): any; } +>method : (p2: number) => any +>p2 : number +>undefined : undefined + diff --git a/tests/baselines/reference/infinitelyExpandingTypesNonGenericBase.js b/tests/baselines/reference/infinitelyExpandingTypesNonGenericBase.js index 71390b03c83..f057b649cb6 100644 --- a/tests/baselines/reference/infinitelyExpandingTypesNonGenericBase.js +++ b/tests/baselines/reference/infinitelyExpandingTypesNonGenericBase.js @@ -28,8 +28,7 @@ o(A); var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var Functionality = (function () { function Functionality() { diff --git a/tests/baselines/reference/inheritFromGenericTypeParameter.errors.txt b/tests/baselines/reference/inheritFromGenericTypeParameter.errors.txt index a9b3cb4b686..c043e37575c 100644 --- a/tests/baselines/reference/inheritFromGenericTypeParameter.errors.txt +++ b/tests/baselines/reference/inheritFromGenericTypeParameter.errors.txt @@ -1,11 +1,11 @@ -tests/cases/compiler/inheritFromGenericTypeParameter.ts(1,20): error TS2311: A class may only extend another class. +tests/cases/compiler/inheritFromGenericTypeParameter.ts(1,20): error TS2304: Cannot find name 'T'. tests/cases/compiler/inheritFromGenericTypeParameter.ts(2,24): error TS2312: An interface may only extend a class or another interface. ==== tests/cases/compiler/inheritFromGenericTypeParameter.ts (2 errors) ==== class C extends T { } ~ -!!! error TS2311: A class may only extend another class. +!!! error TS2304: Cannot find name 'T'. interface I extends T { } ~ !!! error TS2312: An interface may only extend a class or another interface. \ No newline at end of file diff --git a/tests/baselines/reference/inheritFromGenericTypeParameter.js b/tests/baselines/reference/inheritFromGenericTypeParameter.js index ccf445a26bf..ec6be00785f 100644 --- a/tests/baselines/reference/inheritFromGenericTypeParameter.js +++ b/tests/baselines/reference/inheritFromGenericTypeParameter.js @@ -6,8 +6,7 @@ interface I extends T { } var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var C = (function (_super) { __extends(C, _super); diff --git a/tests/baselines/reference/inheritSameNamePrivatePropertiesFromSameOrigin.js b/tests/baselines/reference/inheritSameNamePrivatePropertiesFromSameOrigin.js index 850741c3666..93494c7256e 100644 --- a/tests/baselines/reference/inheritSameNamePrivatePropertiesFromSameOrigin.js +++ b/tests/baselines/reference/inheritSameNamePrivatePropertiesFromSameOrigin.js @@ -14,8 +14,7 @@ interface A extends C, C2 { // ok var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var B = (function () { function B() { diff --git a/tests/baselines/reference/inheritance.js b/tests/baselines/reference/inheritance.js index f2b5be9335e..b581ae894ae 100644 --- a/tests/baselines/reference/inheritance.js +++ b/tests/baselines/reference/inheritance.js @@ -38,8 +38,7 @@ class Baad extends Good { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var B1 = (function () { function B1() { diff --git a/tests/baselines/reference/inheritance1.js b/tests/baselines/reference/inheritance1.js index e0d4fa974c5..aa7775b9904 100644 --- a/tests/baselines/reference/inheritance1.js +++ b/tests/baselines/reference/inheritance1.js @@ -65,8 +65,7 @@ l1 = c; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var Control = (function () { function Control() { diff --git a/tests/baselines/reference/inheritanceGrandParentPrivateMemberCollision.js b/tests/baselines/reference/inheritanceGrandParentPrivateMemberCollision.js index 0f016233ef3..927ae969049 100644 --- a/tests/baselines/reference/inheritanceGrandParentPrivateMemberCollision.js +++ b/tests/baselines/reference/inheritanceGrandParentPrivateMemberCollision.js @@ -14,8 +14,7 @@ class C extends B { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var A = (function () { function A() { diff --git a/tests/baselines/reference/inheritanceGrandParentPrivateMemberCollisionWithPublicMember.js b/tests/baselines/reference/inheritanceGrandParentPrivateMemberCollisionWithPublicMember.js index 596982a4794..05d8dc2a541 100644 --- a/tests/baselines/reference/inheritanceGrandParentPrivateMemberCollisionWithPublicMember.js +++ b/tests/baselines/reference/inheritanceGrandParentPrivateMemberCollisionWithPublicMember.js @@ -14,8 +14,7 @@ class C extends B { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var A = (function () { function A() { diff --git a/tests/baselines/reference/inheritanceGrandParentPublicMemberCollisionWithPrivateMember.js b/tests/baselines/reference/inheritanceGrandParentPublicMemberCollisionWithPrivateMember.js index ec8ae03b3e3..ddd87251f9f 100644 --- a/tests/baselines/reference/inheritanceGrandParentPublicMemberCollisionWithPrivateMember.js +++ b/tests/baselines/reference/inheritanceGrandParentPublicMemberCollisionWithPrivateMember.js @@ -14,8 +14,7 @@ class C extends B { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var A = (function () { function A() { diff --git a/tests/baselines/reference/inheritanceMemberAccessorOverridingAccessor.js b/tests/baselines/reference/inheritanceMemberAccessorOverridingAccessor.js index 2da2bcbe6fe..eaf34df921b 100644 --- a/tests/baselines/reference/inheritanceMemberAccessorOverridingAccessor.js +++ b/tests/baselines/reference/inheritanceMemberAccessorOverridingAccessor.js @@ -21,8 +21,7 @@ class b extends a { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var a = (function () { function a() { diff --git a/tests/baselines/reference/inheritanceMemberAccessorOverridingMethod.js b/tests/baselines/reference/inheritanceMemberAccessorOverridingMethod.js index 8b58a7f2b35..cd79d8c6964 100644 --- a/tests/baselines/reference/inheritanceMemberAccessorOverridingMethod.js +++ b/tests/baselines/reference/inheritanceMemberAccessorOverridingMethod.js @@ -18,8 +18,7 @@ class b extends a { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var a = (function () { function a() { diff --git a/tests/baselines/reference/inheritanceMemberAccessorOverridingProperty.js b/tests/baselines/reference/inheritanceMemberAccessorOverridingProperty.js index 1864e62b237..18c1ab33952 100644 --- a/tests/baselines/reference/inheritanceMemberAccessorOverridingProperty.js +++ b/tests/baselines/reference/inheritanceMemberAccessorOverridingProperty.js @@ -16,8 +16,7 @@ class b extends a { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var a = (function () { function a() { diff --git a/tests/baselines/reference/inheritanceMemberFuncOverridingAccessor.js b/tests/baselines/reference/inheritanceMemberFuncOverridingAccessor.js index 0b24db92a35..5c254251718 100644 --- a/tests/baselines/reference/inheritanceMemberFuncOverridingAccessor.js +++ b/tests/baselines/reference/inheritanceMemberFuncOverridingAccessor.js @@ -18,8 +18,7 @@ class b extends a { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var a = (function () { function a() { diff --git a/tests/baselines/reference/inheritanceMemberFuncOverridingMethod.js b/tests/baselines/reference/inheritanceMemberFuncOverridingMethod.js index bf1186a5cde..e2d3d9551c2 100644 --- a/tests/baselines/reference/inheritanceMemberFuncOverridingMethod.js +++ b/tests/baselines/reference/inheritanceMemberFuncOverridingMethod.js @@ -15,8 +15,7 @@ class b extends a { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var a = (function () { function a() { diff --git a/tests/baselines/reference/inheritanceMemberFuncOverridingProperty.js b/tests/baselines/reference/inheritanceMemberFuncOverridingProperty.js index 2ecf7edb0e8..b1d64aeb2c8 100644 --- a/tests/baselines/reference/inheritanceMemberFuncOverridingProperty.js +++ b/tests/baselines/reference/inheritanceMemberFuncOverridingProperty.js @@ -13,8 +13,7 @@ class b extends a { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var a = (function () { function a() { diff --git a/tests/baselines/reference/inheritanceMemberPropertyOverridingAccessor.js b/tests/baselines/reference/inheritanceMemberPropertyOverridingAccessor.js index 512ca023dee..bfa5d3fb801 100644 --- a/tests/baselines/reference/inheritanceMemberPropertyOverridingAccessor.js +++ b/tests/baselines/reference/inheritanceMemberPropertyOverridingAccessor.js @@ -17,8 +17,7 @@ class b extends a { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var a = (function () { function a() { diff --git a/tests/baselines/reference/inheritanceMemberPropertyOverridingMethod.js b/tests/baselines/reference/inheritanceMemberPropertyOverridingMethod.js index 975727031e3..d84f4879632 100644 --- a/tests/baselines/reference/inheritanceMemberPropertyOverridingMethod.js +++ b/tests/baselines/reference/inheritanceMemberPropertyOverridingMethod.js @@ -13,8 +13,7 @@ class b extends a { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var a = (function () { function a() { diff --git a/tests/baselines/reference/inheritanceMemberPropertyOverridingProperty.js b/tests/baselines/reference/inheritanceMemberPropertyOverridingProperty.js index b924932e0b4..8677d502273 100644 --- a/tests/baselines/reference/inheritanceMemberPropertyOverridingProperty.js +++ b/tests/baselines/reference/inheritanceMemberPropertyOverridingProperty.js @@ -11,8 +11,7 @@ class b extends a { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var a = (function () { function a() { diff --git a/tests/baselines/reference/inheritanceOfGenericConstructorMethod1.js b/tests/baselines/reference/inheritanceOfGenericConstructorMethod1.js index d62c62410b7..73d3b4aa6cb 100644 --- a/tests/baselines/reference/inheritanceOfGenericConstructorMethod1.js +++ b/tests/baselines/reference/inheritanceOfGenericConstructorMethod1.js @@ -11,8 +11,7 @@ var b3 = new B(); // error, could not select overload for 'new' expression var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var A = (function () { function A() { diff --git a/tests/baselines/reference/inheritanceOfGenericConstructorMethod2.js b/tests/baselines/reference/inheritanceOfGenericConstructorMethod2.js index c54f8b4d317..e7e6228392c 100644 --- a/tests/baselines/reference/inheritanceOfGenericConstructorMethod2.js +++ b/tests/baselines/reference/inheritanceOfGenericConstructorMethod2.js @@ -18,8 +18,7 @@ var n3 = new N.D2(); // no error, D2 var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var M; (function (M) { diff --git a/tests/baselines/reference/inheritanceOfGenericConstructorMethod2.types b/tests/baselines/reference/inheritanceOfGenericConstructorMethod2.types index 119b6a19046..c976e905db7 100644 --- a/tests/baselines/reference/inheritanceOfGenericConstructorMethod2.types +++ b/tests/baselines/reference/inheritanceOfGenericConstructorMethod2.types @@ -14,16 +14,16 @@ module N { export class D1 extends M.C1 { } >D1 : D1 ->M.C1 : any +>M.C1 : M.C1 >M : typeof M ->C1 : M.C1 +>C1 : typeof M.C1 export class D2 extends M.C2 { } >D2 : D2 >T : T ->M.C2 : any +>M.C2 : M.C2 >M : typeof M ->C2 : M.C2 +>C2 : typeof M.C2 >T : T } diff --git a/tests/baselines/reference/inheritanceStaticAccessorOverridingAccessor.js b/tests/baselines/reference/inheritanceStaticAccessorOverridingAccessor.js index 120efc11e27..32f1d20eda1 100644 --- a/tests/baselines/reference/inheritanceStaticAccessorOverridingAccessor.js +++ b/tests/baselines/reference/inheritanceStaticAccessorOverridingAccessor.js @@ -21,8 +21,7 @@ class b extends a { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var a = (function () { function a() { diff --git a/tests/baselines/reference/inheritanceStaticAccessorOverridingMethod.js b/tests/baselines/reference/inheritanceStaticAccessorOverridingMethod.js index 7200f37f94b..7a1a86ced18 100644 --- a/tests/baselines/reference/inheritanceStaticAccessorOverridingMethod.js +++ b/tests/baselines/reference/inheritanceStaticAccessorOverridingMethod.js @@ -18,8 +18,7 @@ class b extends a { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var a = (function () { function a() { diff --git a/tests/baselines/reference/inheritanceStaticAccessorOverridingProperty.js b/tests/baselines/reference/inheritanceStaticAccessorOverridingProperty.js index 2fd5e18dab9..8a142d41c57 100644 --- a/tests/baselines/reference/inheritanceStaticAccessorOverridingProperty.js +++ b/tests/baselines/reference/inheritanceStaticAccessorOverridingProperty.js @@ -16,8 +16,7 @@ class b extends a { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var a = (function () { function a() { diff --git a/tests/baselines/reference/inheritanceStaticFuncOverridingAccessor.js b/tests/baselines/reference/inheritanceStaticFuncOverridingAccessor.js index 812ac57bfe4..7c08ec7649e 100644 --- a/tests/baselines/reference/inheritanceStaticFuncOverridingAccessor.js +++ b/tests/baselines/reference/inheritanceStaticFuncOverridingAccessor.js @@ -18,8 +18,7 @@ class b extends a { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var a = (function () { function a() { diff --git a/tests/baselines/reference/inheritanceStaticFuncOverridingAccessorOfFuncType.js b/tests/baselines/reference/inheritanceStaticFuncOverridingAccessorOfFuncType.js index 224c0326a87..acde620c100 100644 --- a/tests/baselines/reference/inheritanceStaticFuncOverridingAccessorOfFuncType.js +++ b/tests/baselines/reference/inheritanceStaticFuncOverridingAccessorOfFuncType.js @@ -15,8 +15,7 @@ class b extends a { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var a = (function () { function a() { diff --git a/tests/baselines/reference/inheritanceStaticFuncOverridingMethod.js b/tests/baselines/reference/inheritanceStaticFuncOverridingMethod.js index 375f07fd905..abd4d7c1498 100644 --- a/tests/baselines/reference/inheritanceStaticFuncOverridingMethod.js +++ b/tests/baselines/reference/inheritanceStaticFuncOverridingMethod.js @@ -15,8 +15,7 @@ class b extends a { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var a = (function () { function a() { diff --git a/tests/baselines/reference/inheritanceStaticFuncOverridingProperty.js b/tests/baselines/reference/inheritanceStaticFuncOverridingProperty.js index c4d3f7ca420..c2d095e5527 100644 --- a/tests/baselines/reference/inheritanceStaticFuncOverridingProperty.js +++ b/tests/baselines/reference/inheritanceStaticFuncOverridingProperty.js @@ -13,8 +13,7 @@ class b extends a { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var a = (function () { function a() { diff --git a/tests/baselines/reference/inheritanceStaticFuncOverridingPropertyOfFuncType.js b/tests/baselines/reference/inheritanceStaticFuncOverridingPropertyOfFuncType.js index f9513f68585..979f0c36359 100644 --- a/tests/baselines/reference/inheritanceStaticFuncOverridingPropertyOfFuncType.js +++ b/tests/baselines/reference/inheritanceStaticFuncOverridingPropertyOfFuncType.js @@ -13,8 +13,7 @@ class b extends a { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var a = (function () { function a() { diff --git a/tests/baselines/reference/inheritanceStaticFunctionOverridingInstanceProperty.js b/tests/baselines/reference/inheritanceStaticFunctionOverridingInstanceProperty.js index f64615e8a7c..5c6c0e06a6f 100644 --- a/tests/baselines/reference/inheritanceStaticFunctionOverridingInstanceProperty.js +++ b/tests/baselines/reference/inheritanceStaticFunctionOverridingInstanceProperty.js @@ -13,8 +13,7 @@ class b extends a { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var a = (function () { function a() { diff --git a/tests/baselines/reference/inheritanceStaticMembersCompatible.js b/tests/baselines/reference/inheritanceStaticMembersCompatible.js index f1e288c57f5..014d3276189 100644 --- a/tests/baselines/reference/inheritanceStaticMembersCompatible.js +++ b/tests/baselines/reference/inheritanceStaticMembersCompatible.js @@ -11,8 +11,7 @@ class b extends a { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var a = (function () { function a() { diff --git a/tests/baselines/reference/inheritanceStaticMembersIncompatible.js b/tests/baselines/reference/inheritanceStaticMembersIncompatible.js index 66ad8612538..a1728dc6dcb 100644 --- a/tests/baselines/reference/inheritanceStaticMembersIncompatible.js +++ b/tests/baselines/reference/inheritanceStaticMembersIncompatible.js @@ -11,8 +11,7 @@ class b extends a { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var a = (function () { function a() { diff --git a/tests/baselines/reference/inheritanceStaticPropertyOverridingAccessor.js b/tests/baselines/reference/inheritanceStaticPropertyOverridingAccessor.js index 310f2127e7e..b81b6cd1d78 100644 --- a/tests/baselines/reference/inheritanceStaticPropertyOverridingAccessor.js +++ b/tests/baselines/reference/inheritanceStaticPropertyOverridingAccessor.js @@ -15,8 +15,7 @@ class b extends a { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var a = (function () { function a() { diff --git a/tests/baselines/reference/inheritanceStaticPropertyOverridingMethod.js b/tests/baselines/reference/inheritanceStaticPropertyOverridingMethod.js index 3e8a444d772..9afa969af65 100644 --- a/tests/baselines/reference/inheritanceStaticPropertyOverridingMethod.js +++ b/tests/baselines/reference/inheritanceStaticPropertyOverridingMethod.js @@ -13,8 +13,7 @@ class b extends a { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var a = (function () { function a() { diff --git a/tests/baselines/reference/inheritanceStaticPropertyOverridingProperty.js b/tests/baselines/reference/inheritanceStaticPropertyOverridingProperty.js index 088cfa9b1f9..fcecca62774 100644 --- a/tests/baselines/reference/inheritanceStaticPropertyOverridingProperty.js +++ b/tests/baselines/reference/inheritanceStaticPropertyOverridingProperty.js @@ -11,8 +11,7 @@ class b extends a { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var a = (function () { function a() { diff --git a/tests/baselines/reference/inheritedConstructorWithRestParams.js b/tests/baselines/reference/inheritedConstructorWithRestParams.js index 45f4fe72535..a0bb2ed8dc1 100644 --- a/tests/baselines/reference/inheritedConstructorWithRestParams.js +++ b/tests/baselines/reference/inheritedConstructorWithRestParams.js @@ -18,8 +18,7 @@ new Derived(3); var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var Base = (function () { function Base() { diff --git a/tests/baselines/reference/inheritedConstructorWithRestParams2.js b/tests/baselines/reference/inheritedConstructorWithRestParams2.js index eeb0413d1ec..9b87465233c 100644 --- a/tests/baselines/reference/inheritedConstructorWithRestParams2.js +++ b/tests/baselines/reference/inheritedConstructorWithRestParams2.js @@ -38,8 +38,7 @@ new Derived("", 3, "", ""); var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var IBaseBase = (function () { function IBaseBase(x) { diff --git a/tests/baselines/reference/inheritedModuleMembersForClodule.js b/tests/baselines/reference/inheritedModuleMembersForClodule.js index 75a2f13fed7..50f41af2c09 100644 --- a/tests/baselines/reference/inheritedModuleMembersForClodule.js +++ b/tests/baselines/reference/inheritedModuleMembersForClodule.js @@ -25,8 +25,7 @@ class E extends D { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var C = (function () { function C() { diff --git a/tests/baselines/reference/inlineSourceMap2.errors.txt b/tests/baselines/reference/inlineSourceMap2.errors.txt index 75db5689c66..2d8bc4be0c1 100644 --- a/tests/baselines/reference/inlineSourceMap2.errors.txt +++ b/tests/baselines/reference/inlineSourceMap2.errors.txt @@ -1,12 +1,12 @@ -error TS5050: Option 'mapRoot' cannot be specified with option 'inlineSourceMap'. -error TS5049: Option 'sourceRoot' cannot be specified with option 'inlineSourceMap'. error TS5048: Option 'sourceMap' cannot be specified with option 'inlineSourceMap'. +error TS5049: Option 'sourceRoot' cannot be specified with option 'inlineSourceMap'. +error TS5050: Option 'mapRoot' cannot be specified with option 'inlineSourceMap'. tests/cases/compiler/inlineSourceMap2.ts(5,1): error TS2304: Cannot find name 'console'. -!!! error TS5050: Option 'mapRoot' cannot be specified with option 'inlineSourceMap'. -!!! error TS5049: Option 'sourceRoot' cannot be specified with option 'inlineSourceMap'. !!! error TS5048: Option 'sourceMap' cannot be specified with option 'inlineSourceMap'. +!!! error TS5049: Option 'sourceRoot' cannot be specified with option 'inlineSourceMap'. +!!! error TS5050: Option 'mapRoot' cannot be specified with option 'inlineSourceMap'. ==== tests/cases/compiler/inlineSourceMap2.ts (1 errors) ==== // configuration errors diff --git a/tests/baselines/reference/instancePropertiesInheritedIntoClassType.js b/tests/baselines/reference/instancePropertiesInheritedIntoClassType.js index 9e8e6d26b31..548cb77b878 100644 --- a/tests/baselines/reference/instancePropertiesInheritedIntoClassType.js +++ b/tests/baselines/reference/instancePropertiesInheritedIntoClassType.js @@ -46,8 +46,7 @@ module Generic { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var NonGeneric; (function (NonGeneric) { diff --git a/tests/baselines/reference/instanceSubtypeCheck2.js b/tests/baselines/reference/instanceSubtypeCheck2.js index e02a2b2afad..59043b29b4e 100644 --- a/tests/baselines/reference/instanceSubtypeCheck2.js +++ b/tests/baselines/reference/instanceSubtypeCheck2.js @@ -11,8 +11,7 @@ class C2 extends C1 { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var C1 = (function () { function C1() { diff --git a/tests/baselines/reference/instantiatedReturnTypeContravariance.js b/tests/baselines/reference/instantiatedReturnTypeContravariance.js index 678f324797f..2484816fe33 100644 --- a/tests/baselines/reference/instantiatedReturnTypeContravariance.js +++ b/tests/baselines/reference/instantiatedReturnTypeContravariance.js @@ -34,8 +34,7 @@ return null; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var c = (function () { function c() { diff --git a/tests/baselines/reference/interfaceExtendsClass1.js b/tests/baselines/reference/interfaceExtendsClass1.js index 5e72b36ef30..2fbe01bdf67 100644 --- a/tests/baselines/reference/interfaceExtendsClass1.js +++ b/tests/baselines/reference/interfaceExtendsClass1.js @@ -22,8 +22,7 @@ class Location { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var Control = (function () { function Control() { diff --git a/tests/baselines/reference/interfaceExtendsClassWithPrivate1.js b/tests/baselines/reference/interfaceExtendsClassWithPrivate1.js index dac502b9ca3..9a6e92c3e2b 100644 --- a/tests/baselines/reference/interfaceExtendsClassWithPrivate1.js +++ b/tests/baselines/reference/interfaceExtendsClassWithPrivate1.js @@ -31,8 +31,7 @@ d = c; // error var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var C = (function () { function C() { diff --git a/tests/baselines/reference/interfaceExtendsClassWithPrivate2.js b/tests/baselines/reference/interfaceExtendsClassWithPrivate2.js index c6a11c1d3ab..44738036f96 100644 --- a/tests/baselines/reference/interfaceExtendsClassWithPrivate2.js +++ b/tests/baselines/reference/interfaceExtendsClassWithPrivate2.js @@ -27,8 +27,7 @@ class D2 extends C implements I { // error var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var C = (function () { function C() { diff --git a/tests/baselines/reference/interfaceImplementation8.js b/tests/baselines/reference/interfaceImplementation8.js index 64b4c453829..cb6eaa12450 100644 --- a/tests/baselines/reference/interfaceImplementation8.js +++ b/tests/baselines/reference/interfaceImplementation8.js @@ -44,8 +44,7 @@ class C8 extends C7 implements i2{ var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var C1 = (function () { function C1() { diff --git a/tests/baselines/reference/interfacesWithPredefinedTypesAsNames.errors.txt b/tests/baselines/reference/interfacesWithPredefinedTypesAsNames.errors.txt index 91cd267b596..902e4b448b5 100644 --- a/tests/baselines/reference/interfacesWithPredefinedTypesAsNames.errors.txt +++ b/tests/baselines/reference/interfacesWithPredefinedTypesAsNames.errors.txt @@ -2,10 +2,11 @@ tests/cases/conformance/interfaces/interfaceDeclarations/interfacesWithPredefine tests/cases/conformance/interfaces/interfaceDeclarations/interfacesWithPredefinedTypesAsNames.ts(2,11): error TS2427: Interface name cannot be 'number' tests/cases/conformance/interfaces/interfaceDeclarations/interfacesWithPredefinedTypesAsNames.ts(3,11): error TS2427: Interface name cannot be 'string' tests/cases/conformance/interfaces/interfaceDeclarations/interfacesWithPredefinedTypesAsNames.ts(4,11): error TS2427: Interface name cannot be 'boolean' -tests/cases/conformance/interfaces/interfaceDeclarations/interfacesWithPredefinedTypesAsNames.ts(5,11): error TS1003: Identifier expected. +tests/cases/conformance/interfaces/interfaceDeclarations/interfacesWithPredefinedTypesAsNames.ts(5,1): error TS2304: Cannot find name 'interface'. +tests/cases/conformance/interfaces/interfaceDeclarations/interfacesWithPredefinedTypesAsNames.ts(5,11): error TS1005: ';' expected. -==== tests/cases/conformance/interfaces/interfaceDeclarations/interfacesWithPredefinedTypesAsNames.ts (5 errors) ==== +==== tests/cases/conformance/interfaces/interfaceDeclarations/interfacesWithPredefinedTypesAsNames.ts (6 errors) ==== interface any { } ~~~ !!! error TS2427: Interface name cannot be 'any' @@ -19,5 +20,7 @@ tests/cases/conformance/interfaces/interfaceDeclarations/interfacesWithPredefine ~~~~~~~ !!! error TS2427: Interface name cannot be 'boolean' interface void {} + ~~~~~~~~~ +!!! error TS2304: Cannot find name 'interface'. ~~~~ -!!! error TS1003: Identifier expected. \ No newline at end of file +!!! error TS1005: ';' expected. \ No newline at end of file diff --git a/tests/baselines/reference/interfacesWithPredefinedTypesAsNames.js b/tests/baselines/reference/interfacesWithPredefinedTypesAsNames.js index b79dfc12a04..ca186b1cef1 100644 --- a/tests/baselines/reference/interfacesWithPredefinedTypesAsNames.js +++ b/tests/baselines/reference/interfacesWithPredefinedTypesAsNames.js @@ -6,4 +6,5 @@ interface boolean { } interface void {} //// [interfacesWithPredefinedTypesAsNames.js] +interface; void {}; diff --git a/tests/baselines/reference/invalidModuleWithStatementsOfEveryKind.js b/tests/baselines/reference/invalidModuleWithStatementsOfEveryKind.js index 4b3ab1b6d88..0b662b56f06 100644 --- a/tests/baselines/reference/invalidModuleWithStatementsOfEveryKind.js +++ b/tests/baselines/reference/invalidModuleWithStatementsOfEveryKind.js @@ -83,8 +83,7 @@ module YYY4 { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var Y; (function (Y) { diff --git a/tests/baselines/reference/invalidMultipleVariableDeclarations.js b/tests/baselines/reference/invalidMultipleVariableDeclarations.js index 31d0e44c918..b239a3dc1dd 100644 --- a/tests/baselines/reference/invalidMultipleVariableDeclarations.js +++ b/tests/baselines/reference/invalidMultipleVariableDeclarations.js @@ -57,8 +57,7 @@ var m = M.A; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var C = (function () { function C() { diff --git a/tests/baselines/reference/invalidReturnStatements.js b/tests/baselines/reference/invalidReturnStatements.js index 50977334f4c..5fbe8c4dc37 100644 --- a/tests/baselines/reference/invalidReturnStatements.js +++ b/tests/baselines/reference/invalidReturnStatements.js @@ -24,8 +24,7 @@ function fn11(): D { return new C(); } var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; // all the following should be error function fn1() { } diff --git a/tests/baselines/reference/isArray.js b/tests/baselines/reference/isArray.js new file mode 100644 index 00000000000..a90898fd65b --- /dev/null +++ b/tests/baselines/reference/isArray.js @@ -0,0 +1,19 @@ +//// [isArray.ts] +var maybeArray: number | number[]; + + +if (Array.isArray(maybeArray)) { + maybeArray.length; // OK +} +else { + maybeArray.toFixed(); // OK +} + +//// [isArray.js] +var maybeArray; +if (Array.isArray(maybeArray)) { + maybeArray.length; // OK +} +else { + maybeArray.toFixed(); // OK +} diff --git a/tests/baselines/reference/isArray.symbols b/tests/baselines/reference/isArray.symbols new file mode 100644 index 00000000000..75351b377be --- /dev/null +++ b/tests/baselines/reference/isArray.symbols @@ -0,0 +1,22 @@ +=== tests/cases/compiler/isArray.ts === +var maybeArray: number | number[]; +>maybeArray : Symbol(maybeArray, Decl(isArray.ts, 0, 3)) + + +if (Array.isArray(maybeArray)) { +>Array.isArray : Symbol(ArrayConstructor.isArray, Decl(lib.d.ts, 1166, 28)) +>Array : Symbol(Array, Decl(lib.d.ts, 1000, 23), Decl(lib.d.ts, 1171, 11)) +>isArray : Symbol(ArrayConstructor.isArray, Decl(lib.d.ts, 1166, 28)) +>maybeArray : Symbol(maybeArray, Decl(isArray.ts, 0, 3)) + + maybeArray.length; // OK +>maybeArray.length : Symbol(Array.length, Decl(lib.d.ts, 1007, 20)) +>maybeArray : Symbol(maybeArray, Decl(isArray.ts, 0, 3)) +>length : Symbol(Array.length, Decl(lib.d.ts, 1007, 20)) +} +else { + maybeArray.toFixed(); // OK +>maybeArray.toFixed : Symbol(Number.toFixed, Decl(lib.d.ts, 463, 37)) +>maybeArray : Symbol(maybeArray, Decl(isArray.ts, 0, 3)) +>toFixed : Symbol(Number.toFixed, Decl(lib.d.ts, 463, 37)) +} diff --git a/tests/baselines/reference/isArray.types b/tests/baselines/reference/isArray.types new file mode 100644 index 00000000000..8865ff73bc0 --- /dev/null +++ b/tests/baselines/reference/isArray.types @@ -0,0 +1,24 @@ +=== tests/cases/compiler/isArray.ts === +var maybeArray: number | number[]; +>maybeArray : number | number[] + + +if (Array.isArray(maybeArray)) { +>Array.isArray(maybeArray) : boolean +>Array.isArray : (arg: any) => boolean +>Array : ArrayConstructor +>isArray : (arg: any) => boolean +>maybeArray : number | number[] + + maybeArray.length; // OK +>maybeArray.length : number +>maybeArray : number[] +>length : number +} +else { + maybeArray.toFixed(); // OK +>maybeArray.toFixed() : string +>maybeArray.toFixed : (fractionDigits?: number) => string +>maybeArray : number +>toFixed : (fractionDigits?: number) => string +} diff --git a/tests/baselines/reference/isolatedModulesAmbientConstEnum.errors.txt b/tests/baselines/reference/isolatedModulesAmbientConstEnum.errors.txt new file mode 100644 index 00000000000..bb8a5202bc5 --- /dev/null +++ b/tests/baselines/reference/isolatedModulesAmbientConstEnum.errors.txt @@ -0,0 +1,10 @@ +tests/cases/compiler/isolatedModulesAmbientConstEnum.ts(3,20): error TS1209: Ambient const enums are not allowed when the '--isolatedModules' flag is provided. + + +==== tests/cases/compiler/isolatedModulesAmbientConstEnum.ts (1 errors) ==== + + + declare const enum E { X = 1} + ~ +!!! error TS1209: Ambient const enums are not allowed when the '--isolatedModules' flag is provided. + export var y; \ No newline at end of file diff --git a/tests/baselines/reference/isolatedModulesAmbientConstEnum.js b/tests/baselines/reference/isolatedModulesAmbientConstEnum.js new file mode 100644 index 00000000000..7742122b687 --- /dev/null +++ b/tests/baselines/reference/isolatedModulesAmbientConstEnum.js @@ -0,0 +1,8 @@ +//// [isolatedModulesAmbientConstEnum.ts] + + +declare const enum E { X = 1} +export var y; + +//// [isolatedModulesAmbientConstEnum.js] +export var y; diff --git a/tests/baselines/reference/isolatedModulesDeclaration.errors.txt b/tests/baselines/reference/isolatedModulesDeclaration.errors.txt new file mode 100644 index 00000000000..de5cb97586c --- /dev/null +++ b/tests/baselines/reference/isolatedModulesDeclaration.errors.txt @@ -0,0 +1,7 @@ +error TS5044: Option 'declaration' cannot be specified with option 'isolatedModules'. + + +!!! error TS5044: Option 'declaration' cannot be specified with option 'isolatedModules'. +==== tests/cases/compiler/isolatedModulesDeclaration.ts (0 errors) ==== + + export var x; \ No newline at end of file diff --git a/tests/baselines/reference/isolatedModulesDeclaration.js b/tests/baselines/reference/isolatedModulesDeclaration.js new file mode 100644 index 00000000000..12e6f23f92e --- /dev/null +++ b/tests/baselines/reference/isolatedModulesDeclaration.js @@ -0,0 +1,10 @@ +//// [isolatedModulesDeclaration.ts] + +export var x; + +//// [isolatedModulesDeclaration.js] +export var x; + + +//// [isolatedModulesDeclaration.d.ts] +export declare var x: any; diff --git a/tests/baselines/reference/isolatedModulesES6.js b/tests/baselines/reference/isolatedModulesES6.js new file mode 100644 index 00000000000..eb2ee3ee33a --- /dev/null +++ b/tests/baselines/reference/isolatedModulesES6.js @@ -0,0 +1,5 @@ +//// [isolatedModulesES6.ts] +export var x; + +//// [isolatedModulesES6.js] +export var x; diff --git a/tests/baselines/reference/isolatedModulesES6.symbols b/tests/baselines/reference/isolatedModulesES6.symbols new file mode 100644 index 00000000000..c705cbc5af8 --- /dev/null +++ b/tests/baselines/reference/isolatedModulesES6.symbols @@ -0,0 +1,4 @@ +=== tests/cases/compiler/isolatedModulesES6.ts === +export var x; +>x : Symbol(x, Decl(isolatedModulesES6.ts, 0, 10)) + diff --git a/tests/baselines/reference/isolatedModulesES6.types b/tests/baselines/reference/isolatedModulesES6.types new file mode 100644 index 00000000000..898b9715ca4 --- /dev/null +++ b/tests/baselines/reference/isolatedModulesES6.types @@ -0,0 +1,4 @@ +=== tests/cases/compiler/isolatedModulesES6.ts === +export var x; +>x : any + diff --git a/tests/baselines/reference/isolatedModulesImportExportElision.errors.txt b/tests/baselines/reference/isolatedModulesImportExportElision.errors.txt new file mode 100644 index 00000000000..8c6881a9bc1 --- /dev/null +++ b/tests/baselines/reference/isolatedModulesImportExportElision.errors.txt @@ -0,0 +1,28 @@ +tests/cases/compiler/isolatedModulesImportExportElision.ts(2,17): error TS2307: Cannot find module 'module'. +tests/cases/compiler/isolatedModulesImportExportElision.ts(3,18): error TS2307: Cannot find module 'module'. +tests/cases/compiler/isolatedModulesImportExportElision.ts(4,21): error TS2307: Cannot find module 'module'. +tests/cases/compiler/isolatedModulesImportExportElision.ts(12,18): error TS2307: Cannot find module 'module'. + + +==== tests/cases/compiler/isolatedModulesImportExportElision.ts (4 errors) ==== + + import {c} from "module" + ~~~~~~~~ +!!! error TS2307: Cannot find module 'module'. + import {c2} from "module" + ~~~~~~~~ +!!! error TS2307: Cannot find module 'module'. + import * as ns from "module" + ~~~~~~~~ +!!! error TS2307: Cannot find module 'module'. + + class C extends c2.C { + } + + let x = new c(); + let y = ns.value; + + export {c1} from "module"; + ~~~~~~~~ +!!! error TS2307: Cannot find module 'module'. + export var z = x; \ No newline at end of file diff --git a/tests/baselines/reference/separateCompilationImportExportElision.js b/tests/baselines/reference/isolatedModulesImportExportElision.js similarity index 78% rename from tests/baselines/reference/separateCompilationImportExportElision.js rename to tests/baselines/reference/isolatedModulesImportExportElision.js index cfa57980249..8cb65747e6f 100644 --- a/tests/baselines/reference/separateCompilationImportExportElision.js +++ b/tests/baselines/reference/isolatedModulesImportExportElision.js @@ -1,4 +1,4 @@ -//// [separateCompilationImportExportElision.ts] +//// [isolatedModulesImportExportElision.ts] import {c} from "module" import {c2} from "module" @@ -13,12 +13,11 @@ let y = ns.value; export {c1} from "module"; export var z = x; -//// [separateCompilationImportExportElision.js] +//// [isolatedModulesImportExportElision.js] var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var module_1 = require("module"); var module_2 = require("module"); diff --git a/tests/baselines/reference/isolatedModulesNoEmitOnError.errors.txt b/tests/baselines/reference/isolatedModulesNoEmitOnError.errors.txt new file mode 100644 index 00000000000..68b2747cf6b --- /dev/null +++ b/tests/baselines/reference/isolatedModulesNoEmitOnError.errors.txt @@ -0,0 +1,7 @@ +error TS5045: Option 'noEmitOnError' cannot be specified with option 'isolatedModules'. + + +!!! error TS5045: Option 'noEmitOnError' cannot be specified with option 'isolatedModules'. +==== tests/cases/compiler/isolatedModulesNoEmitOnError.ts (0 errors) ==== + + export var x; \ No newline at end of file diff --git a/tests/baselines/reference/isolatedModulesNoExternalModule.errors.txt b/tests/baselines/reference/isolatedModulesNoExternalModule.errors.txt new file mode 100644 index 00000000000..d00520a0618 --- /dev/null +++ b/tests/baselines/reference/isolatedModulesNoExternalModule.errors.txt @@ -0,0 +1,8 @@ +tests/cases/compiler/isolatedModulesNoExternalModule.ts(2,1): error TS1208: Cannot compile namespaces when the '--isolatedModules' flag is provided. + + +==== tests/cases/compiler/isolatedModulesNoExternalModule.ts (1 errors) ==== + + var x; + ~~~ +!!! error TS1208: Cannot compile namespaces when the '--isolatedModules' flag is provided. \ No newline at end of file diff --git a/tests/baselines/reference/isolatedModulesNoExternalModule.js b/tests/baselines/reference/isolatedModulesNoExternalModule.js new file mode 100644 index 00000000000..dd5d23a538c --- /dev/null +++ b/tests/baselines/reference/isolatedModulesNoExternalModule.js @@ -0,0 +1,6 @@ +//// [isolatedModulesNoExternalModule.ts] + +var x; + +//// [isolatedModulesNoExternalModule.js] +var x; diff --git a/tests/baselines/reference/separateCompilationNonAmbientConstEnum.js b/tests/baselines/reference/isolatedModulesNonAmbientConstEnum.js similarity index 58% rename from tests/baselines/reference/separateCompilationNonAmbientConstEnum.js rename to tests/baselines/reference/isolatedModulesNonAmbientConstEnum.js index 74096adca1f..efdba17dc93 100644 --- a/tests/baselines/reference/separateCompilationNonAmbientConstEnum.js +++ b/tests/baselines/reference/isolatedModulesNonAmbientConstEnum.js @@ -1,10 +1,10 @@ -//// [separateCompilationNonAmbientConstEnum.ts] +//// [isolatedModulesNonAmbientConstEnum.ts] const enum E { X = 100 }; var e = E.X; export var x; -//// [separateCompilationNonAmbientConstEnum.js] +//// [isolatedModulesNonAmbientConstEnum.js] var E; (function (E) { E[E["X"] = 100] = "X"; diff --git a/tests/baselines/reference/isolatedModulesNonAmbientConstEnum.symbols b/tests/baselines/reference/isolatedModulesNonAmbientConstEnum.symbols new file mode 100644 index 00000000000..5e30fd0b2ff --- /dev/null +++ b/tests/baselines/reference/isolatedModulesNonAmbientConstEnum.symbols @@ -0,0 +1,15 @@ +=== tests/cases/compiler/isolatedModulesNonAmbientConstEnum.ts === + +const enum E { X = 100 }; +>E : Symbol(E, Decl(isolatedModulesNonAmbientConstEnum.ts, 0, 0)) +>X : Symbol(E.X, Decl(isolatedModulesNonAmbientConstEnum.ts, 1, 14)) + +var e = E.X; +>e : Symbol(e, Decl(isolatedModulesNonAmbientConstEnum.ts, 2, 3)) +>E.X : Symbol(E.X, Decl(isolatedModulesNonAmbientConstEnum.ts, 1, 14)) +>E : Symbol(E, Decl(isolatedModulesNonAmbientConstEnum.ts, 0, 0)) +>X : Symbol(E.X, Decl(isolatedModulesNonAmbientConstEnum.ts, 1, 14)) + +export var x; +>x : Symbol(x, Decl(isolatedModulesNonAmbientConstEnum.ts, 3, 10)) + diff --git a/tests/baselines/reference/separateCompilationNonAmbientConstEnum.types b/tests/baselines/reference/isolatedModulesNonAmbientConstEnum.types similarity index 60% rename from tests/baselines/reference/separateCompilationNonAmbientConstEnum.types rename to tests/baselines/reference/isolatedModulesNonAmbientConstEnum.types index ce55b80f41d..d7e83b81070 100644 --- a/tests/baselines/reference/separateCompilationNonAmbientConstEnum.types +++ b/tests/baselines/reference/isolatedModulesNonAmbientConstEnum.types @@ -1,4 +1,4 @@ -=== tests/cases/compiler/separateCompilationNonAmbientConstEnum.ts === +=== tests/cases/compiler/isolatedModulesNonAmbientConstEnum.ts === const enum E { X = 100 }; >E : E diff --git a/tests/baselines/reference/separateCompilationOut.errors.txt b/tests/baselines/reference/isolatedModulesOut.errors.txt similarity index 50% rename from tests/baselines/reference/separateCompilationOut.errors.txt rename to tests/baselines/reference/isolatedModulesOut.errors.txt index 9017809901f..8234ba94585 100644 --- a/tests/baselines/reference/separateCompilationOut.errors.txt +++ b/tests/baselines/reference/isolatedModulesOut.errors.txt @@ -1,12 +1,12 @@ -error TS5046: Option 'out' cannot be specified with option 'separateCompilation'. -tests/cases/compiler/file2.ts(1,1): error TS1208: Cannot compile namespaces when the '--separateCompilation' flag is provided. +error TS5046: Option 'out' cannot be specified with option 'isolatedModules'. +tests/cases/compiler/file2.ts(1,1): error TS1208: Cannot compile namespaces when the '--isolatedModules' flag is provided. -!!! error TS5046: Option 'out' cannot be specified with option 'separateCompilation'. +!!! error TS5046: Option 'out' cannot be specified with option 'isolatedModules'. ==== tests/cases/compiler/file1.ts (0 errors) ==== export var x; ==== tests/cases/compiler/file2.ts (1 errors) ==== var y; ~~~ -!!! error TS1208: Cannot compile namespaces when the '--separateCompilation' flag is provided. \ No newline at end of file +!!! error TS1208: Cannot compile namespaces when the '--isolatedModules' flag is provided. \ No newline at end of file diff --git a/tests/baselines/reference/separateCompilationOut.js b/tests/baselines/reference/isolatedModulesOut.js similarity index 60% rename from tests/baselines/reference/separateCompilationOut.js rename to tests/baselines/reference/isolatedModulesOut.js index 67dd2dcfbfa..ca5eb2b7579 100644 --- a/tests/baselines/reference/separateCompilationOut.js +++ b/tests/baselines/reference/isolatedModulesOut.js @@ -1,4 +1,4 @@ -//// [tests/cases/compiler/separateCompilationOut.ts] //// +//// [tests/cases/compiler/isolatedModulesOut.ts] //// //// [file1.ts] diff --git a/tests/baselines/reference/isolatedModulesPlainFile-AMD.errors.txt b/tests/baselines/reference/isolatedModulesPlainFile-AMD.errors.txt new file mode 100644 index 00000000000..680070a73c8 --- /dev/null +++ b/tests/baselines/reference/isolatedModulesPlainFile-AMD.errors.txt @@ -0,0 +1,10 @@ +tests/cases/compiler/isolatedModulesPlainFile-AMD.ts(2,1): error TS1208: Cannot compile namespaces when the '--isolatedModules' flag is provided. + + +==== tests/cases/compiler/isolatedModulesPlainFile-AMD.ts (1 errors) ==== + + declare function run(a: number): void; + ~~~~~~~ +!!! error TS1208: Cannot compile namespaces when the '--isolatedModules' flag is provided. + run(1); + \ No newline at end of file diff --git a/tests/baselines/reference/separateCompilationPlainFile-AMD.js b/tests/baselines/reference/isolatedModulesPlainFile-AMD.js similarity index 57% rename from tests/baselines/reference/separateCompilationPlainFile-AMD.js rename to tests/baselines/reference/isolatedModulesPlainFile-AMD.js index e3e9fc1eaeb..7f4f4219123 100644 --- a/tests/baselines/reference/separateCompilationPlainFile-AMD.js +++ b/tests/baselines/reference/isolatedModulesPlainFile-AMD.js @@ -1,10 +1,10 @@ -//// [separateCompilationPlainFile-AMD.ts] +//// [isolatedModulesPlainFile-AMD.ts] declare function run(a: number): void; run(1); -//// [separateCompilationPlainFile-AMD.js] +//// [isolatedModulesPlainFile-AMD.js] define(["require", "exports"], function (require, exports) { run(1); }); diff --git a/tests/baselines/reference/isolatedModulesPlainFile-CommonJS.errors.txt b/tests/baselines/reference/isolatedModulesPlainFile-CommonJS.errors.txt new file mode 100644 index 00000000000..d1f0ca3caad --- /dev/null +++ b/tests/baselines/reference/isolatedModulesPlainFile-CommonJS.errors.txt @@ -0,0 +1,10 @@ +tests/cases/compiler/isolatedModulesPlainFile-CommonJS.ts(2,1): error TS1208: Cannot compile namespaces when the '--isolatedModules' flag is provided. + + +==== tests/cases/compiler/isolatedModulesPlainFile-CommonJS.ts (1 errors) ==== + + declare function run(a: number): void; + ~~~~~~~ +!!! error TS1208: Cannot compile namespaces when the '--isolatedModules' flag is provided. + run(1); + \ No newline at end of file diff --git a/tests/baselines/reference/isolatedModulesPlainFile-CommonJS.js b/tests/baselines/reference/isolatedModulesPlainFile-CommonJS.js new file mode 100644 index 00000000000..7026a7d9bed --- /dev/null +++ b/tests/baselines/reference/isolatedModulesPlainFile-CommonJS.js @@ -0,0 +1,8 @@ +//// [isolatedModulesPlainFile-CommonJS.ts] + +declare function run(a: number): void; +run(1); + + +//// [isolatedModulesPlainFile-CommonJS.js] +run(1); diff --git a/tests/baselines/reference/isolatedModulesPlainFile-ES6.errors.txt b/tests/baselines/reference/isolatedModulesPlainFile-ES6.errors.txt new file mode 100644 index 00000000000..d46fce22fd7 --- /dev/null +++ b/tests/baselines/reference/isolatedModulesPlainFile-ES6.errors.txt @@ -0,0 +1,10 @@ +tests/cases/compiler/isolatedModulesPlainFile-ES6.ts(2,1): error TS1208: Cannot compile namespaces when the '--isolatedModules' flag is provided. + + +==== tests/cases/compiler/isolatedModulesPlainFile-ES6.ts (1 errors) ==== + + declare function run(a: number): void; + ~~~~~~~ +!!! error TS1208: Cannot compile namespaces when the '--isolatedModules' flag is provided. + run(1); + \ No newline at end of file diff --git a/tests/baselines/reference/isolatedModulesPlainFile-ES6.js b/tests/baselines/reference/isolatedModulesPlainFile-ES6.js new file mode 100644 index 00000000000..245d3fe668f --- /dev/null +++ b/tests/baselines/reference/isolatedModulesPlainFile-ES6.js @@ -0,0 +1,8 @@ +//// [isolatedModulesPlainFile-ES6.ts] + +declare function run(a: number): void; +run(1); + + +//// [isolatedModulesPlainFile-ES6.js] +run(1); diff --git a/tests/baselines/reference/isolatedModulesPlainFile-System.errors.txt b/tests/baselines/reference/isolatedModulesPlainFile-System.errors.txt new file mode 100644 index 00000000000..fe1a2f80018 --- /dev/null +++ b/tests/baselines/reference/isolatedModulesPlainFile-System.errors.txt @@ -0,0 +1,10 @@ +tests/cases/compiler/isolatedModulesPlainFile-System.ts(2,1): error TS1208: Cannot compile namespaces when the '--isolatedModules' flag is provided. + + +==== tests/cases/compiler/isolatedModulesPlainFile-System.ts (1 errors) ==== + + declare function run(a: number): void; + ~~~~~~~ +!!! error TS1208: Cannot compile namespaces when the '--isolatedModules' flag is provided. + run(1); + \ No newline at end of file diff --git a/tests/baselines/reference/separateCompilationPlainFile-System.js b/tests/baselines/reference/isolatedModulesPlainFile-System.js similarity index 65% rename from tests/baselines/reference/separateCompilationPlainFile-System.js rename to tests/baselines/reference/isolatedModulesPlainFile-System.js index c256ed7862a..b924a3b21f9 100644 --- a/tests/baselines/reference/separateCompilationPlainFile-System.js +++ b/tests/baselines/reference/isolatedModulesPlainFile-System.js @@ -1,10 +1,10 @@ -//// [separateCompilationPlainFile-System.ts] +//// [isolatedModulesPlainFile-System.ts] declare function run(a: number): void; run(1); -//// [separateCompilationPlainFile-System.js] +//// [isolatedModulesPlainFile-System.js] System.register([], function(exports_1) { return { setters:[], diff --git a/tests/baselines/reference/isolatedModulesPlainFile-UMD.errors.txt b/tests/baselines/reference/isolatedModulesPlainFile-UMD.errors.txt new file mode 100644 index 00000000000..24c5c86f8f8 --- /dev/null +++ b/tests/baselines/reference/isolatedModulesPlainFile-UMD.errors.txt @@ -0,0 +1,10 @@ +tests/cases/compiler/isolatedModulesPlainFile-UMD.ts(2,1): error TS1208: Cannot compile namespaces when the '--isolatedModules' flag is provided. + + +==== tests/cases/compiler/isolatedModulesPlainFile-UMD.ts (1 errors) ==== + + declare function run(a: number): void; + ~~~~~~~ +!!! error TS1208: Cannot compile namespaces when the '--isolatedModules' flag is provided. + run(1); + \ No newline at end of file diff --git a/tests/baselines/reference/separateCompilationPlainFile-UMD.js b/tests/baselines/reference/isolatedModulesPlainFile-UMD.js similarity index 80% rename from tests/baselines/reference/separateCompilationPlainFile-UMD.js rename to tests/baselines/reference/isolatedModulesPlainFile-UMD.js index 6a145e7d239..0ed6e83a37f 100644 --- a/tests/baselines/reference/separateCompilationPlainFile-UMD.js +++ b/tests/baselines/reference/isolatedModulesPlainFile-UMD.js @@ -1,10 +1,10 @@ -//// [separateCompilationPlainFile-UMD.ts] +//// [isolatedModulesPlainFile-UMD.ts] declare function run(a: number): void; run(1); -//// [separateCompilationPlainFile-UMD.js] +//// [isolatedModulesPlainFile-UMD.js] (function (deps, factory) { if (typeof module === 'object' && typeof module.exports === 'object') { var v = factory(require, exports); if (v !== undefined) module.exports = v; diff --git a/tests/baselines/reference/isolatedModulesSourceMap.errors.txt b/tests/baselines/reference/isolatedModulesSourceMap.errors.txt new file mode 100644 index 00000000000..6383e85ecd5 --- /dev/null +++ b/tests/baselines/reference/isolatedModulesSourceMap.errors.txt @@ -0,0 +1,7 @@ +error TS5043: Option 'sourceMap' cannot be specified with option 'isolatedModules'. + + +!!! error TS5043: Option 'sourceMap' cannot be specified with option 'isolatedModules'. +==== tests/cases/compiler/isolatedModulesSourceMap.ts (0 errors) ==== + + export var x; \ No newline at end of file diff --git a/tests/baselines/reference/isolatedModulesSourceMap.js b/tests/baselines/reference/isolatedModulesSourceMap.js new file mode 100644 index 00000000000..ca6f4b4190e --- /dev/null +++ b/tests/baselines/reference/isolatedModulesSourceMap.js @@ -0,0 +1,7 @@ +//// [isolatedModulesSourceMap.ts] + +export var x; + +//// [isolatedModulesSourceMap.js] +export var x; +//# sourceMappingURL=isolatedModulesSourceMap.js.map \ No newline at end of file diff --git a/tests/baselines/reference/isolatedModulesSourceMap.js.map b/tests/baselines/reference/isolatedModulesSourceMap.js.map new file mode 100644 index 00000000000..8e505dcda7a --- /dev/null +++ b/tests/baselines/reference/isolatedModulesSourceMap.js.map @@ -0,0 +1,2 @@ +//// [isolatedModulesSourceMap.js.map] +{"version":3,"file":"isolatedModulesSourceMap.js","sourceRoot":"","sources":["isolatedModulesSourceMap.ts"],"names":[],"mappings":"AACA,WAAW,CAAC,CAAC"} \ No newline at end of file diff --git a/tests/baselines/reference/separateCompilationSourceMap.sourcemap.txt b/tests/baselines/reference/isolatedModulesSourceMap.sourcemap.txt similarity index 61% rename from tests/baselines/reference/separateCompilationSourceMap.sourcemap.txt rename to tests/baselines/reference/isolatedModulesSourceMap.sourcemap.txt index 74e0d73d7e0..5c6b7659bc6 100644 --- a/tests/baselines/reference/separateCompilationSourceMap.sourcemap.txt +++ b/tests/baselines/reference/isolatedModulesSourceMap.sourcemap.txt @@ -1,19 +1,19 @@ =================================================================== -JsFile: separateCompilationSourceMap.js -mapUrl: separateCompilationSourceMap.js.map +JsFile: isolatedModulesSourceMap.js +mapUrl: isolatedModulesSourceMap.js.map sourceRoot: -sources: separateCompilationSourceMap.ts +sources: isolatedModulesSourceMap.ts =================================================================== ------------------------------------------------------------------- -emittedFile:tests/cases/compiler/separateCompilationSourceMap.js -sourceFile:separateCompilationSourceMap.ts +emittedFile:tests/cases/compiler/isolatedModulesSourceMap.js +sourceFile:isolatedModulesSourceMap.ts ------------------------------------------------------------------- >>>export var x; 1 > 2 >^^^^^^^^^^^ 3 > ^ 4 > ^ -5 > ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^-> +5 > ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^-> 1 > > 2 >export var @@ -24,4 +24,4 @@ sourceFile:separateCompilationSourceMap.ts 3 >Emitted(1, 13) Source(2, 13) + SourceIndex(0) 4 >Emitted(1, 14) Source(2, 14) + SourceIndex(0) --- ->>>//# sourceMappingURL=separateCompilationSourceMap.js.map \ No newline at end of file +>>>//# sourceMappingURL=isolatedModulesSourceMap.js.map \ No newline at end of file diff --git a/tests/baselines/reference/isolatedModulesSpecifiedModule.js b/tests/baselines/reference/isolatedModulesSpecifiedModule.js new file mode 100644 index 00000000000..95e4ec88d92 --- /dev/null +++ b/tests/baselines/reference/isolatedModulesSpecifiedModule.js @@ -0,0 +1,4 @@ +//// [isolatedModulesSpecifiedModule.ts] +export var x; + +//// [isolatedModulesSpecifiedModule.js] diff --git a/tests/baselines/reference/isolatedModulesSpecifiedModule.symbols b/tests/baselines/reference/isolatedModulesSpecifiedModule.symbols new file mode 100644 index 00000000000..91ede682d7c --- /dev/null +++ b/tests/baselines/reference/isolatedModulesSpecifiedModule.symbols @@ -0,0 +1,4 @@ +=== tests/cases/compiler/isolatedModulesSpecifiedModule.ts === +export var x; +>x : Symbol(x, Decl(isolatedModulesSpecifiedModule.ts, 0, 10)) + diff --git a/tests/baselines/reference/isolatedModulesSpecifiedModule.types b/tests/baselines/reference/isolatedModulesSpecifiedModule.types new file mode 100644 index 00000000000..8dee90a199f --- /dev/null +++ b/tests/baselines/reference/isolatedModulesSpecifiedModule.types @@ -0,0 +1,4 @@ +=== tests/cases/compiler/isolatedModulesSpecifiedModule.ts === +export var x; +>x : any + diff --git a/tests/baselines/reference/isolatedModulesUnspecifiedModule.errors.txt b/tests/baselines/reference/isolatedModulesUnspecifiedModule.errors.txt new file mode 100644 index 00000000000..7d290bcae44 --- /dev/null +++ b/tests/baselines/reference/isolatedModulesUnspecifiedModule.errors.txt @@ -0,0 +1,6 @@ +error TS5047: Option 'isolatedModules' can only be used when either option'--module' is provided or option 'target' is 'ES6' or higher. + + +!!! error TS5047: Option 'isolatedModules' can only be used when either option'--module' is provided or option 'target' is 'ES6' or higher. +==== tests/cases/compiler/isolatedModulesUnspecifiedModule.ts (0 errors) ==== + export var x; \ No newline at end of file diff --git a/tests/baselines/reference/isolatedModulesUnspecifiedModule.js b/tests/baselines/reference/isolatedModulesUnspecifiedModule.js new file mode 100644 index 00000000000..68b9bfb62db --- /dev/null +++ b/tests/baselines/reference/isolatedModulesUnspecifiedModule.js @@ -0,0 +1,4 @@ +//// [isolatedModulesUnspecifiedModule.ts] +export var x; + +//// [isolatedModulesUnspecifiedModule.js] diff --git a/tests/baselines/reference/separateCompilationWithDeclarationFile.js b/tests/baselines/reference/isolatedModulesWithDeclarationFile.js similarity index 57% rename from tests/baselines/reference/separateCompilationWithDeclarationFile.js rename to tests/baselines/reference/isolatedModulesWithDeclarationFile.js index 71d7ef41929..42d091b6108 100644 --- a/tests/baselines/reference/separateCompilationWithDeclarationFile.js +++ b/tests/baselines/reference/isolatedModulesWithDeclarationFile.js @@ -1,4 +1,4 @@ -//// [tests/cases/compiler/separateCompilationWithDeclarationFile.ts] //// +//// [tests/cases/compiler/isolatedModulesWithDeclarationFile.ts] //// //// [file1.d.ts] diff --git a/tests/baselines/reference/separateCompilationWithDeclarationFile.symbols b/tests/baselines/reference/isolatedModulesWithDeclarationFile.symbols similarity index 100% rename from tests/baselines/reference/separateCompilationWithDeclarationFile.symbols rename to tests/baselines/reference/isolatedModulesWithDeclarationFile.symbols diff --git a/tests/baselines/reference/separateCompilationWithDeclarationFile.types b/tests/baselines/reference/isolatedModulesWithDeclarationFile.types similarity index 100% rename from tests/baselines/reference/separateCompilationWithDeclarationFile.types rename to tests/baselines/reference/isolatedModulesWithDeclarationFile.types diff --git a/tests/baselines/reference/iterableArrayPattern30.symbols b/tests/baselines/reference/iterableArrayPattern30.symbols index 0f50713b43d..715dd79c97a 100644 --- a/tests/baselines/reference/iterableArrayPattern30.symbols +++ b/tests/baselines/reference/iterableArrayPattern30.symbols @@ -4,5 +4,5 @@ const [[k1, v1], [k2, v2]] = new Map([["", true], ["hello", true]]) >v1 : Symbol(v1, Decl(iterableArrayPattern30.ts, 0, 11)) >k2 : Symbol(k2, Decl(iterableArrayPattern30.ts, 0, 18)) >v2 : Symbol(v2, Decl(iterableArrayPattern30.ts, 0, 21)) ->Map : Symbol(Map, Decl(lib.d.ts, 1867, 1), Decl(lib.d.ts, 1889, 11)) +>Map : Symbol(Map, Decl(lib.d.ts, 1864, 1), Decl(lib.d.ts, 1886, 11)) diff --git a/tests/baselines/reference/iterableContextualTyping1.symbols b/tests/baselines/reference/iterableContextualTyping1.symbols index 76d94dc2923..a900c56ecab 100644 --- a/tests/baselines/reference/iterableContextualTyping1.symbols +++ b/tests/baselines/reference/iterableContextualTyping1.symbols @@ -1,7 +1,7 @@ === tests/cases/conformance/expressions/contextualTyping/iterableContextualTyping1.ts === var iter: Iterable<(x: string) => number> = [s => s.length]; >iter : Symbol(iter, Decl(iterableContextualTyping1.ts, 0, 3)) ->Iterable : Symbol(Iterable, Decl(lib.d.ts, 1663, 1)) +>Iterable : Symbol(Iterable, Decl(lib.d.ts, 1668, 1)) >x : Symbol(x, Decl(iterableContextualTyping1.ts, 0, 20)) >s : Symbol(s, Decl(iterableContextualTyping1.ts, 0, 45)) >s.length : Symbol(String.length, Decl(lib.d.ts, 414, 19)) diff --git a/tests/baselines/reference/iteratorSpreadInArray11.symbols b/tests/baselines/reference/iteratorSpreadInArray11.symbols index b128803aa50..548e026744a 100644 --- a/tests/baselines/reference/iteratorSpreadInArray11.symbols +++ b/tests/baselines/reference/iteratorSpreadInArray11.symbols @@ -1,7 +1,7 @@ === tests/cases/conformance/es6/spread/iteratorSpreadInArray11.ts === var iter: Iterable; >iter : Symbol(iter, Decl(iteratorSpreadInArray11.ts, 0, 3)) ->Iterable : Symbol(Iterable, Decl(lib.d.ts, 1663, 1)) +>Iterable : Symbol(Iterable, Decl(lib.d.ts, 1668, 1)) var array = [...iter]; >array : Symbol(array, Decl(iteratorSpreadInArray11.ts, 1, 3)) diff --git a/tests/baselines/reference/lambdaArgCrash.js b/tests/baselines/reference/lambdaArgCrash.js index 0f71ae803d6..5616b5d525f 100644 --- a/tests/baselines/reference/lambdaArgCrash.js +++ b/tests/baselines/reference/lambdaArgCrash.js @@ -38,8 +38,7 @@ class ItemSetEvent extends Event { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var Event = (function () { function Event() { diff --git a/tests/baselines/reference/letAsIdentifier.errors.txt b/tests/baselines/reference/letAsIdentifier.errors.txt new file mode 100644 index 00000000000..b4e4db22853 --- /dev/null +++ b/tests/baselines/reference/letAsIdentifier.errors.txt @@ -0,0 +1,15 @@ +tests/cases/compiler/letAsIdentifier.ts(3,5): error TS2300: Duplicate identifier 'a'. +tests/cases/compiler/letAsIdentifier.ts(6,1): error TS2300: Duplicate identifier 'a'. + + +==== tests/cases/compiler/letAsIdentifier.ts (2 errors) ==== + + var let = 10; + var a = 10; + ~ +!!! error TS2300: Duplicate identifier 'a'. + let = 30; + let + a; + ~ +!!! error TS2300: Duplicate identifier 'a'. \ No newline at end of file diff --git a/tests/baselines/reference/letAsIdentifier.js b/tests/baselines/reference/letAsIdentifier.js index ae45b4b491c..05811ce1088 100644 --- a/tests/baselines/reference/letAsIdentifier.js +++ b/tests/baselines/reference/letAsIdentifier.js @@ -10,10 +10,10 @@ a; var let = 10; var a = 10; let = 30; -let; -a; +var a; //// [letAsIdentifier.d.ts] declare var let: number; declare var a: number; +declare let a: any; diff --git a/tests/baselines/reference/letAsIdentifier.symbols b/tests/baselines/reference/letAsIdentifier.symbols deleted file mode 100644 index be5066f5ac7..00000000000 --- a/tests/baselines/reference/letAsIdentifier.symbols +++ /dev/null @@ -1,17 +0,0 @@ -=== tests/cases/compiler/letAsIdentifier.ts === - -var let = 10; ->let : Symbol(let, Decl(letAsIdentifier.ts, 1, 3)) - -var a = 10; ->a : Symbol(a, Decl(letAsIdentifier.ts, 2, 3)) - -let = 30; ->let : Symbol(let, Decl(letAsIdentifier.ts, 1, 3)) - -let ->let : Symbol(let, Decl(letAsIdentifier.ts, 1, 3)) - -a; ->a : Symbol(a, Decl(letAsIdentifier.ts, 2, 3)) - diff --git a/tests/baselines/reference/letAsIdentifier.types b/tests/baselines/reference/letAsIdentifier.types deleted file mode 100644 index 36c190a92e4..00000000000 --- a/tests/baselines/reference/letAsIdentifier.types +++ /dev/null @@ -1,21 +0,0 @@ -=== tests/cases/compiler/letAsIdentifier.ts === - -var let = 10; ->let : number ->10 : number - -var a = 10; ->a : number ->10 : number - -let = 30; ->let = 30 : number ->let : number ->30 : number - -let ->let : number - -a; ->a : number - diff --git a/tests/baselines/reference/letAsIdentifierInStrictMode.errors.txt b/tests/baselines/reference/letAsIdentifierInStrictMode.errors.txt index b59daca008c..42f71669c66 100644 --- a/tests/baselines/reference/letAsIdentifierInStrictMode.errors.txt +++ b/tests/baselines/reference/letAsIdentifierInStrictMode.errors.txt @@ -1,20 +1,20 @@ +tests/cases/compiler/letAsIdentifierInStrictMode.ts(2,5): error TS1212: Identifier expected. 'let' is a reserved word in strict mode tests/cases/compiler/letAsIdentifierInStrictMode.ts(3,5): error TS2300: Duplicate identifier 'a'. -tests/cases/compiler/letAsIdentifierInStrictMode.ts(4,5): error TS1134: Variable declaration expected. -tests/cases/compiler/letAsIdentifierInStrictMode.ts(4,7): error TS1134: Variable declaration expected. +tests/cases/compiler/letAsIdentifierInStrictMode.ts(4,1): error TS1212: Identifier expected. 'let' is a reserved word in strict mode tests/cases/compiler/letAsIdentifierInStrictMode.ts(6,1): error TS2300: Duplicate identifier 'a'. ==== tests/cases/compiler/letAsIdentifierInStrictMode.ts (4 errors) ==== "use strict"; var let = 10; + ~~~ +!!! error TS1212: Identifier expected. 'let' is a reserved word in strict mode var a = 10; ~ !!! error TS2300: Duplicate identifier 'a'. let = 30; - ~ -!!! error TS1134: Variable declaration expected. - ~~ -!!! error TS1134: Variable declaration expected. + ~~~ +!!! error TS1212: Identifier expected. 'let' is a reserved word in strict mode let a; ~ diff --git a/tests/baselines/reference/letAsIdentifierInStrictMode.js b/tests/baselines/reference/letAsIdentifierInStrictMode.js index eb840e1a641..cce0b13cf64 100644 --- a/tests/baselines/reference/letAsIdentifierInStrictMode.js +++ b/tests/baselines/reference/letAsIdentifierInStrictMode.js @@ -10,6 +10,5 @@ a; "use strict"; var let = 10; var a = 10; -var ; -30; +let = 30; var a; diff --git a/tests/baselines/reference/library_ArraySlice.symbols b/tests/baselines/reference/library_ArraySlice.symbols index 25e6fbd5b5b..02c58859d40 100644 --- a/tests/baselines/reference/library_ArraySlice.symbols +++ b/tests/baselines/reference/library_ArraySlice.symbols @@ -2,22 +2,22 @@ // Array.prototype.slice can have zero, one, or two arguments Array.prototype.slice(); >Array.prototype.slice : Symbol(Array.slice, Decl(lib.d.ts, 1048, 15)) ->Array.prototype : Symbol(ArrayConstructor.prototype, Decl(lib.d.ts, 1167, 31)) +>Array.prototype : Symbol(ArrayConstructor.prototype, Decl(lib.d.ts, 1167, 41)) >Array : Symbol(Array, Decl(lib.d.ts, 1000, 23), Decl(lib.d.ts, 1171, 11)) ->prototype : Symbol(ArrayConstructor.prototype, Decl(lib.d.ts, 1167, 31)) +>prototype : Symbol(ArrayConstructor.prototype, Decl(lib.d.ts, 1167, 41)) >slice : Symbol(Array.slice, Decl(lib.d.ts, 1048, 15)) Array.prototype.slice(0); >Array.prototype.slice : Symbol(Array.slice, Decl(lib.d.ts, 1048, 15)) ->Array.prototype : Symbol(ArrayConstructor.prototype, Decl(lib.d.ts, 1167, 31)) +>Array.prototype : Symbol(ArrayConstructor.prototype, Decl(lib.d.ts, 1167, 41)) >Array : Symbol(Array, Decl(lib.d.ts, 1000, 23), Decl(lib.d.ts, 1171, 11)) ->prototype : Symbol(ArrayConstructor.prototype, Decl(lib.d.ts, 1167, 31)) +>prototype : Symbol(ArrayConstructor.prototype, Decl(lib.d.ts, 1167, 41)) >slice : Symbol(Array.slice, Decl(lib.d.ts, 1048, 15)) Array.prototype.slice(0, 1); >Array.prototype.slice : Symbol(Array.slice, Decl(lib.d.ts, 1048, 15)) ->Array.prototype : Symbol(ArrayConstructor.prototype, Decl(lib.d.ts, 1167, 31)) +>Array.prototype : Symbol(ArrayConstructor.prototype, Decl(lib.d.ts, 1167, 41)) >Array : Symbol(Array, Decl(lib.d.ts, 1000, 23), Decl(lib.d.ts, 1171, 11)) ->prototype : Symbol(ArrayConstructor.prototype, Decl(lib.d.ts, 1167, 31)) +>prototype : Symbol(ArrayConstructor.prototype, Decl(lib.d.ts, 1167, 41)) >slice : Symbol(Array.slice, Decl(lib.d.ts, 1048, 15)) diff --git a/tests/baselines/reference/lift.js b/tests/baselines/reference/lift.js index eaaf94e7024..a832b34641d 100644 --- a/tests/baselines/reference/lift.js +++ b/tests/baselines/reference/lift.js @@ -21,8 +21,7 @@ class C extends B { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var B = (function () { function B(y) { diff --git a/tests/baselines/reference/localTypes1.js b/tests/baselines/reference/localTypes1.js new file mode 100644 index 00000000000..00c65db2c96 --- /dev/null +++ b/tests/baselines/reference/localTypes1.js @@ -0,0 +1,324 @@ +//// [localTypes1.ts] + +function f1() { + enum E { + A, B, C + } + class C { + x: E; + } + interface I { + x: E; + } + type A = I[]; + let a: A = [new C()]; + a[0].x = E.B; + return a; +} + +function f2() { + function g() { + enum E { + A, B, C + } + class C { + x: E; + } + interface I { + x: E; + } + type A = I[]; + let a: A = [new C()]; + a[0].x = E.B; + return a; + } + return g(); +} + +function f3(b: boolean) { + if (true) { + enum E { + A, B, C + } + if (b) { + class C { + x: E; + } + interface I { + x: E; + } + type A = I[]; + let a: A = [new C()]; + a[0].x = E.B; + return a; + } + else { + class A { + x: E; + } + interface J { + x: E; + } + type C = J[]; + let c: C = [new A()]; + c[0].x = E.B; + return c; + } + } +} + +function f5() { + var z1 = function () { + enum E { + A, B, C + } + class C { + x: E; + } + return new C(); + } + var z2 = () => { + enum E { + A, B, C + } + class C { + x: E; + } + return new C(); + } +} + +class A { + constructor() { + enum E { + A, B, C + } + class C { + x: E; + } + } + m() { + enum E { + A, B, C + } + class C { + x: E; + } + return new C(); + } + get p() { + enum E { + A, B, C + } + class C { + x: E; + } + return new C(); + } +} + +function f6() { + class A { + a: string; + } + function g() { + class B extends A { + b: string; + } + function h() { + class C extends B { + c: string; + } + var x = new C(); + x.a = "a"; + x.b = "b"; + x.c = "c"; + return x; + } + return h(); + } + return g(); +} + + +//// [localTypes1.js] +var __extends = (this && this.__extends) || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); +}; +function f1() { + var E; + (function (E) { + E[E["A"] = 0] = "A"; + E[E["B"] = 1] = "B"; + E[E["C"] = 2] = "C"; + })(E || (E = {})); + var C = (function () { + function C() { + } + return C; + })(); + var a = [new C()]; + a[0].x = E.B; + return a; +} +function f2() { + function g() { + var E; + (function (E) { + E[E["A"] = 0] = "A"; + E[E["B"] = 1] = "B"; + E[E["C"] = 2] = "C"; + })(E || (E = {})); + var C = (function () { + function C() { + } + return C; + })(); + var a = [new C()]; + a[0].x = E.B; + return a; + } + return g(); +} +function f3(b) { + if (true) { + var E; + (function (E) { + E[E["A"] = 0] = "A"; + E[E["B"] = 1] = "B"; + E[E["C"] = 2] = "C"; + })(E || (E = {})); + if (b) { + var C = (function () { + function C() { + } + return C; + })(); + var a = [new C()]; + a[0].x = E.B; + return a; + } + else { + var A_1 = (function () { + function A_1() { + } + return A_1; + })(); + var c = [new A_1()]; + c[0].x = E.B; + return c; + } + } +} +function f5() { + var z1 = function () { + var E; + (function (E) { + E[E["A"] = 0] = "A"; + E[E["B"] = 1] = "B"; + E[E["C"] = 2] = "C"; + })(E || (E = {})); + var C = (function () { + function C() { + } + return C; + })(); + return new C(); + }; + var z2 = function () { + var E; + (function (E) { + E[E["A"] = 0] = "A"; + E[E["B"] = 1] = "B"; + E[E["C"] = 2] = "C"; + })(E || (E = {})); + var C = (function () { + function C() { + } + return C; + })(); + return new C(); + }; +} +var A = (function () { + function A() { + var E; + (function (E) { + E[E["A"] = 0] = "A"; + E[E["B"] = 1] = "B"; + E[E["C"] = 2] = "C"; + })(E || (E = {})); + var C = (function () { + function C() { + } + return C; + })(); + } + A.prototype.m = function () { + var E; + (function (E) { + E[E["A"] = 0] = "A"; + E[E["B"] = 1] = "B"; + E[E["C"] = 2] = "C"; + })(E || (E = {})); + var C = (function () { + function C() { + } + return C; + })(); + return new C(); + }; + Object.defineProperty(A.prototype, "p", { + get: function () { + var E; + (function (E) { + E[E["A"] = 0] = "A"; + E[E["B"] = 1] = "B"; + E[E["C"] = 2] = "C"; + })(E || (E = {})); + var C = (function () { + function C() { + } + return C; + })(); + return new C(); + }, + enumerable: true, + configurable: true + }); + return A; +})(); +function f6() { + var A = (function () { + function A() { + } + return A; + })(); + function g() { + var B = (function (_super) { + __extends(B, _super); + function B() { + _super.apply(this, arguments); + } + return B; + })(A); + function h() { + var C = (function (_super) { + __extends(C, _super); + function C() { + _super.apply(this, arguments); + } + return C; + })(B); + var x = new C(); + x.a = "a"; + x.b = "b"; + x.c = "c"; + return x; + } + return h(); + } + return g(); +} diff --git a/tests/baselines/reference/localTypes1.symbols b/tests/baselines/reference/localTypes1.symbols new file mode 100644 index 00000000000..53d4191ae61 --- /dev/null +++ b/tests/baselines/reference/localTypes1.symbols @@ -0,0 +1,357 @@ +=== tests/cases/conformance/types/localTypes/localTypes1.ts === + +function f1() { +>f1 : Symbol(f1, Decl(localTypes1.ts, 0, 0)) + + enum E { +>E : Symbol(E, Decl(localTypes1.ts, 1, 15)) + + A, B, C +>A : Symbol(E.A, Decl(localTypes1.ts, 2, 12)) +>B : Symbol(E.B, Decl(localTypes1.ts, 3, 10)) +>C : Symbol(E.C, Decl(localTypes1.ts, 3, 13)) + } + class C { +>C : Symbol(C, Decl(localTypes1.ts, 4, 5)) + + x: E; +>x : Symbol(x, Decl(localTypes1.ts, 5, 13)) +>E : Symbol(E, Decl(localTypes1.ts, 1, 15)) + } + interface I { +>I : Symbol(I, Decl(localTypes1.ts, 7, 5)) + + x: E; +>x : Symbol(x, Decl(localTypes1.ts, 8, 17)) +>E : Symbol(E, Decl(localTypes1.ts, 1, 15)) + } + type A = I[]; +>A : Symbol(A, Decl(localTypes1.ts, 10, 5)) +>I : Symbol(I, Decl(localTypes1.ts, 7, 5)) + + let a: A = [new C()]; +>a : Symbol(a, Decl(localTypes1.ts, 12, 7)) +>A : Symbol(A, Decl(localTypes1.ts, 10, 5)) +>C : Symbol(C, Decl(localTypes1.ts, 4, 5)) + + a[0].x = E.B; +>a[0].x : Symbol(I.x, Decl(localTypes1.ts, 8, 17)) +>a : Symbol(a, Decl(localTypes1.ts, 12, 7)) +>x : Symbol(I.x, Decl(localTypes1.ts, 8, 17)) +>E.B : Symbol(E.B, Decl(localTypes1.ts, 3, 10)) +>E : Symbol(E, Decl(localTypes1.ts, 1, 15)) +>B : Symbol(E.B, Decl(localTypes1.ts, 3, 10)) + + return a; +>a : Symbol(a, Decl(localTypes1.ts, 12, 7)) +} + +function f2() { +>f2 : Symbol(f2, Decl(localTypes1.ts, 15, 1)) + + function g() { +>g : Symbol(g, Decl(localTypes1.ts, 17, 15)) + + enum E { +>E : Symbol(E, Decl(localTypes1.ts, 18, 18)) + + A, B, C +>A : Symbol(E.A, Decl(localTypes1.ts, 19, 16)) +>B : Symbol(E.B, Decl(localTypes1.ts, 20, 14)) +>C : Symbol(E.C, Decl(localTypes1.ts, 20, 17)) + } + class C { +>C : Symbol(C, Decl(localTypes1.ts, 21, 9)) + + x: E; +>x : Symbol(x, Decl(localTypes1.ts, 22, 17)) +>E : Symbol(E, Decl(localTypes1.ts, 18, 18)) + } + interface I { +>I : Symbol(I, Decl(localTypes1.ts, 24, 9)) + + x: E; +>x : Symbol(x, Decl(localTypes1.ts, 25, 21)) +>E : Symbol(E, Decl(localTypes1.ts, 18, 18)) + } + type A = I[]; +>A : Symbol(A, Decl(localTypes1.ts, 27, 9)) +>I : Symbol(I, Decl(localTypes1.ts, 24, 9)) + + let a: A = [new C()]; +>a : Symbol(a, Decl(localTypes1.ts, 29, 11)) +>A : Symbol(A, Decl(localTypes1.ts, 27, 9)) +>C : Symbol(C, Decl(localTypes1.ts, 21, 9)) + + a[0].x = E.B; +>a[0].x : Symbol(I.x, Decl(localTypes1.ts, 25, 21)) +>a : Symbol(a, Decl(localTypes1.ts, 29, 11)) +>x : Symbol(I.x, Decl(localTypes1.ts, 25, 21)) +>E.B : Symbol(E.B, Decl(localTypes1.ts, 20, 14)) +>E : Symbol(E, Decl(localTypes1.ts, 18, 18)) +>B : Symbol(E.B, Decl(localTypes1.ts, 20, 14)) + + return a; +>a : Symbol(a, Decl(localTypes1.ts, 29, 11)) + } + return g(); +>g : Symbol(g, Decl(localTypes1.ts, 17, 15)) +} + +function f3(b: boolean) { +>f3 : Symbol(f3, Decl(localTypes1.ts, 34, 1)) +>b : Symbol(b, Decl(localTypes1.ts, 36, 12)) + + if (true) { + enum E { +>E : Symbol(E, Decl(localTypes1.ts, 37, 15)) + + A, B, C +>A : Symbol(E.A, Decl(localTypes1.ts, 38, 16)) +>B : Symbol(E.B, Decl(localTypes1.ts, 39, 14)) +>C : Symbol(E.C, Decl(localTypes1.ts, 39, 17)) + } + if (b) { +>b : Symbol(b, Decl(localTypes1.ts, 36, 12)) + + class C { +>C : Symbol(C, Decl(localTypes1.ts, 41, 16)) + + x: E; +>x : Symbol(x, Decl(localTypes1.ts, 42, 21)) +>E : Symbol(E, Decl(localTypes1.ts, 37, 15)) + } + interface I { +>I : Symbol(I, Decl(localTypes1.ts, 44, 13)) + + x: E; +>x : Symbol(x, Decl(localTypes1.ts, 45, 25)) +>E : Symbol(E, Decl(localTypes1.ts, 37, 15)) + } + type A = I[]; +>A : Symbol(A, Decl(localTypes1.ts, 47, 13)) +>I : Symbol(I, Decl(localTypes1.ts, 44, 13)) + + let a: A = [new C()]; +>a : Symbol(a, Decl(localTypes1.ts, 49, 15)) +>A : Symbol(A, Decl(localTypes1.ts, 47, 13)) +>C : Symbol(C, Decl(localTypes1.ts, 41, 16)) + + a[0].x = E.B; +>a[0].x : Symbol(I.x, Decl(localTypes1.ts, 45, 25)) +>a : Symbol(a, Decl(localTypes1.ts, 49, 15)) +>x : Symbol(I.x, Decl(localTypes1.ts, 45, 25)) +>E.B : Symbol(E.B, Decl(localTypes1.ts, 39, 14)) +>E : Symbol(E, Decl(localTypes1.ts, 37, 15)) +>B : Symbol(E.B, Decl(localTypes1.ts, 39, 14)) + + return a; +>a : Symbol(a, Decl(localTypes1.ts, 49, 15)) + } + else { + class A { +>A : Symbol(A, Decl(localTypes1.ts, 53, 14)) + + x: E; +>x : Symbol(x, Decl(localTypes1.ts, 54, 21)) +>E : Symbol(E, Decl(localTypes1.ts, 37, 15)) + } + interface J { +>J : Symbol(J, Decl(localTypes1.ts, 56, 13)) + + x: E; +>x : Symbol(x, Decl(localTypes1.ts, 57, 25)) +>E : Symbol(E, Decl(localTypes1.ts, 37, 15)) + } + type C = J[]; +>C : Symbol(C, Decl(localTypes1.ts, 59, 13)) +>J : Symbol(J, Decl(localTypes1.ts, 56, 13)) + + let c: C = [new A()]; +>c : Symbol(c, Decl(localTypes1.ts, 61, 15)) +>C : Symbol(C, Decl(localTypes1.ts, 59, 13)) +>A : Symbol(A, Decl(localTypes1.ts, 53, 14)) + + c[0].x = E.B; +>c[0].x : Symbol(J.x, Decl(localTypes1.ts, 57, 25)) +>c : Symbol(c, Decl(localTypes1.ts, 61, 15)) +>x : Symbol(J.x, Decl(localTypes1.ts, 57, 25)) +>E.B : Symbol(E.B, Decl(localTypes1.ts, 39, 14)) +>E : Symbol(E, Decl(localTypes1.ts, 37, 15)) +>B : Symbol(E.B, Decl(localTypes1.ts, 39, 14)) + + return c; +>c : Symbol(c, Decl(localTypes1.ts, 61, 15)) + } + } +} + +function f5() { +>f5 : Symbol(f5, Decl(localTypes1.ts, 66, 1)) + + var z1 = function () { +>z1 : Symbol(z1, Decl(localTypes1.ts, 69, 7)) + + enum E { +>E : Symbol(E, Decl(localTypes1.ts, 69, 26)) + + A, B, C +>A : Symbol(E.A, Decl(localTypes1.ts, 70, 16)) +>B : Symbol(E.B, Decl(localTypes1.ts, 71, 14)) +>C : Symbol(E.C, Decl(localTypes1.ts, 71, 17)) + } + class C { +>C : Symbol(C, Decl(localTypes1.ts, 72, 9)) + + x: E; +>x : Symbol(x, Decl(localTypes1.ts, 73, 17)) +>E : Symbol(E, Decl(localTypes1.ts, 69, 26)) + } + return new C(); +>C : Symbol(C, Decl(localTypes1.ts, 72, 9)) + } + var z2 = () => { +>z2 : Symbol(z2, Decl(localTypes1.ts, 78, 7)) + + enum E { +>E : Symbol(E, Decl(localTypes1.ts, 78, 20)) + + A, B, C +>A : Symbol(E.A, Decl(localTypes1.ts, 79, 16)) +>B : Symbol(E.B, Decl(localTypes1.ts, 80, 14)) +>C : Symbol(E.C, Decl(localTypes1.ts, 80, 17)) + } + class C { +>C : Symbol(C, Decl(localTypes1.ts, 81, 9)) + + x: E; +>x : Symbol(x, Decl(localTypes1.ts, 82, 17)) +>E : Symbol(E, Decl(localTypes1.ts, 78, 20)) + } + return new C(); +>C : Symbol(C, Decl(localTypes1.ts, 81, 9)) + } +} + +class A { +>A : Symbol(A, Decl(localTypes1.ts, 87, 1)) + + constructor() { + enum E { +>E : Symbol(E, Decl(localTypes1.ts, 90, 19)) + + A, B, C +>A : Symbol(E.A, Decl(localTypes1.ts, 91, 16)) +>B : Symbol(E.B, Decl(localTypes1.ts, 92, 14)) +>C : Symbol(E.C, Decl(localTypes1.ts, 92, 17)) + } + class C { +>C : Symbol(C, Decl(localTypes1.ts, 93, 9)) + + x: E; +>x : Symbol(x, Decl(localTypes1.ts, 94, 17)) +>E : Symbol(E, Decl(localTypes1.ts, 90, 19)) + } + } + m() { +>m : Symbol(m, Decl(localTypes1.ts, 97, 5)) + + enum E { +>E : Symbol(E, Decl(localTypes1.ts, 98, 9)) + + A, B, C +>A : Symbol(E.A, Decl(localTypes1.ts, 99, 16)) +>B : Symbol(E.B, Decl(localTypes1.ts, 100, 14)) +>C : Symbol(E.C, Decl(localTypes1.ts, 100, 17)) + } + class C { +>C : Symbol(C, Decl(localTypes1.ts, 101, 9)) + + x: E; +>x : Symbol(x, Decl(localTypes1.ts, 102, 17)) +>E : Symbol(E, Decl(localTypes1.ts, 98, 9)) + } + return new C(); +>C : Symbol(C, Decl(localTypes1.ts, 101, 9)) + } + get p() { +>p : Symbol(p, Decl(localTypes1.ts, 106, 5)) + + enum E { +>E : Symbol(E, Decl(localTypes1.ts, 107, 13)) + + A, B, C +>A : Symbol(E.A, Decl(localTypes1.ts, 108, 16)) +>B : Symbol(E.B, Decl(localTypes1.ts, 109, 14)) +>C : Symbol(E.C, Decl(localTypes1.ts, 109, 17)) + } + class C { +>C : Symbol(C, Decl(localTypes1.ts, 110, 9)) + + x: E; +>x : Symbol(x, Decl(localTypes1.ts, 111, 17)) +>E : Symbol(E, Decl(localTypes1.ts, 107, 13)) + } + return new C(); +>C : Symbol(C, Decl(localTypes1.ts, 110, 9)) + } +} + +function f6() { +>f6 : Symbol(f6, Decl(localTypes1.ts, 116, 1)) + + class A { +>A : Symbol(A, Decl(localTypes1.ts, 118, 15)) + + a: string; +>a : Symbol(a, Decl(localTypes1.ts, 119, 13)) + } + function g() { +>g : Symbol(g, Decl(localTypes1.ts, 121, 5)) + + class B extends A { +>B : Symbol(B, Decl(localTypes1.ts, 122, 18)) +>A : Symbol(A, Decl(localTypes1.ts, 118, 15)) + + b: string; +>b : Symbol(b, Decl(localTypes1.ts, 123, 27)) + } + function h() { +>h : Symbol(h, Decl(localTypes1.ts, 125, 9)) + + class C extends B { +>C : Symbol(C, Decl(localTypes1.ts, 126, 22)) +>B : Symbol(B, Decl(localTypes1.ts, 122, 18)) + + c: string; +>c : Symbol(c, Decl(localTypes1.ts, 127, 31)) + } + var x = new C(); +>x : Symbol(x, Decl(localTypes1.ts, 130, 15)) +>C : Symbol(C, Decl(localTypes1.ts, 126, 22)) + + x.a = "a"; +>x.a : Symbol(A.a, Decl(localTypes1.ts, 119, 13)) +>x : Symbol(x, Decl(localTypes1.ts, 130, 15)) +>a : Symbol(A.a, Decl(localTypes1.ts, 119, 13)) + + x.b = "b"; +>x.b : Symbol(B.b, Decl(localTypes1.ts, 123, 27)) +>x : Symbol(x, Decl(localTypes1.ts, 130, 15)) +>b : Symbol(B.b, Decl(localTypes1.ts, 123, 27)) + + x.c = "c"; +>x.c : Symbol(C.c, Decl(localTypes1.ts, 127, 31)) +>x : Symbol(x, Decl(localTypes1.ts, 130, 15)) +>c : Symbol(C.c, Decl(localTypes1.ts, 127, 31)) + + return x; +>x : Symbol(x, Decl(localTypes1.ts, 130, 15)) + } + return h(); +>h : Symbol(h, Decl(localTypes1.ts, 125, 9)) + } + return g(); +>g : Symbol(g, Decl(localTypes1.ts, 121, 5)) +} + diff --git a/tests/baselines/reference/localTypes1.types b/tests/baselines/reference/localTypes1.types new file mode 100644 index 00000000000..1770a36edb7 --- /dev/null +++ b/tests/baselines/reference/localTypes1.types @@ -0,0 +1,395 @@ +=== tests/cases/conformance/types/localTypes/localTypes1.ts === + +function f1() { +>f1 : () => I[] + + enum E { +>E : E + + A, B, C +>A : E +>B : E +>C : E + } + class C { +>C : C + + x: E; +>x : E +>E : E + } + interface I { +>I : I + + x: E; +>x : E +>E : E + } + type A = I[]; +>A : I[] +>I : I + + let a: A = [new C()]; +>a : I[] +>A : I[] +>[new C()] : C[] +>new C() : C +>C : typeof C + + a[0].x = E.B; +>a[0].x = E.B : E +>a[0].x : E +>a[0] : I +>a : I[] +>0 : number +>x : E +>E.B : E +>E : typeof E +>B : E + + return a; +>a : I[] +} + +function f2() { +>f2 : () => I[] + + function g() { +>g : () => I[] + + enum E { +>E : E + + A, B, C +>A : E +>B : E +>C : E + } + class C { +>C : C + + x: E; +>x : E +>E : E + } + interface I { +>I : I + + x: E; +>x : E +>E : E + } + type A = I[]; +>A : I[] +>I : I + + let a: A = [new C()]; +>a : I[] +>A : I[] +>[new C()] : C[] +>new C() : C +>C : typeof C + + a[0].x = E.B; +>a[0].x = E.B : E +>a[0].x : E +>a[0] : I +>a : I[] +>0 : number +>x : E +>E.B : E +>E : typeof E +>B : E + + return a; +>a : I[] + } + return g(); +>g() : I[] +>g : () => I[] +} + +function f3(b: boolean) { +>f3 : (b: boolean) => I[] +>b : boolean + + if (true) { +>true : boolean + + enum E { +>E : E + + A, B, C +>A : E +>B : E +>C : E + } + if (b) { +>b : boolean + + class C { +>C : C + + x: E; +>x : E +>E : E + } + interface I { +>I : I + + x: E; +>x : E +>E : E + } + type A = I[]; +>A : I[] +>I : I + + let a: A = [new C()]; +>a : I[] +>A : I[] +>[new C()] : C[] +>new C() : C +>C : typeof C + + a[0].x = E.B; +>a[0].x = E.B : E +>a[0].x : E +>a[0] : I +>a : I[] +>0 : number +>x : E +>E.B : E +>E : typeof E +>B : E + + return a; +>a : I[] + } + else { + class A { +>A : A + + x: E; +>x : E +>E : E + } + interface J { +>J : J + + x: E; +>x : E +>E : E + } + type C = J[]; +>C : J[] +>J : J + + let c: C = [new A()]; +>c : J[] +>C : J[] +>[new A()] : A[] +>new A() : A +>A : typeof A + + c[0].x = E.B; +>c[0].x = E.B : E +>c[0].x : E +>c[0] : J +>c : J[] +>0 : number +>x : E +>E.B : E +>E : typeof E +>B : E + + return c; +>c : J[] + } + } +} + +function f5() { +>f5 : () => void + + var z1 = function () { +>z1 : () => C +>function () { enum E { A, B, C } class C { x: E; } return new C(); } : () => C + + enum E { +>E : E + + A, B, C +>A : E +>B : E +>C : E + } + class C { +>C : C + + x: E; +>x : E +>E : E + } + return new C(); +>new C() : C +>C : typeof C + } + var z2 = () => { +>z2 : () => C +>() => { enum E { A, B, C } class C { x: E; } return new C(); } : () => C + + enum E { +>E : E + + A, B, C +>A : E +>B : E +>C : E + } + class C { +>C : C + + x: E; +>x : E +>E : E + } + return new C(); +>new C() : C +>C : typeof C + } +} + +class A { +>A : A + + constructor() { + enum E { +>E : E + + A, B, C +>A : E +>B : E +>C : E + } + class C { +>C : C + + x: E; +>x : E +>E : E + } + } + m() { +>m : () => C + + enum E { +>E : E + + A, B, C +>A : E +>B : E +>C : E + } + class C { +>C : C + + x: E; +>x : E +>E : E + } + return new C(); +>new C() : C +>C : typeof C + } + get p() { +>p : C + + enum E { +>E : E + + A, B, C +>A : E +>B : E +>C : E + } + class C { +>C : C + + x: E; +>x : E +>E : E + } + return new C(); +>new C() : C +>C : typeof C + } +} + +function f6() { +>f6 : () => C + + class A { +>A : A + + a: string; +>a : string + } + function g() { +>g : () => C + + class B extends A { +>B : B +>A : A + + b: string; +>b : string + } + function h() { +>h : () => C + + class C extends B { +>C : C +>B : B + + c: string; +>c : string + } + var x = new C(); +>x : C +>new C() : C +>C : typeof C + + x.a = "a"; +>x.a = "a" : string +>x.a : string +>x : C +>a : string +>"a" : string + + x.b = "b"; +>x.b = "b" : string +>x.b : string +>x : C +>b : string +>"b" : string + + x.c = "c"; +>x.c = "c" : string +>x.c : string +>x : C +>c : string +>"c" : string + + return x; +>x : C + } + return h(); +>h() : C +>h : () => C + } + return g(); +>g() : C +>g : () => C +} + diff --git a/tests/baselines/reference/localTypes2.js b/tests/baselines/reference/localTypes2.js new file mode 100644 index 00000000000..a95844f0794 --- /dev/null +++ b/tests/baselines/reference/localTypes2.js @@ -0,0 +1,92 @@ +//// [localTypes2.ts] +function f1() { + function f() { + class C { + constructor(public x: number, public y: number) { } + } + return C; + } + let C = f(); + let v = new C(10, 20); + let x = v.x; + let y = v.y; +} + +function f2() { + function f(x: number) { + class C { + public x = x; + constructor(public y: number) { } + } + return C; + } + let C = f(10); + let v = new C(20); + let x = v.x; + let y = v.y; +} + +function f3() { + function f(x: number, y: number) { + class C { + public x = x; + public y = y; + } + return C; + } + let C = f(10, 20); + let v = new C(); + let x = v.x; + let y = v.y; +} + + +//// [localTypes2.js] +function f1() { + function f() { + var C = (function () { + function C(x, y) { + this.x = x; + this.y = y; + } + return C; + })(); + return C; + } + var C = f(); + var v = new C(10, 20); + var x = v.x; + var y = v.y; +} +function f2() { + function f(x) { + var C = (function () { + function C(y) { + this.y = y; + this.x = x; + } + return C; + })(); + return C; + } + var C = f(10); + var v = new C(20); + var x = v.x; + var y = v.y; +} +function f3() { + function f(x, y) { + var C = (function () { + function C() { + this.x = x; + this.y = y; + } + return C; + })(); + return C; + } + var C = f(10, 20); + var v = new C(); + var x = v.x; + var y = v.y; +} diff --git a/tests/baselines/reference/localTypes2.symbols b/tests/baselines/reference/localTypes2.symbols new file mode 100644 index 00000000000..3054c6f552d --- /dev/null +++ b/tests/baselines/reference/localTypes2.symbols @@ -0,0 +1,122 @@ +=== tests/cases/conformance/types/localTypes/localTypes2.ts === +function f1() { +>f1 : Symbol(f1, Decl(localTypes2.ts, 0, 0)) + + function f() { +>f : Symbol(f, Decl(localTypes2.ts, 0, 15)) + + class C { +>C : Symbol(C, Decl(localTypes2.ts, 1, 18)) + + constructor(public x: number, public y: number) { } +>x : Symbol(x, Decl(localTypes2.ts, 3, 24)) +>y : Symbol(y, Decl(localTypes2.ts, 3, 41)) + } + return C; +>C : Symbol(C, Decl(localTypes2.ts, 1, 18)) + } + let C = f(); +>C : Symbol(C, Decl(localTypes2.ts, 7, 7)) +>f : Symbol(f, Decl(localTypes2.ts, 0, 15)) + + let v = new C(10, 20); +>v : Symbol(v, Decl(localTypes2.ts, 8, 7)) +>C : Symbol(C, Decl(localTypes2.ts, 7, 7)) + + let x = v.x; +>x : Symbol(x, Decl(localTypes2.ts, 9, 7)) +>v.x : Symbol(C.x, Decl(localTypes2.ts, 3, 24)) +>v : Symbol(v, Decl(localTypes2.ts, 8, 7)) +>x : Symbol(C.x, Decl(localTypes2.ts, 3, 24)) + + let y = v.y; +>y : Symbol(y, Decl(localTypes2.ts, 10, 7)) +>v.y : Symbol(C.y, Decl(localTypes2.ts, 3, 41)) +>v : Symbol(v, Decl(localTypes2.ts, 8, 7)) +>y : Symbol(C.y, Decl(localTypes2.ts, 3, 41)) +} + +function f2() { +>f2 : Symbol(f2, Decl(localTypes2.ts, 11, 1)) + + function f(x: number) { +>f : Symbol(f, Decl(localTypes2.ts, 13, 15)) +>x : Symbol(x, Decl(localTypes2.ts, 14, 15)) + + class C { +>C : Symbol(C, Decl(localTypes2.ts, 14, 27)) + + public x = x; +>x : Symbol(x, Decl(localTypes2.ts, 15, 17)) +>x : Symbol(x, Decl(localTypes2.ts, 14, 15)) + + constructor(public y: number) { } +>y : Symbol(y, Decl(localTypes2.ts, 17, 24)) + } + return C; +>C : Symbol(C, Decl(localTypes2.ts, 14, 27)) + } + let C = f(10); +>C : Symbol(C, Decl(localTypes2.ts, 21, 7)) +>f : Symbol(f, Decl(localTypes2.ts, 13, 15)) + + let v = new C(20); +>v : Symbol(v, Decl(localTypes2.ts, 22, 7)) +>C : Symbol(C, Decl(localTypes2.ts, 21, 7)) + + let x = v.x; +>x : Symbol(x, Decl(localTypes2.ts, 23, 7)) +>v.x : Symbol(C.x, Decl(localTypes2.ts, 15, 17)) +>v : Symbol(v, Decl(localTypes2.ts, 22, 7)) +>x : Symbol(C.x, Decl(localTypes2.ts, 15, 17)) + + let y = v.y; +>y : Symbol(y, Decl(localTypes2.ts, 24, 7)) +>v.y : Symbol(C.y, Decl(localTypes2.ts, 17, 24)) +>v : Symbol(v, Decl(localTypes2.ts, 22, 7)) +>y : Symbol(C.y, Decl(localTypes2.ts, 17, 24)) +} + +function f3() { +>f3 : Symbol(f3, Decl(localTypes2.ts, 25, 1)) + + function f(x: number, y: number) { +>f : Symbol(f, Decl(localTypes2.ts, 27, 15)) +>x : Symbol(x, Decl(localTypes2.ts, 28, 15)) +>y : Symbol(y, Decl(localTypes2.ts, 28, 25)) + + class C { +>C : Symbol(C, Decl(localTypes2.ts, 28, 38)) + + public x = x; +>x : Symbol(x, Decl(localTypes2.ts, 29, 17)) +>x : Symbol(x, Decl(localTypes2.ts, 28, 15)) + + public y = y; +>y : Symbol(y, Decl(localTypes2.ts, 30, 25)) +>y : Symbol(y, Decl(localTypes2.ts, 28, 25)) + } + return C; +>C : Symbol(C, Decl(localTypes2.ts, 28, 38)) + } + let C = f(10, 20); +>C : Symbol(C, Decl(localTypes2.ts, 35, 7)) +>f : Symbol(f, Decl(localTypes2.ts, 27, 15)) + + let v = new C(); +>v : Symbol(v, Decl(localTypes2.ts, 36, 7)) +>C : Symbol(C, Decl(localTypes2.ts, 35, 7)) + + let x = v.x; +>x : Symbol(x, Decl(localTypes2.ts, 37, 7)) +>v.x : Symbol(C.x, Decl(localTypes2.ts, 29, 17)) +>v : Symbol(v, Decl(localTypes2.ts, 36, 7)) +>x : Symbol(C.x, Decl(localTypes2.ts, 29, 17)) + + let y = v.y; +>y : Symbol(y, Decl(localTypes2.ts, 38, 7)) +>v.y : Symbol(C.y, Decl(localTypes2.ts, 30, 25)) +>v : Symbol(v, Decl(localTypes2.ts, 36, 7)) +>y : Symbol(C.y, Decl(localTypes2.ts, 30, 25)) +} + diff --git a/tests/baselines/reference/localTypes2.types b/tests/baselines/reference/localTypes2.types new file mode 100644 index 00000000000..a6b85b7bb14 --- /dev/null +++ b/tests/baselines/reference/localTypes2.types @@ -0,0 +1,134 @@ +=== tests/cases/conformance/types/localTypes/localTypes2.ts === +function f1() { +>f1 : () => void + + function f() { +>f : () => typeof C + + class C { +>C : C + + constructor(public x: number, public y: number) { } +>x : number +>y : number + } + return C; +>C : typeof C + } + let C = f(); +>C : typeof C +>f() : typeof C +>f : () => typeof C + + let v = new C(10, 20); +>v : C +>new C(10, 20) : C +>C : typeof C +>10 : number +>20 : number + + let x = v.x; +>x : number +>v.x : number +>v : C +>x : number + + let y = v.y; +>y : number +>v.y : number +>v : C +>y : number +} + +function f2() { +>f2 : () => void + + function f(x: number) { +>f : (x: number) => typeof C +>x : number + + class C { +>C : C + + public x = x; +>x : number +>x : number + + constructor(public y: number) { } +>y : number + } + return C; +>C : typeof C + } + let C = f(10); +>C : typeof C +>f(10) : typeof C +>f : (x: number) => typeof C +>10 : number + + let v = new C(20); +>v : C +>new C(20) : C +>C : typeof C +>20 : number + + let x = v.x; +>x : number +>v.x : number +>v : C +>x : number + + let y = v.y; +>y : number +>v.y : number +>v : C +>y : number +} + +function f3() { +>f3 : () => void + + function f(x: number, y: number) { +>f : (x: number, y: number) => typeof C +>x : number +>y : number + + class C { +>C : C + + public x = x; +>x : number +>x : number + + public y = y; +>y : number +>y : number + } + return C; +>C : typeof C + } + let C = f(10, 20); +>C : typeof C +>f(10, 20) : typeof C +>f : (x: number, y: number) => typeof C +>10 : number +>20 : number + + let v = new C(); +>v : C +>new C() : C +>C : typeof C + + let x = v.x; +>x : number +>v.x : number +>v : C +>x : number + + let y = v.y; +>y : number +>v.y : number +>v : C +>y : number +} + diff --git a/tests/baselines/reference/localTypes3.js b/tests/baselines/reference/localTypes3.js new file mode 100644 index 00000000000..2d40bc922b9 --- /dev/null +++ b/tests/baselines/reference/localTypes3.js @@ -0,0 +1,92 @@ +//// [localTypes3.ts] +function f1() { + function f() { + class C { + constructor(public x: X, public y: Y) { } + } + return C; + } + let C = f(); + let v = new C(10, "hello"); + let x = v.x; + let y = v.y; +} + +function f2() { + function f(x: X) { + class C { + public x = x; + constructor(public y: Y) { } + } + return C; + } + let C = f(10); + let v = new C("hello"); + let x = v.x; + let y = v.y; +} + +function f3() { + function f(x: X, y: Y) { + class C { + public x = x; + public y = y; + } + return C; + } + let C = f(10, "hello"); + let v = new C(); + let x = v.x; + let y = v.y; +} + + +//// [localTypes3.js] +function f1() { + function f() { + var C = (function () { + function C(x, y) { + this.x = x; + this.y = y; + } + return C; + })(); + return C; + } + var C = f(); + var v = new C(10, "hello"); + var x = v.x; + var y = v.y; +} +function f2() { + function f(x) { + var C = (function () { + function C(y) { + this.y = y; + this.x = x; + } + return C; + })(); + return C; + } + var C = f(10); + var v = new C("hello"); + var x = v.x; + var y = v.y; +} +function f3() { + function f(x, y) { + var C = (function () { + function C() { + this.x = x; + this.y = y; + } + return C; + })(); + return C; + } + var C = f(10, "hello"); + var v = new C(); + var x = v.x; + var y = v.y; +} diff --git a/tests/baselines/reference/localTypes3.symbols b/tests/baselines/reference/localTypes3.symbols new file mode 100644 index 00000000000..fe7082e4577 --- /dev/null +++ b/tests/baselines/reference/localTypes3.symbols @@ -0,0 +1,134 @@ +=== tests/cases/conformance/types/localTypes/localTypes3.ts === +function f1() { +>f1 : Symbol(f1, Decl(localTypes3.ts, 0, 0)) + + function f() { +>f : Symbol(f, Decl(localTypes3.ts, 0, 15)) + + class C { +>C : Symbol(C, Decl(localTypes3.ts, 1, 18)) +>X : Symbol(X, Decl(localTypes3.ts, 2, 16)) +>Y : Symbol(Y, Decl(localTypes3.ts, 2, 18)) + + constructor(public x: X, public y: Y) { } +>x : Symbol(x, Decl(localTypes3.ts, 3, 24)) +>X : Symbol(X, Decl(localTypes3.ts, 2, 16)) +>y : Symbol(y, Decl(localTypes3.ts, 3, 36)) +>Y : Symbol(Y, Decl(localTypes3.ts, 2, 18)) + } + return C; +>C : Symbol(C, Decl(localTypes3.ts, 1, 18)) + } + let C = f(); +>C : Symbol(C, Decl(localTypes3.ts, 7, 7)) +>f : Symbol(f, Decl(localTypes3.ts, 0, 15)) + + let v = new C(10, "hello"); +>v : Symbol(v, Decl(localTypes3.ts, 8, 7)) +>C : Symbol(C, Decl(localTypes3.ts, 7, 7)) + + let x = v.x; +>x : Symbol(x, Decl(localTypes3.ts, 9, 7)) +>v.x : Symbol(C.x, Decl(localTypes3.ts, 3, 24)) +>v : Symbol(v, Decl(localTypes3.ts, 8, 7)) +>x : Symbol(C.x, Decl(localTypes3.ts, 3, 24)) + + let y = v.y; +>y : Symbol(y, Decl(localTypes3.ts, 10, 7)) +>v.y : Symbol(C.y, Decl(localTypes3.ts, 3, 36)) +>v : Symbol(v, Decl(localTypes3.ts, 8, 7)) +>y : Symbol(C.y, Decl(localTypes3.ts, 3, 36)) +} + +function f2() { +>f2 : Symbol(f2, Decl(localTypes3.ts, 11, 1)) + + function f(x: X) { +>f : Symbol(f, Decl(localTypes3.ts, 13, 15)) +>X : Symbol(X, Decl(localTypes3.ts, 14, 15)) +>x : Symbol(x, Decl(localTypes3.ts, 14, 18)) +>X : Symbol(X, Decl(localTypes3.ts, 14, 15)) + + class C { +>C : Symbol(C, Decl(localTypes3.ts, 14, 25)) +>Y : Symbol(Y, Decl(localTypes3.ts, 15, 16)) + + public x = x; +>x : Symbol(x, Decl(localTypes3.ts, 15, 20)) +>x : Symbol(x, Decl(localTypes3.ts, 14, 18)) + + constructor(public y: Y) { } +>y : Symbol(y, Decl(localTypes3.ts, 17, 24)) +>Y : Symbol(Y, Decl(localTypes3.ts, 15, 16)) + } + return C; +>C : Symbol(C, Decl(localTypes3.ts, 14, 25)) + } + let C = f(10); +>C : Symbol(C, Decl(localTypes3.ts, 21, 7)) +>f : Symbol(f, Decl(localTypes3.ts, 13, 15)) + + let v = new C("hello"); +>v : Symbol(v, Decl(localTypes3.ts, 22, 7)) +>C : Symbol(C, Decl(localTypes3.ts, 21, 7)) + + let x = v.x; +>x : Symbol(x, Decl(localTypes3.ts, 23, 7)) +>v.x : Symbol(C.x, Decl(localTypes3.ts, 15, 20)) +>v : Symbol(v, Decl(localTypes3.ts, 22, 7)) +>x : Symbol(C.x, Decl(localTypes3.ts, 15, 20)) + + let y = v.y; +>y : Symbol(y, Decl(localTypes3.ts, 24, 7)) +>v.y : Symbol(C.y, Decl(localTypes3.ts, 17, 24)) +>v : Symbol(v, Decl(localTypes3.ts, 22, 7)) +>y : Symbol(C.y, Decl(localTypes3.ts, 17, 24)) +} + +function f3() { +>f3 : Symbol(f3, Decl(localTypes3.ts, 25, 1)) + + function f(x: X, y: Y) { +>f : Symbol(f, Decl(localTypes3.ts, 27, 15)) +>X : Symbol(X, Decl(localTypes3.ts, 28, 15)) +>Y : Symbol(Y, Decl(localTypes3.ts, 28, 17)) +>x : Symbol(x, Decl(localTypes3.ts, 28, 21)) +>X : Symbol(X, Decl(localTypes3.ts, 28, 15)) +>y : Symbol(y, Decl(localTypes3.ts, 28, 26)) +>Y : Symbol(Y, Decl(localTypes3.ts, 28, 17)) + + class C { +>C : Symbol(C, Decl(localTypes3.ts, 28, 34)) + + public x = x; +>x : Symbol(x, Decl(localTypes3.ts, 29, 17)) +>x : Symbol(x, Decl(localTypes3.ts, 28, 21)) + + public y = y; +>y : Symbol(y, Decl(localTypes3.ts, 30, 25)) +>y : Symbol(y, Decl(localTypes3.ts, 28, 26)) + } + return C; +>C : Symbol(C, Decl(localTypes3.ts, 28, 34)) + } + let C = f(10, "hello"); +>C : Symbol(C, Decl(localTypes3.ts, 35, 7)) +>f : Symbol(f, Decl(localTypes3.ts, 27, 15)) + + let v = new C(); +>v : Symbol(v, Decl(localTypes3.ts, 36, 7)) +>C : Symbol(C, Decl(localTypes3.ts, 35, 7)) + + let x = v.x; +>x : Symbol(x, Decl(localTypes3.ts, 37, 7)) +>v.x : Symbol(C.x, Decl(localTypes3.ts, 29, 17)) +>v : Symbol(v, Decl(localTypes3.ts, 36, 7)) +>x : Symbol(C.x, Decl(localTypes3.ts, 29, 17)) + + let y = v.y; +>y : Symbol(y, Decl(localTypes3.ts, 38, 7)) +>v.y : Symbol(C.y, Decl(localTypes3.ts, 30, 25)) +>v : Symbol(v, Decl(localTypes3.ts, 36, 7)) +>y : Symbol(C.y, Decl(localTypes3.ts, 30, 25)) +} + diff --git a/tests/baselines/reference/localTypes3.types b/tests/baselines/reference/localTypes3.types new file mode 100644 index 00000000000..551096468c5 --- /dev/null +++ b/tests/baselines/reference/localTypes3.types @@ -0,0 +1,146 @@ +=== tests/cases/conformance/types/localTypes/localTypes3.ts === +function f1() { +>f1 : () => void + + function f() { +>f : () => typeof C + + class C { +>C : C +>X : X +>Y : Y + + constructor(public x: X, public y: Y) { } +>x : X +>X : X +>y : Y +>Y : Y + } + return C; +>C : typeof C + } + let C = f(); +>C : typeof C +>f() : typeof C +>f : () => typeof C + + let v = new C(10, "hello"); +>v : C +>new C(10, "hello") : C +>C : typeof C +>10 : number +>"hello" : string + + let x = v.x; +>x : number +>v.x : number +>v : C +>x : number + + let y = v.y; +>y : string +>v.y : string +>v : C +>y : string +} + +function f2() { +>f2 : () => void + + function f(x: X) { +>f : (x: X) => typeof C +>X : X +>x : X +>X : X + + class C { +>C : C +>Y : Y + + public x = x; +>x : X +>x : X + + constructor(public y: Y) { } +>y : Y +>Y : Y + } + return C; +>C : typeof C + } + let C = f(10); +>C : typeof C +>f(10) : typeof C +>f : (x: X) => typeof C +>10 : number + + let v = new C("hello"); +>v : f.C +>new C("hello") : f.C +>C : typeof C +>"hello" : string + + let x = v.x; +>x : number +>v.x : number +>v : f.C +>x : number + + let y = v.y; +>y : string +>v.y : string +>v : f.C +>y : string +} + +function f3() { +>f3 : () => void + + function f(x: X, y: Y) { +>f : (x: X, y: Y) => typeof C +>X : X +>Y : Y +>x : X +>X : X +>y : Y +>Y : Y + + class C { +>C : C + + public x = x; +>x : X +>x : X + + public y = y; +>y : Y +>y : Y + } + return C; +>C : typeof C + } + let C = f(10, "hello"); +>C : typeof C +>f(10, "hello") : typeof C +>f : (x: X, y: Y) => typeof C +>10 : number +>"hello" : string + + let v = new C(); +>v : f.C +>new C() : f.C +>C : typeof C + + let x = v.x; +>x : number +>v.x : number +>v : f.C +>x : number + + let y = v.y; +>y : string +>v.y : string +>v : f.C +>y : string +} + diff --git a/tests/baselines/reference/localTypes4.errors.txt b/tests/baselines/reference/localTypes4.errors.txt new file mode 100644 index 00000000000..cad9d30c933 --- /dev/null +++ b/tests/baselines/reference/localTypes4.errors.txt @@ -0,0 +1,53 @@ +tests/cases/conformance/types/localTypes/localTypes4.ts(10,19): error TS2304: Cannot find name 'T'. +tests/cases/conformance/types/localTypes/localTypes4.ts(10,23): error TS2304: Cannot find name 'T'. +tests/cases/conformance/types/localTypes/localTypes4.ts(18,16): error TS2300: Duplicate identifier 'T'. +tests/cases/conformance/types/localTypes/localTypes4.ts(19,19): error TS2300: Duplicate identifier 'T'. + + +==== tests/cases/conformance/types/localTypes/localTypes4.ts (4 errors) ==== + function f1() { + // Type parameters are in scope in parameters and return types + function f(x: T): T { + return undefined; + } + } + + function f2() { + // Local types are not in scope in parameters and return types + function f(x: T): T { + ~ +!!! error TS2304: Cannot find name 'T'. + ~ +!!! error TS2304: Cannot find name 'T'. + interface T { } + return undefined; + } + } + + function f3() { + // Type parameters and top-level local types are in same declaration space + function f() { + ~ +!!! error TS2300: Duplicate identifier 'T'. + interface T { } + ~ +!!! error TS2300: Duplicate identifier 'T'. + return undefined; + } + } + + function f4() { + // Local types are block scoped + interface T { x: number } + let v: T; + v.x = 10; + if (true) { + interface T { x: string } + let v: T; + v.x = "hello"; + } + else { + v.x = 20; + } + } + \ No newline at end of file diff --git a/tests/baselines/reference/localTypes4.js b/tests/baselines/reference/localTypes4.js new file mode 100644 index 00000000000..8f51761a65a --- /dev/null +++ b/tests/baselines/reference/localTypes4.js @@ -0,0 +1,70 @@ +//// [localTypes4.ts] +function f1() { + // Type parameters are in scope in parameters and return types + function f(x: T): T { + return undefined; + } +} + +function f2() { + // Local types are not in scope in parameters and return types + function f(x: T): T { + interface T { } + return undefined; + } +} + +function f3() { + // Type parameters and top-level local types are in same declaration space + function f() { + interface T { } + return undefined; + } +} + +function f4() { + // Local types are block scoped + interface T { x: number } + let v: T; + v.x = 10; + if (true) { + interface T { x: string } + let v: T; + v.x = "hello"; + } + else { + v.x = 20; + } +} + + +//// [localTypes4.js] +function f1() { + // Type parameters are in scope in parameters and return types + function f(x) { + return undefined; + } +} +function f2() { + // Local types are not in scope in parameters and return types + function f(x) { + return undefined; + } +} +function f3() { + // Type parameters and top-level local types are in same declaration space + function f() { + return undefined; + } +} +function f4() { + var v; + v.x = 10; + if (true) { + var v_1; + v_1.x = "hello"; + } + else { + v.x = 20; + } +} diff --git a/tests/baselines/reference/localTypes5.js b/tests/baselines/reference/localTypes5.js new file mode 100644 index 00000000000..872629276d2 --- /dev/null +++ b/tests/baselines/reference/localTypes5.js @@ -0,0 +1,38 @@ +//// [localTypes5.ts] +function foo() { + class X { + m() { + return (function () { + class Y { + } + return new Y(); + })(); + } + } + var x = new X(); + return x.m(); +} +var x = foo(); + + +//// [localTypes5.js] +function foo() { + var X = (function () { + function X() { + } + X.prototype.m = function () { + return (function () { + var Y = (function () { + function Y() { + } + return Y; + })(); + return new Y(); + })(); + }; + return X; + })(); + var x = new X(); + return x.m(); +} +var x = foo(); diff --git a/tests/baselines/reference/localTypes5.symbols b/tests/baselines/reference/localTypes5.symbols new file mode 100644 index 00000000000..4ffe53b3e53 --- /dev/null +++ b/tests/baselines/reference/localTypes5.symbols @@ -0,0 +1,40 @@ +=== tests/cases/conformance/types/localTypes/localTypes5.ts === +function foo() { +>foo : Symbol(foo, Decl(localTypes5.ts, 0, 0)) +>A : Symbol(A, Decl(localTypes5.ts, 0, 13)) + + class X { +>X : Symbol(X, Decl(localTypes5.ts, 0, 19)) + + m() { +>m : Symbol(m, Decl(localTypes5.ts, 1, 13)) +>B : Symbol(B, Decl(localTypes5.ts, 2, 10)) +>C : Symbol(C, Decl(localTypes5.ts, 2, 12)) + + return (function () { +>D : Symbol(D, Decl(localTypes5.ts, 3, 30)) + + class Y { +>Y : Symbol(Y, Decl(localTypes5.ts, 3, 36)) +>E : Symbol(E, Decl(localTypes5.ts, 4, 24)) + } + return new Y(); +>Y : Symbol(Y, Decl(localTypes5.ts, 3, 36)) + + })(); +>Date : Symbol(Date, Decl(lib.d.ts, 633, 23), Decl(lib.d.ts, 815, 11)) + } + } + var x = new X(); +>x : Symbol(x, Decl(localTypes5.ts, 10, 7)) +>X : Symbol(X, Decl(localTypes5.ts, 0, 19)) + + return x.m(); +>x.m : Symbol(X.m, Decl(localTypes5.ts, 1, 13)) +>x : Symbol(x, Decl(localTypes5.ts, 10, 7)) +>m : Symbol(X.m, Decl(localTypes5.ts, 1, 13)) +} +var x = foo(); +>x : Symbol(x, Decl(localTypes5.ts, 13, 3)) +>foo : Symbol(foo, Decl(localTypes5.ts, 0, 0)) + diff --git a/tests/baselines/reference/localTypes5.types b/tests/baselines/reference/localTypes5.types new file mode 100644 index 00000000000..b12e362f754 --- /dev/null +++ b/tests/baselines/reference/localTypes5.types @@ -0,0 +1,47 @@ +=== tests/cases/conformance/types/localTypes/localTypes5.ts === +function foo() { +>foo : () => X.m..Y +>A : A + + class X { +>X : X + + m() { +>m : () => .Y +>B : B +>C : C + + return (function () { +>(function () { class Y { } return new Y(); })() : .Y +>(function () { class Y { } return new Y(); }) : () => Y +>function () { class Y { } return new Y(); } : () => Y +>D : D + + class Y { +>Y : Y +>E : E + } + return new Y(); +>new Y() : Y +>Y : typeof Y + + })(); +>Date : Date + } + } + var x = new X(); +>x : X +>new X() : X +>X : typeof X + + return x.m(); +>x.m() : X.m..Y +>x.m : () => .Y +>x : X +>m : () => .Y +} +var x = foo(); +>x : foo.X.m..Y +>foo() : foo.X.m..Y +>foo : () => X.m..Y + diff --git a/tests/baselines/reference/logicalOrOperatorWithEveryType.types b/tests/baselines/reference/logicalOrOperatorWithEveryType.types index c98966acb98..ecf6b23e729 100644 --- a/tests/baselines/reference/logicalOrOperatorWithEveryType.types +++ b/tests/baselines/reference/logicalOrOperatorWithEveryType.types @@ -379,8 +379,8 @@ var rg7 = a7 || a6; // object || enum is object | enum >a6 : E var rg8 = a8 || a6; // array || enum is array | enum ->rg8 : string[] | E ->a8 || a6 : string[] | E +>rg8 : E | string[] +>a8 || a6 : E | string[] >a8 : string[] >a6 : E @@ -439,8 +439,8 @@ var rh7 = a7 || a7; // object || object is object >a7 : { a: string; } var rh8 = a8 || a7; // array || object is array | object ->rh8 : string[] | { a: string; } ->a8 || a7 : string[] | { a: string; } +>rh8 : { a: string; } | string[] +>a8 || a7 : { a: string; } | string[] >a8 : string[] >a7 : { a: string; } @@ -487,14 +487,14 @@ var ri5 = a5 || a8; // void || array is void | array >a8 : string[] var ri6 = a6 || a8; // enum || array is enum | array ->ri6 : string[] | E ->a6 || a8 : string[] | E +>ri6 : E | string[] +>a6 || a8 : E | string[] >a6 : E >a8 : string[] var ri7 = a7 || a8; // object || array is object | array ->ri7 : string[] | { a: string; } ->a7 || a8 : string[] | { a: string; } +>ri7 : { a: string; } | string[] +>a7 || a8 : { a: string; } | string[] >a7 : { a: string; } >a8 : string[] diff --git a/tests/baselines/reference/m7Bugs.js b/tests/baselines/reference/m7Bugs.js index 72829316fb8..86b5aa96c77 100644 --- a/tests/baselines/reference/m7Bugs.js +++ b/tests/baselines/reference/m7Bugs.js @@ -30,8 +30,7 @@ var y3: C1 = {}; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var s = ({}); var x = {}; diff --git a/tests/baselines/reference/mergedInterfacesWithInheritedPrivates2.js b/tests/baselines/reference/mergedInterfacesWithInheritedPrivates2.js index 389bbfa63dd..26cd3c8bf7c 100644 --- a/tests/baselines/reference/mergedInterfacesWithInheritedPrivates2.js +++ b/tests/baselines/reference/mergedInterfacesWithInheritedPrivates2.js @@ -35,8 +35,7 @@ var r2 = a.w; // error var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var C = (function () { function C() { diff --git a/tests/baselines/reference/mergedInterfacesWithInheritedPrivates3.js b/tests/baselines/reference/mergedInterfacesWithInheritedPrivates3.js index d088aab3d3c..530595d54f6 100644 --- a/tests/baselines/reference/mergedInterfacesWithInheritedPrivates3.js +++ b/tests/baselines/reference/mergedInterfacesWithInheritedPrivates3.js @@ -42,8 +42,7 @@ module M { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var C = (function () { function C() { diff --git a/tests/baselines/reference/missingDecoratorType.errors.txt b/tests/baselines/reference/missingDecoratorType.errors.txt index 91b54fde54a..f2af7d49b57 100644 --- a/tests/baselines/reference/missingDecoratorType.errors.txt +++ b/tests/baselines/reference/missingDecoratorType.errors.txt @@ -2,16 +2,6 @@ error TS2318: Cannot find global type 'TypedPropertyDescriptor'. !!! error TS2318: Cannot find global type 'TypedPropertyDescriptor'. -==== tests/cases/conformance/decorators/b.ts (0 errors) ==== - /// - declare function dec(t, k, d); - - class C { - @dec - method() {} - } - - ==== tests/cases/conformance/decorators/a.ts (0 errors) ==== interface Object { } @@ -22,4 +12,13 @@ error TS2318: Cannot find global type 'TypedPropertyDescriptor'. interface Function { } interface RegExp { } interface IArguments { } + +==== tests/cases/conformance/decorators/b.ts (0 errors) ==== + declare function dec(t, k, d); + + class C { + @dec + method() {} + } + \ No newline at end of file diff --git a/tests/baselines/reference/missingDecoratorType.js b/tests/baselines/reference/missingDecoratorType.js index e65ca7dc341..ad6be3a646e 100644 --- a/tests/baselines/reference/missingDecoratorType.js +++ b/tests/baselines/reference/missingDecoratorType.js @@ -12,7 +12,6 @@ interface RegExp { } interface IArguments { } //// [b.ts] -/// declare function dec(t, k, d); class C { @@ -32,7 +31,6 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key, case 4: return decorators.reduceRight(function(o, d) { return (d && d(target, key, o)) || o; }, desc); } }; -/// var C = (function () { function C() { } diff --git a/tests/baselines/reference/moduleAsBaseType.js b/tests/baselines/reference/moduleAsBaseType.js index c2246be8795..7e2af06480d 100644 --- a/tests/baselines/reference/moduleAsBaseType.js +++ b/tests/baselines/reference/moduleAsBaseType.js @@ -8,8 +8,7 @@ class C2 implements M { } var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var C = (function (_super) { __extends(C, _super); diff --git a/tests/baselines/reference/moduleElementsInWrongContext.errors.txt b/tests/baselines/reference/moduleElementsInWrongContext.errors.txt new file mode 100644 index 00000000000..4ab5c5b42c0 --- /dev/null +++ b/tests/baselines/reference/moduleElementsInWrongContext.errors.txt @@ -0,0 +1,87 @@ +tests/cases/compiler/moduleElementsInWrongContext.ts(2,5): error TS1235: A namespace declaration is only allowed in a namespace or module. +tests/cases/compiler/moduleElementsInWrongContext.ts(3,5): error TS1235: A namespace declaration is only allowed in a namespace or module. +tests/cases/compiler/moduleElementsInWrongContext.ts(7,5): error TS1235: A namespace declaration is only allowed in a namespace or module. +tests/cases/compiler/moduleElementsInWrongContext.ts(9,5): error TS1234: An ambient module declaration is only allowed at the top level in a file. +tests/cases/compiler/moduleElementsInWrongContext.ts(13,5): error TS1231: An export assignment can only be used in a module. +tests/cases/compiler/moduleElementsInWrongContext.ts(17,5): error TS1233: An export declaration can only be used in a module. +tests/cases/compiler/moduleElementsInWrongContext.ts(18,5): error TS1233: An export declaration can only be used in a module. +tests/cases/compiler/moduleElementsInWrongContext.ts(19,5): error TS1233: An export declaration can only be used in a module. +tests/cases/compiler/moduleElementsInWrongContext.ts(19,14): error TS2305: Module '"ambient"' has no exported member 'baz'. +tests/cases/compiler/moduleElementsInWrongContext.ts(20,5): error TS1231: An export assignment can only be used in a module. +tests/cases/compiler/moduleElementsInWrongContext.ts(21,5): error TS1184: Modifiers cannot appear here. +tests/cases/compiler/moduleElementsInWrongContext.ts(22,5): error TS1184: Modifiers cannot appear here. +tests/cases/compiler/moduleElementsInWrongContext.ts(23,5): error TS1232: An import declaration can only be used in a namespace or module. +tests/cases/compiler/moduleElementsInWrongContext.ts(24,5): error TS1232: An import declaration can only be used in a namespace or module. +tests/cases/compiler/moduleElementsInWrongContext.ts(25,5): error TS1232: An import declaration can only be used in a namespace or module. +tests/cases/compiler/moduleElementsInWrongContext.ts(26,5): error TS1232: An import declaration can only be used in a namespace or module. +tests/cases/compiler/moduleElementsInWrongContext.ts(27,5): error TS1232: An import declaration can only be used in a namespace or module. +tests/cases/compiler/moduleElementsInWrongContext.ts(28,5): error TS1232: An import declaration can only be used in a namespace or module. + + +==== tests/cases/compiler/moduleElementsInWrongContext.ts (18 errors) ==== + { + module M { } + ~~~~~~ +!!! error TS1235: A namespace declaration is only allowed in a namespace or module. + export namespace N { + ~~~~~~ +!!! error TS1235: A namespace declaration is only allowed in a namespace or module. + export interface I { } + } + + namespace Q.K { } + ~~~~~~~~~ +!!! error TS1235: A namespace declaration is only allowed in a namespace or module. + + declare module "ambient" { + ~~~~~~~ +!!! error TS1234: An ambient module declaration is only allowed at the top level in a file. + + } + + export = M; + ~~~~~~ +!!! error TS1231: An export assignment can only be used in a module. + + var v; + function foo() { } + export * from "ambient"; + ~~~~~~ +!!! error TS1233: An export declaration can only be used in a module. + export { foo }; + ~~~~~~ +!!! error TS1233: An export declaration can only be used in a module. + export { baz as b } from "ambient"; + ~~~~~~ +!!! error TS1233: An export declaration can only be used in a module. + ~~~ +!!! error TS2305: Module '"ambient"' has no exported member 'baz'. + export default v; + ~~~~~~ +!!! error TS1231: An export assignment can only be used in a module. + export default class C { } + ~~~~~~ +!!! error TS1184: Modifiers cannot appear here. + export function bee() { } + ~~~~~~ +!!! error TS1184: Modifiers cannot appear here. + import I = M; + ~~~~~~ +!!! error TS1232: An import declaration can only be used in a namespace or module. + import I2 = require("foo"); + ~~~~~~ +!!! error TS1232: An import declaration can only be used in a namespace or module. + import * as Foo from "ambient"; + ~~~~~~ +!!! error TS1232: An import declaration can only be used in a namespace or module. + import bar from "ambient"; + ~~~~~~ +!!! error TS1232: An import declaration can only be used in a namespace or module. + import { baz } from "ambient"; + ~~~~~~ +!!! error TS1232: An import declaration can only be used in a namespace or module. + import "ambient"; + ~~~~~~ +!!! error TS1232: An import declaration can only be used in a namespace or module. + } + \ No newline at end of file diff --git a/tests/baselines/reference/moduleElementsInWrongContext.js b/tests/baselines/reference/moduleElementsInWrongContext.js new file mode 100644 index 00000000000..635da02bdf2 --- /dev/null +++ b/tests/baselines/reference/moduleElementsInWrongContext.js @@ -0,0 +1,47 @@ +//// [moduleElementsInWrongContext.ts] +{ + module M { } + export namespace N { + export interface I { } + } + + namespace Q.K { } + + declare module "ambient" { + + } + + export = M; + + var v; + function foo() { } + export * from "ambient"; + export { foo }; + export { baz as b } from "ambient"; + export default v; + export default class C { } + export function bee() { } + import I = M; + import I2 = require("foo"); + import * as Foo from "ambient"; + import bar from "ambient"; + import { baz } from "ambient"; + import "ambient"; +} + + +//// [moduleElementsInWrongContext.js] +{ + var v; + function foo() { } + __export(require("ambient")); + exports["default"] = v; + var C = (function () { + function C() { + } + return C; + })(); + exports["default"] = C; + function bee() { } + exports.bee = bee; +} diff --git a/tests/baselines/reference/moduleElementsInWrongContext2.errors.txt b/tests/baselines/reference/moduleElementsInWrongContext2.errors.txt new file mode 100644 index 00000000000..d6611e71831 --- /dev/null +++ b/tests/baselines/reference/moduleElementsInWrongContext2.errors.txt @@ -0,0 +1,87 @@ +tests/cases/compiler/moduleElementsInWrongContext2.ts(2,5): error TS1235: A namespace declaration is only allowed in a namespace or module. +tests/cases/compiler/moduleElementsInWrongContext2.ts(3,5): error TS1235: A namespace declaration is only allowed in a namespace or module. +tests/cases/compiler/moduleElementsInWrongContext2.ts(7,5): error TS1235: A namespace declaration is only allowed in a namespace or module. +tests/cases/compiler/moduleElementsInWrongContext2.ts(9,5): error TS1234: An ambient module declaration is only allowed at the top level in a file. +tests/cases/compiler/moduleElementsInWrongContext2.ts(13,5): error TS1231: An export assignment can only be used in a module. +tests/cases/compiler/moduleElementsInWrongContext2.ts(17,5): error TS1233: An export declaration can only be used in a module. +tests/cases/compiler/moduleElementsInWrongContext2.ts(18,5): error TS1233: An export declaration can only be used in a module. +tests/cases/compiler/moduleElementsInWrongContext2.ts(19,5): error TS1233: An export declaration can only be used in a module. +tests/cases/compiler/moduleElementsInWrongContext2.ts(19,30): error TS2307: Cannot find module 'ambient'. +tests/cases/compiler/moduleElementsInWrongContext2.ts(20,5): error TS1231: An export assignment can only be used in a module. +tests/cases/compiler/moduleElementsInWrongContext2.ts(21,5): error TS1184: Modifiers cannot appear here. +tests/cases/compiler/moduleElementsInWrongContext2.ts(22,5): error TS1184: Modifiers cannot appear here. +tests/cases/compiler/moduleElementsInWrongContext2.ts(23,5): error TS1232: An import declaration can only be used in a namespace or module. +tests/cases/compiler/moduleElementsInWrongContext2.ts(24,5): error TS1232: An import declaration can only be used in a namespace or module. +tests/cases/compiler/moduleElementsInWrongContext2.ts(25,5): error TS1232: An import declaration can only be used in a namespace or module. +tests/cases/compiler/moduleElementsInWrongContext2.ts(26,5): error TS1232: An import declaration can only be used in a namespace or module. +tests/cases/compiler/moduleElementsInWrongContext2.ts(27,5): error TS1232: An import declaration can only be used in a namespace or module. +tests/cases/compiler/moduleElementsInWrongContext2.ts(28,5): error TS1232: An import declaration can only be used in a namespace or module. + + +==== tests/cases/compiler/moduleElementsInWrongContext2.ts (18 errors) ==== + function blah () { + module M { } + ~~~~~~ +!!! error TS1235: A namespace declaration is only allowed in a namespace or module. + export namespace N { + ~~~~~~ +!!! error TS1235: A namespace declaration is only allowed in a namespace or module. + export interface I { } + } + + namespace Q.K { } + ~~~~~~~~~ +!!! error TS1235: A namespace declaration is only allowed in a namespace or module. + + declare module "ambient" { + ~~~~~~~ +!!! error TS1234: An ambient module declaration is only allowed at the top level in a file. + + } + + export = M; + ~~~~~~ +!!! error TS1231: An export assignment can only be used in a module. + + var v; + function foo() { } + export * from "ambient"; + ~~~~~~ +!!! error TS1233: An export declaration can only be used in a module. + export { foo }; + ~~~~~~ +!!! error TS1233: An export declaration can only be used in a module. + export { baz as b } from "ambient"; + ~~~~~~ +!!! error TS1233: An export declaration can only be used in a module. + ~~~~~~~~~ +!!! error TS2307: Cannot find module 'ambient'. + export default v; + ~~~~~~ +!!! error TS1231: An export assignment can only be used in a module. + export default class C { } + ~~~~~~ +!!! error TS1184: Modifiers cannot appear here. + export function bee() { } + ~~~~~~ +!!! error TS1184: Modifiers cannot appear here. + import I = M; + ~~~~~~ +!!! error TS1232: An import declaration can only be used in a namespace or module. + import I2 = require("foo"); + ~~~~~~ +!!! error TS1232: An import declaration can only be used in a namespace or module. + import * as Foo from "ambient"; + ~~~~~~ +!!! error TS1232: An import declaration can only be used in a namespace or module. + import bar from "ambient"; + ~~~~~~ +!!! error TS1232: An import declaration can only be used in a namespace or module. + import { baz } from "ambient"; + ~~~~~~ +!!! error TS1232: An import declaration can only be used in a namespace or module. + import "ambient"; + ~~~~~~ +!!! error TS1232: An import declaration can only be used in a namespace or module. + } + \ No newline at end of file diff --git a/tests/baselines/reference/moduleElementsInWrongContext2.js b/tests/baselines/reference/moduleElementsInWrongContext2.js new file mode 100644 index 00000000000..fdf1222e549 --- /dev/null +++ b/tests/baselines/reference/moduleElementsInWrongContext2.js @@ -0,0 +1,47 @@ +//// [moduleElementsInWrongContext2.ts] +function blah () { + module M { } + export namespace N { + export interface I { } + } + + namespace Q.K { } + + declare module "ambient" { + + } + + export = M; + + var v; + function foo() { } + export * from "ambient"; + export { foo }; + export { baz as b } from "ambient"; + export default v; + export default class C { } + export function bee() { } + import I = M; + import I2 = require("foo"); + import * as Foo from "ambient"; + import bar from "ambient"; + import { baz } from "ambient"; + import "ambient"; +} + + +//// [moduleElementsInWrongContext2.js] +function blah() { + var v; + function foo() { } + __export(require("ambient")); + exports["default"] = v; + var C = (function () { + function C() { + } + return C; + })(); + exports["default"] = C; + function bee() { } + exports.bee = bee; +} diff --git a/tests/baselines/reference/moduleElementsInWrongContext3.errors.txt b/tests/baselines/reference/moduleElementsInWrongContext3.errors.txt new file mode 100644 index 00000000000..f5361319b68 --- /dev/null +++ b/tests/baselines/reference/moduleElementsInWrongContext3.errors.txt @@ -0,0 +1,88 @@ +tests/cases/compiler/moduleElementsInWrongContext3.ts(3,9): error TS1235: A namespace declaration is only allowed in a namespace or module. +tests/cases/compiler/moduleElementsInWrongContext3.ts(4,9): error TS1235: A namespace declaration is only allowed in a namespace or module. +tests/cases/compiler/moduleElementsInWrongContext3.ts(8,9): error TS1235: A namespace declaration is only allowed in a namespace or module. +tests/cases/compiler/moduleElementsInWrongContext3.ts(10,9): error TS1234: An ambient module declaration is only allowed at the top level in a file. +tests/cases/compiler/moduleElementsInWrongContext3.ts(14,9): error TS1231: An export assignment can only be used in a module. +tests/cases/compiler/moduleElementsInWrongContext3.ts(18,9): error TS1233: An export declaration can only be used in a module. +tests/cases/compiler/moduleElementsInWrongContext3.ts(19,9): error TS1233: An export declaration can only be used in a module. +tests/cases/compiler/moduleElementsInWrongContext3.ts(20,9): error TS1233: An export declaration can only be used in a module. +tests/cases/compiler/moduleElementsInWrongContext3.ts(20,34): error TS2307: Cannot find module 'ambient'. +tests/cases/compiler/moduleElementsInWrongContext3.ts(21,9): error TS1231: An export assignment can only be used in a module. +tests/cases/compiler/moduleElementsInWrongContext3.ts(22,9): error TS1184: Modifiers cannot appear here. +tests/cases/compiler/moduleElementsInWrongContext3.ts(23,9): error TS1184: Modifiers cannot appear here. +tests/cases/compiler/moduleElementsInWrongContext3.ts(24,9): error TS1232: An import declaration can only be used in a namespace or module. +tests/cases/compiler/moduleElementsInWrongContext3.ts(25,9): error TS1232: An import declaration can only be used in a namespace or module. +tests/cases/compiler/moduleElementsInWrongContext3.ts(26,9): error TS1232: An import declaration can only be used in a namespace or module. +tests/cases/compiler/moduleElementsInWrongContext3.ts(27,9): error TS1232: An import declaration can only be used in a namespace or module. +tests/cases/compiler/moduleElementsInWrongContext3.ts(28,9): error TS1232: An import declaration can only be used in a namespace or module. +tests/cases/compiler/moduleElementsInWrongContext3.ts(29,9): error TS1232: An import declaration can only be used in a namespace or module. + + +==== tests/cases/compiler/moduleElementsInWrongContext3.ts (18 errors) ==== + module P { + { + module M { } + ~~~~~~ +!!! error TS1235: A namespace declaration is only allowed in a namespace or module. + export namespace N { + ~~~~~~ +!!! error TS1235: A namespace declaration is only allowed in a namespace or module. + export interface I { } + } + + namespace Q.K { } + ~~~~~~~~~ +!!! error TS1235: A namespace declaration is only allowed in a namespace or module. + + declare module "ambient" { + ~~~~~~~ +!!! error TS1234: An ambient module declaration is only allowed at the top level in a file. + + } + + export = M; + ~~~~~~ +!!! error TS1231: An export assignment can only be used in a module. + + var v; + function foo() { } + export * from "ambient"; + ~~~~~~ +!!! error TS1233: An export declaration can only be used in a module. + export { foo }; + ~~~~~~ +!!! error TS1233: An export declaration can only be used in a module. + export { baz as b } from "ambient"; + ~~~~~~ +!!! error TS1233: An export declaration can only be used in a module. + ~~~~~~~~~ +!!! error TS2307: Cannot find module 'ambient'. + export default v; + ~~~~~~ +!!! error TS1231: An export assignment can only be used in a module. + export default class C { } + ~~~~~~ +!!! error TS1184: Modifiers cannot appear here. + export function bee() { } + ~~~~~~ +!!! error TS1184: Modifiers cannot appear here. + import I = M; + ~~~~~~ +!!! error TS1232: An import declaration can only be used in a namespace or module. + import I2 = require("foo"); + ~~~~~~ +!!! error TS1232: An import declaration can only be used in a namespace or module. + import * as Foo from "ambient"; + ~~~~~~ +!!! error TS1232: An import declaration can only be used in a namespace or module. + import bar from "ambient"; + ~~~~~~ +!!! error TS1232: An import declaration can only be used in a namespace or module. + import { baz } from "ambient"; + ~~~~~~ +!!! error TS1232: An import declaration can only be used in a namespace or module. + import "ambient"; + ~~~~~~ +!!! error TS1232: An import declaration can only be used in a namespace or module. + } + } \ No newline at end of file diff --git a/tests/baselines/reference/moduleElementsInWrongContext3.js b/tests/baselines/reference/moduleElementsInWrongContext3.js new file mode 100644 index 00000000000..d464d9d31b1 --- /dev/null +++ b/tests/baselines/reference/moduleElementsInWrongContext3.js @@ -0,0 +1,51 @@ +//// [moduleElementsInWrongContext3.ts] +module P { + { + module M { } + export namespace N { + export interface I { } + } + + namespace Q.K { } + + declare module "ambient" { + + } + + export = M; + + var v; + function foo() { } + export * from "ambient"; + export { foo }; + export { baz as b } from "ambient"; + export default v; + export default class C { } + export function bee() { } + import I = M; + import I2 = require("foo"); + import * as Foo from "ambient"; + import bar from "ambient"; + import { baz } from "ambient"; + import "ambient"; + } +} + +//// [moduleElementsInWrongContext3.js] +var P; +(function (P) { + { + var v; + function foo() { } + __export(require("ambient")); + P["default"] = v; + var C = (function () { + function C() { + } + return C; + })(); + exports["default"] = C; + function bee() { } + P.bee = bee; + } +})(P || (P = {})); diff --git a/tests/baselines/reference/moduleImportedForTypeArgumentPosition.js b/tests/baselines/reference/moduleImportedForTypeArgumentPosition.js index e8e08eed26c..9b7449b95ca 100644 --- a/tests/baselines/reference/moduleImportedForTypeArgumentPosition.js +++ b/tests/baselines/reference/moduleImportedForTypeArgumentPosition.js @@ -18,8 +18,7 @@ define(["require", "exports"], function (require, exports) { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; define(["require", "exports"], function (require, exports) { var C1 = (function () { diff --git a/tests/baselines/reference/moduleImportedForTypeArgumentPosition.types b/tests/baselines/reference/moduleImportedForTypeArgumentPosition.types index 0a85e6e0002..d3ef4e4e9ce 100644 --- a/tests/baselines/reference/moduleImportedForTypeArgumentPosition.types +++ b/tests/baselines/reference/moduleImportedForTypeArgumentPosition.types @@ -9,7 +9,7 @@ class C1{ } class Test1 extends C1 { >Test1 : Test1 ->C1 : C1 +>C1 : C1 >M2 : any >M2C : M2.M2C } diff --git a/tests/baselines/reference/moduleWithStatementsOfEveryKind.js b/tests/baselines/reference/moduleWithStatementsOfEveryKind.js index 6c0f625f986..aeffc8d6e5b 100644 --- a/tests/baselines/reference/moduleWithStatementsOfEveryKind.js +++ b/tests/baselines/reference/moduleWithStatementsOfEveryKind.js @@ -62,8 +62,7 @@ module Y { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var A; (function (A_1) { diff --git a/tests/baselines/reference/moduleWithStatementsOfEveryKind.types b/tests/baselines/reference/moduleWithStatementsOfEveryKind.types index 9475d9cfdcb..c6f4be850be 100644 --- a/tests/baselines/reference/moduleWithStatementsOfEveryKind.types +++ b/tests/baselines/reference/moduleWithStatementsOfEveryKind.types @@ -18,7 +18,7 @@ module A { class B extends AA implements I { id: number } >B : B ->AA : AA +>AA : AA >I : I >id : number @@ -106,7 +106,7 @@ module Y { export class B extends AA implements I { id: number } >B : B ->AA : AA +>AA : AA >I : I >id : number diff --git a/tests/baselines/reference/multiLinePropertyAccessAndArrowFunctionIndent1.errors.txt b/tests/baselines/reference/multiLinePropertyAccessAndArrowFunctionIndent1.errors.txt index 14b7769d22f..abf11dc9dba 100644 --- a/tests/baselines/reference/multiLinePropertyAccessAndArrowFunctionIndent1.errors.txt +++ b/tests/baselines/reference/multiLinePropertyAccessAndArrowFunctionIndent1.errors.txt @@ -1,12 +1,15 @@ tests/cases/compiler/multiLinePropertyAccessAndArrowFunctionIndent1.ts(1,1): error TS1108: A 'return' statement can only be used within a function body. +tests/cases/compiler/multiLinePropertyAccessAndArrowFunctionIndent1.ts(1,18): error TS2304: Cannot find name 'role'. tests/cases/compiler/multiLinePropertyAccessAndArrowFunctionIndent1.ts(2,18): error TS2304: Cannot find name 'Role'. tests/cases/compiler/multiLinePropertyAccessAndArrowFunctionIndent1.ts(4,26): error TS2503: Cannot find namespace 'ng'. -==== tests/cases/compiler/multiLinePropertyAccessAndArrowFunctionIndent1.ts (3 errors) ==== +==== tests/cases/compiler/multiLinePropertyAccessAndArrowFunctionIndent1.ts (4 errors) ==== return this.edit(role) ~~~~~~ !!! error TS1108: A 'return' statement can only be used within a function body. + ~~~~ +!!! error TS2304: Cannot find name 'role'. .then((role: Role) => ~~~~ !!! error TS2304: Cannot find name 'Role'. diff --git a/tests/baselines/reference/multipleInheritance.js b/tests/baselines/reference/multipleInheritance.js index ea4a7156df9..901838b584b 100644 --- a/tests/baselines/reference/multipleInheritance.js +++ b/tests/baselines/reference/multipleInheritance.js @@ -42,8 +42,7 @@ class Baad extends Good { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var B1 = (function () { function B1() { diff --git a/tests/baselines/reference/mutuallyRecursiveGenericBaseTypes2.js b/tests/baselines/reference/mutuallyRecursiveGenericBaseTypes2.js index 9b3d6f31291..09f4be0c4e9 100644 --- a/tests/baselines/reference/mutuallyRecursiveGenericBaseTypes2.js +++ b/tests/baselines/reference/mutuallyRecursiveGenericBaseTypes2.js @@ -14,8 +14,7 @@ var test = new foo(); var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var foo = (function () { function foo() { diff --git a/tests/baselines/reference/namespacesDeclaration.js b/tests/baselines/reference/namespacesDeclaration.js new file mode 100644 index 00000000000..7c7cfa84af0 --- /dev/null +++ b/tests/baselines/reference/namespacesDeclaration.js @@ -0,0 +1,22 @@ +//// [namespacesDeclaration.ts] + +module M { + export namespace N { + export module M2 { + export interface I {} + } + } +} + +//// [namespacesDeclaration.js] + + +//// [namespacesDeclaration.d.ts] +declare module M { + namespace N { + module M2 { + interface I { + } + } + } +} diff --git a/tests/baselines/reference/namespacesDeclaration.symbols b/tests/baselines/reference/namespacesDeclaration.symbols new file mode 100644 index 00000000000..1706f212f34 --- /dev/null +++ b/tests/baselines/reference/namespacesDeclaration.symbols @@ -0,0 +1,16 @@ +=== tests/cases/compiler/namespacesDeclaration.ts === + +module M { +>M : Symbol(M, Decl(namespacesDeclaration.ts, 0, 0)) + + export namespace N { +>N : Symbol(N, Decl(namespacesDeclaration.ts, 1, 10)) + + export module M2 { +>M2 : Symbol(M2, Decl(namespacesDeclaration.ts, 2, 23)) + + export interface I {} +>I : Symbol(I, Decl(namespacesDeclaration.ts, 3, 24)) + } + } +} diff --git a/tests/baselines/reference/namespacesDeclaration.types b/tests/baselines/reference/namespacesDeclaration.types new file mode 100644 index 00000000000..944098097fc --- /dev/null +++ b/tests/baselines/reference/namespacesDeclaration.types @@ -0,0 +1,16 @@ +=== tests/cases/compiler/namespacesDeclaration.ts === + +module M { +>M : any + + export namespace N { +>N : any + + export module M2 { +>M2 : any + + export interface I {} +>I : I + } + } +} diff --git a/tests/baselines/reference/noDefaultLib.errors.txt b/tests/baselines/reference/noDefaultLib.errors.txt index b8f42ba7c33..02098950055 100644 --- a/tests/baselines/reference/noDefaultLib.errors.txt +++ b/tests/baselines/reference/noDefaultLib.errors.txt @@ -1,10 +1,10 @@ -error TS2318: Cannot find global type 'IArguments'. error TS2318: Cannot find global type 'Boolean'. +error TS2318: Cannot find global type 'IArguments'. tests/cases/compiler/noDefaultLib.ts(4,11): error TS2317: Global type 'Array' must have 1 type parameter(s). -!!! error TS2318: Cannot find global type 'IArguments'. !!! error TS2318: Cannot find global type 'Boolean'. +!!! error TS2318: Cannot find global type 'IArguments'. ==== tests/cases/compiler/noDefaultLib.ts (1 errors) ==== /// var x; diff --git a/tests/baselines/reference/nonGenericClassExtendingGenericClassWithAny.js b/tests/baselines/reference/nonGenericClassExtendingGenericClassWithAny.js index b687162c154..7cdb702d6ff 100644 --- a/tests/baselines/reference/nonGenericClassExtendingGenericClassWithAny.js +++ b/tests/baselines/reference/nonGenericClassExtendingGenericClassWithAny.js @@ -9,8 +9,7 @@ class Bar extends Foo { } // Valid var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var Foo = (function () { function Foo() { diff --git a/tests/baselines/reference/nonGenericClassExtendingGenericClassWithAny.types b/tests/baselines/reference/nonGenericClassExtendingGenericClassWithAny.types index 177becac643..4eb4c61aedf 100644 --- a/tests/baselines/reference/nonGenericClassExtendingGenericClassWithAny.types +++ b/tests/baselines/reference/nonGenericClassExtendingGenericClassWithAny.types @@ -10,5 +10,5 @@ class Foo { class Bar extends Foo { } // Valid >Bar : Bar ->Foo : Foo +>Foo : Foo diff --git a/tests/baselines/reference/nonGenericTypeReferenceWithTypeArguments.errors.txt b/tests/baselines/reference/nonGenericTypeReferenceWithTypeArguments.errors.txt new file mode 100644 index 00000000000..b227ff0f0ae --- /dev/null +++ b/tests/baselines/reference/nonGenericTypeReferenceWithTypeArguments.errors.txt @@ -0,0 +1,53 @@ +tests/cases/conformance/types/specifyingTypes/typeReferences/nonGenericTypeReferenceWithTypeArguments.ts(7,9): error TS2315: Type 'C' is not generic. +tests/cases/conformance/types/specifyingTypes/typeReferences/nonGenericTypeReferenceWithTypeArguments.ts(8,9): error TS2315: Type 'I' is not generic. +tests/cases/conformance/types/specifyingTypes/typeReferences/nonGenericTypeReferenceWithTypeArguments.ts(9,9): error TS2315: Type 'E' is not generic. +tests/cases/conformance/types/specifyingTypes/typeReferences/nonGenericTypeReferenceWithTypeArguments.ts(10,9): error TS2315: Type 'T' is not generic. +tests/cases/conformance/types/specifyingTypes/typeReferences/nonGenericTypeReferenceWithTypeArguments.ts(17,13): error TS2315: Type 'C' is not generic. +tests/cases/conformance/types/specifyingTypes/typeReferences/nonGenericTypeReferenceWithTypeArguments.ts(18,13): error TS2315: Type 'I' is not generic. +tests/cases/conformance/types/specifyingTypes/typeReferences/nonGenericTypeReferenceWithTypeArguments.ts(19,13): error TS2315: Type 'E' is not generic. +tests/cases/conformance/types/specifyingTypes/typeReferences/nonGenericTypeReferenceWithTypeArguments.ts(20,13): error TS2315: Type 'T' is not generic. +tests/cases/conformance/types/specifyingTypes/typeReferences/nonGenericTypeReferenceWithTypeArguments.ts(21,13): error TS2315: Type 'U' is not generic. + + +==== tests/cases/conformance/types/specifyingTypes/typeReferences/nonGenericTypeReferenceWithTypeArguments.ts (9 errors) ==== + // Check that errors are reported for non-generic types with type arguments + + class C { } + interface I { } + enum E { } + type T = { }; + var v1: C; + ~~~~~~~~~ +!!! error TS2315: Type 'C' is not generic. + var v2: I; + ~~~~~~~~~ +!!! error TS2315: Type 'I' is not generic. + var v3: E; + ~~~~~~~~~ +!!! error TS2315: Type 'E' is not generic. + var v4: T; + ~~~~~~~~~ +!!! error TS2315: Type 'T' is not generic. + + function f() { + class C { } + interface I { } + enum E { } + type T = {}; + var v1: C; + ~~~~~~~~~ +!!! error TS2315: Type 'C' is not generic. + var v2: I; + ~~~~~~~~~ +!!! error TS2315: Type 'I' is not generic. + var v3: E; + ~~~~~~~~~ +!!! error TS2315: Type 'E' is not generic. + var v4: T; + ~~~~~~~~~ +!!! error TS2315: Type 'T' is not generic. + var v5: U; + ~~~~~~~~~ +!!! error TS2315: Type 'U' is not generic. + } + \ No newline at end of file diff --git a/tests/baselines/reference/nonGenericTypeReferenceWithTypeArguments.js b/tests/baselines/reference/nonGenericTypeReferenceWithTypeArguments.js new file mode 100644 index 00000000000..5558cb2fc8b --- /dev/null +++ b/tests/baselines/reference/nonGenericTypeReferenceWithTypeArguments.js @@ -0,0 +1,54 @@ +//// [nonGenericTypeReferenceWithTypeArguments.ts] +// Check that errors are reported for non-generic types with type arguments + +class C { } +interface I { } +enum E { } +type T = { }; +var v1: C; +var v2: I; +var v3: E; +var v4: T; + +function f() { + class C { } + interface I { } + enum E { } + type T = {}; + var v1: C; + var v2: I; + var v3: E; + var v4: T; + var v5: U; +} + + +//// [nonGenericTypeReferenceWithTypeArguments.js] +// Check that errors are reported for non-generic types with type arguments +var C = (function () { + function C() { + } + return C; +})(); +var E; +(function (E) { +})(E || (E = {})); +var v1; +var v2; +var v3; +var v4; +function f() { + var C = (function () { + function C() { + } + return C; + })(); + var E; + (function (E) { + })(E || (E = {})); + var v1; + var v2; + var v3; + var v4; + var v5; +} diff --git a/tests/baselines/reference/numericIndexerConstrainsPropertyDeclarations2.js b/tests/baselines/reference/numericIndexerConstrainsPropertyDeclarations2.js index fe1e4768672..ade000d50ba 100644 --- a/tests/baselines/reference/numericIndexerConstrainsPropertyDeclarations2.js +++ b/tests/baselines/reference/numericIndexerConstrainsPropertyDeclarations2.js @@ -50,8 +50,7 @@ var b: { [x: number]: A } = { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var A = (function () { function A() { diff --git a/tests/baselines/reference/numericIndexerConstraint3.js b/tests/baselines/reference/numericIndexerConstraint3.js index 724db29f557..dc3b6024eee 100644 --- a/tests/baselines/reference/numericIndexerConstraint3.js +++ b/tests/baselines/reference/numericIndexerConstraint3.js @@ -16,8 +16,7 @@ class C { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var A = (function () { function A() { diff --git a/tests/baselines/reference/numericIndexerConstraint4.js b/tests/baselines/reference/numericIndexerConstraint4.js index 404a9394bf7..7509c64eac8 100644 --- a/tests/baselines/reference/numericIndexerConstraint4.js +++ b/tests/baselines/reference/numericIndexerConstraint4.js @@ -15,8 +15,7 @@ var x: { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var A = (function () { function A() { diff --git a/tests/baselines/reference/numericIndexerTyping2.js b/tests/baselines/reference/numericIndexerTyping2.js index c5e91e9dfc0..2e3ba2ce74c 100644 --- a/tests/baselines/reference/numericIndexerTyping2.js +++ b/tests/baselines/reference/numericIndexerTyping2.js @@ -16,8 +16,7 @@ var r2: string = i2[1]; // error: numeric indexer returns the type of the string var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var I = (function () { function I() { diff --git a/tests/baselines/reference/objectCreationOfElementAccessExpression.js b/tests/baselines/reference/objectCreationOfElementAccessExpression.js index 45d56a1d716..05457a559e9 100644 --- a/tests/baselines/reference/objectCreationOfElementAccessExpression.js +++ b/tests/baselines/reference/objectCreationOfElementAccessExpression.js @@ -59,8 +59,7 @@ var foods2: MonsterFood[] = new PetFood[new IceCream('Mint chocolate chip') , Co var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var Food = (function () { function Food(name) { diff --git a/tests/baselines/reference/objectTypeHidingMembersOfExtendedObject.js b/tests/baselines/reference/objectTypeHidingMembersOfExtendedObject.js index 339f6b23f6a..5d30e0faecf 100644 --- a/tests/baselines/reference/objectTypeHidingMembersOfExtendedObject.js +++ b/tests/baselines/reference/objectTypeHidingMembersOfExtendedObject.js @@ -58,8 +58,7 @@ var r4: void = b.valueOf(); var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var A = (function () { function A() { diff --git a/tests/baselines/reference/objectTypesIdentityWithNumericIndexers1.js b/tests/baselines/reference/objectTypesIdentityWithNumericIndexers1.js index 8f6d1706e40..e0f626ae083 100644 --- a/tests/baselines/reference/objectTypesIdentityWithNumericIndexers1.js +++ b/tests/baselines/reference/objectTypesIdentityWithNumericIndexers1.js @@ -127,8 +127,7 @@ function foo16(x: any) { } var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var A = (function () { function A() { diff --git a/tests/baselines/reference/objectTypesIdentityWithNumericIndexers2.js b/tests/baselines/reference/objectTypesIdentityWithNumericIndexers2.js index 8f5b6449a88..f0417a7ca23 100644 --- a/tests/baselines/reference/objectTypesIdentityWithNumericIndexers2.js +++ b/tests/baselines/reference/objectTypesIdentityWithNumericIndexers2.js @@ -130,8 +130,7 @@ function foo16(x: any) { } var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var Base = (function () { function Base() { diff --git a/tests/baselines/reference/objectTypesIdentityWithNumericIndexers3.js b/tests/baselines/reference/objectTypesIdentityWithNumericIndexers3.js index 2fc8c0c946d..e1473790553 100644 --- a/tests/baselines/reference/objectTypesIdentityWithNumericIndexers3.js +++ b/tests/baselines/reference/objectTypesIdentityWithNumericIndexers3.js @@ -127,8 +127,7 @@ function foo16(x: any) { } var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var A = (function () { function A() { diff --git a/tests/baselines/reference/objectTypesIdentityWithPrivates.js b/tests/baselines/reference/objectTypesIdentityWithPrivates.js index a68eba8c6a2..bf4f80da15a 100644 --- a/tests/baselines/reference/objectTypesIdentityWithPrivates.js +++ b/tests/baselines/reference/objectTypesIdentityWithPrivates.js @@ -125,8 +125,7 @@ function foo16(x: any) { } var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var A = (function () { function A() { diff --git a/tests/baselines/reference/objectTypesIdentityWithPrivates2.js b/tests/baselines/reference/objectTypesIdentityWithPrivates2.js index 92aac37ecdb..c8cd12cff30 100644 --- a/tests/baselines/reference/objectTypesIdentityWithPrivates2.js +++ b/tests/baselines/reference/objectTypesIdentityWithPrivates2.js @@ -43,8 +43,7 @@ function foo6(x: any): any { } var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var C = (function () { function C() { diff --git a/tests/baselines/reference/objectTypesIdentityWithPrivates3.js b/tests/baselines/reference/objectTypesIdentityWithPrivates3.js index c202f684895..a812a1fc4bd 100644 --- a/tests/baselines/reference/objectTypesIdentityWithPrivates3.js +++ b/tests/baselines/reference/objectTypesIdentityWithPrivates3.js @@ -29,8 +29,7 @@ var c3: C3; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var C1 = (function () { function C1() { diff --git a/tests/baselines/reference/objectTypesIdentityWithStringIndexers.js b/tests/baselines/reference/objectTypesIdentityWithStringIndexers.js index 98693b4e6ee..9cf9e99cb4b 100644 --- a/tests/baselines/reference/objectTypesIdentityWithStringIndexers.js +++ b/tests/baselines/reference/objectTypesIdentityWithStringIndexers.js @@ -127,8 +127,7 @@ function foo16(x: any) { } var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var A = (function () { function A() { diff --git a/tests/baselines/reference/objectTypesIdentityWithStringIndexers2.js b/tests/baselines/reference/objectTypesIdentityWithStringIndexers2.js index 7e9abbad7e6..84f3d04e7bf 100644 --- a/tests/baselines/reference/objectTypesIdentityWithStringIndexers2.js +++ b/tests/baselines/reference/objectTypesIdentityWithStringIndexers2.js @@ -130,8 +130,7 @@ function foo16(x: any) { } var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var Base = (function () { function Base() { diff --git a/tests/baselines/reference/optionalConstructorArgInSuper.js b/tests/baselines/reference/optionalConstructorArgInSuper.js index 2ac23c39be5..e8b65ea5119 100644 --- a/tests/baselines/reference/optionalConstructorArgInSuper.js +++ b/tests/baselines/reference/optionalConstructorArgInSuper.js @@ -14,8 +14,7 @@ d2.foo(); var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var Base = (function () { function Base(opt) { diff --git a/tests/baselines/reference/optionalParamArgsTest.js b/tests/baselines/reference/optionalParamArgsTest.js index 7538397566a..414f474598d 100644 --- a/tests/baselines/reference/optionalParamArgsTest.js +++ b/tests/baselines/reference/optionalParamArgsTest.js @@ -129,8 +129,7 @@ fnOpt2(1, [2, 3], [1], true); var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; // test basic configurations var C1 = (function () { diff --git a/tests/baselines/reference/optionalParamInOverride.js b/tests/baselines/reference/optionalParamInOverride.js index aa76f41644c..4a72953bdad 100644 --- a/tests/baselines/reference/optionalParamInOverride.js +++ b/tests/baselines/reference/optionalParamInOverride.js @@ -11,8 +11,7 @@ class Y extends Z { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var Z = (function () { function Z() { diff --git a/tests/baselines/reference/overload1.js b/tests/baselines/reference/overload1.js index b308c0e8d83..af3aebde4ee 100644 --- a/tests/baselines/reference/overload1.js +++ b/tests/baselines/reference/overload1.js @@ -43,8 +43,7 @@ var v=x.g; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var O; (function (O) { diff --git a/tests/baselines/reference/overloadOnConstConstraintChecks1.js b/tests/baselines/reference/overloadOnConstConstraintChecks1.js index 4588bef017b..67aa365ee39 100644 --- a/tests/baselines/reference/overloadOnConstConstraintChecks1.js +++ b/tests/baselines/reference/overloadOnConstConstraintChecks1.js @@ -26,8 +26,7 @@ class D implements MyDoc { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var Base = (function () { function Base() { diff --git a/tests/baselines/reference/overloadOnConstConstraintChecks2.js b/tests/baselines/reference/overloadOnConstConstraintChecks2.js index 709f7808ac1..353680bb92e 100644 --- a/tests/baselines/reference/overloadOnConstConstraintChecks2.js +++ b/tests/baselines/reference/overloadOnConstConstraintChecks2.js @@ -15,8 +15,7 @@ function foo(name: any): A { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var A = (function () { function A() { diff --git a/tests/baselines/reference/overloadOnConstConstraintChecks3.js b/tests/baselines/reference/overloadOnConstConstraintChecks3.js index 7104c441938..2debaa589f5 100644 --- a/tests/baselines/reference/overloadOnConstConstraintChecks3.js +++ b/tests/baselines/reference/overloadOnConstConstraintChecks3.js @@ -16,8 +16,7 @@ function foo(name: any): A { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var A = (function () { function A() { diff --git a/tests/baselines/reference/overloadOnConstConstraintChecks4.js b/tests/baselines/reference/overloadOnConstConstraintChecks4.js index 4483b42a941..17ec3779620 100644 --- a/tests/baselines/reference/overloadOnConstConstraintChecks4.js +++ b/tests/baselines/reference/overloadOnConstConstraintChecks4.js @@ -17,8 +17,7 @@ function foo(name: any): Z { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var Z = (function () { function Z() { diff --git a/tests/baselines/reference/overloadOnConstantsInvalidOverload1.js b/tests/baselines/reference/overloadOnConstantsInvalidOverload1.js index efcad011ab5..a8dfcde9ada 100644 --- a/tests/baselines/reference/overloadOnConstantsInvalidOverload1.js +++ b/tests/baselines/reference/overloadOnConstantsInvalidOverload1.js @@ -15,8 +15,7 @@ foo("HI"); var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var Base = (function () { function Base() { diff --git a/tests/baselines/reference/overloadResolution.js b/tests/baselines/reference/overloadResolution.js index d234ea4a69a..287c5ccdb8e 100644 --- a/tests/baselines/reference/overloadResolution.js +++ b/tests/baselines/reference/overloadResolution.js @@ -98,8 +98,7 @@ var s = fn5((n) => n.substr(0)); var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var SomeBase = (function () { function SomeBase() { diff --git a/tests/baselines/reference/overloadResolutionClassConstructors.js b/tests/baselines/reference/overloadResolutionClassConstructors.js index fc7dbd9cebe..14306b7873b 100644 --- a/tests/baselines/reference/overloadResolutionClassConstructors.js +++ b/tests/baselines/reference/overloadResolutionClassConstructors.js @@ -105,8 +105,7 @@ new fn5((n) => n.blah); // Error var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var SomeBase = (function () { function SomeBase() { diff --git a/tests/baselines/reference/overloadResolutionConstructors.js b/tests/baselines/reference/overloadResolutionConstructors.js index b3c2b2ef764..788e6362f86 100644 --- a/tests/baselines/reference/overloadResolutionConstructors.js +++ b/tests/baselines/reference/overloadResolutionConstructors.js @@ -106,8 +106,7 @@ var s = new fn5((n) => n.substr(0)); var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var SomeBase = (function () { function SomeBase() { diff --git a/tests/baselines/reference/overloadingOnConstants1.js b/tests/baselines/reference/overloadingOnConstants1.js index 4274841d60f..bd08f70498d 100644 --- a/tests/baselines/reference/overloadingOnConstants1.js +++ b/tests/baselines/reference/overloadingOnConstants1.js @@ -29,8 +29,7 @@ var htmlSpanElement2: Derived1 = d2.createElement("span"); var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var Base = (function () { function Base() { diff --git a/tests/baselines/reference/overloadingOnConstants2.js b/tests/baselines/reference/overloadingOnConstants2.js index 2414ec4eab2..eaec0054f66 100644 --- a/tests/baselines/reference/overloadingOnConstants2.js +++ b/tests/baselines/reference/overloadingOnConstants2.js @@ -31,8 +31,7 @@ var f: C = bar("um", []); // C var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var C = (function () { function C() { diff --git a/tests/baselines/reference/overloadingStaticFunctionsInFunctions.errors.txt b/tests/baselines/reference/overloadingStaticFunctionsInFunctions.errors.txt index e340e5596cd..ae16b59b095 100644 --- a/tests/baselines/reference/overloadingStaticFunctionsInFunctions.errors.txt +++ b/tests/baselines/reference/overloadingStaticFunctionsInFunctions.errors.txt @@ -1,12 +1,12 @@ tests/cases/compiler/overloadingStaticFunctionsInFunctions.ts(1,14): error TS1005: '(' expected. -tests/cases/compiler/overloadingStaticFunctionsInFunctions.ts(2,3): error TS1129: Statement expected. +tests/cases/compiler/overloadingStaticFunctionsInFunctions.ts(2,3): error TS1128: Declaration or statement expected. tests/cases/compiler/overloadingStaticFunctionsInFunctions.ts(2,10): error TS2304: Cannot find name 'test'. -tests/cases/compiler/overloadingStaticFunctionsInFunctions.ts(3,3): error TS1129: Statement expected. +tests/cases/compiler/overloadingStaticFunctionsInFunctions.ts(3,3): error TS1128: Declaration or statement expected. tests/cases/compiler/overloadingStaticFunctionsInFunctions.ts(3,10): error TS2304: Cannot find name 'test'. tests/cases/compiler/overloadingStaticFunctionsInFunctions.ts(3,15): error TS2304: Cannot find name 'name'. tests/cases/compiler/overloadingStaticFunctionsInFunctions.ts(3,19): error TS1005: ',' expected. tests/cases/compiler/overloadingStaticFunctionsInFunctions.ts(3,20): error TS2304: Cannot find name 'string'. -tests/cases/compiler/overloadingStaticFunctionsInFunctions.ts(4,3): error TS1129: Statement expected. +tests/cases/compiler/overloadingStaticFunctionsInFunctions.ts(4,3): error TS1128: Declaration or statement expected. tests/cases/compiler/overloadingStaticFunctionsInFunctions.ts(4,10): error TS2304: Cannot find name 'test'. tests/cases/compiler/overloadingStaticFunctionsInFunctions.ts(4,15): error TS2304: Cannot find name 'name'. tests/cases/compiler/overloadingStaticFunctionsInFunctions.ts(4,20): error TS1109: Expression expected. @@ -20,12 +20,12 @@ tests/cases/compiler/overloadingStaticFunctionsInFunctions.ts(4,25): error TS100 !!! error TS1005: '(' expected. static test() ~~~~~~ -!!! error TS1129: Statement expected. +!!! error TS1128: Declaration or statement expected. ~~~~ !!! error TS2304: Cannot find name 'test'. static test(name:string) ~~~~~~ -!!! error TS1129: Statement expected. +!!! error TS1128: Declaration or statement expected. ~~~~ !!! error TS2304: Cannot find name 'test'. ~~~~ @@ -36,7 +36,7 @@ tests/cases/compiler/overloadingStaticFunctionsInFunctions.ts(4,25): error TS100 !!! error TS2304: Cannot find name 'string'. static test(name?:any){ } ~~~~~~ -!!! error TS1129: Statement expected. +!!! error TS1128: Declaration or statement expected. ~~~~ !!! error TS2304: Cannot find name 'test'. ~~~~ diff --git a/tests/baselines/reference/overloadresolutionWithConstraintCheckingDeferred.errors.txt b/tests/baselines/reference/overloadresolutionWithConstraintCheckingDeferred.errors.txt index 35837d3233f..45c9f99b691 100644 --- a/tests/baselines/reference/overloadresolutionWithConstraintCheckingDeferred.errors.txt +++ b/tests/baselines/reference/overloadresolutionWithConstraintCheckingDeferred.errors.txt @@ -7,7 +7,7 @@ tests/cases/compiler/overloadresolutionWithConstraintCheckingDeferred.ts(18,27): Types of parameters 'x' and 'x' are incompatible. Type 'D' is not assignable to type 'B'. Property 'x' is missing in type 'D'. -tests/cases/compiler/overloadresolutionWithConstraintCheckingDeferred.ts(19,12): error TS2344: Type 'D' does not satisfy the constraint 'A'. +tests/cases/compiler/overloadresolutionWithConstraintCheckingDeferred.ts(19,14): error TS2344: Type 'D' does not satisfy the constraint 'A'. ==== tests/cases/compiler/overloadresolutionWithConstraintCheckingDeferred.ts (6 errors) ==== @@ -41,7 +41,7 @@ tests/cases/compiler/overloadresolutionWithConstraintCheckingDeferred.ts(19,12): ~~~~~~~~~~~~~~~~~~~~~~ var y: G; // error that D does not satisfy constraint, y is of type G, entire call to foo is an error ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - ~~~~~~~~~~~ + ~~~~~~~~ !!! error TS2344: Type 'D' does not satisfy the constraint 'A'. return y; ~~~~~~~~~~~~~ diff --git a/tests/baselines/reference/overridingPrivateStaticMembers.js b/tests/baselines/reference/overridingPrivateStaticMembers.js index 56ecfec66c0..a155bb1b830 100644 --- a/tests/baselines/reference/overridingPrivateStaticMembers.js +++ b/tests/baselines/reference/overridingPrivateStaticMembers.js @@ -11,8 +11,7 @@ class Derived2 extends Base2 { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var Base2 = (function () { function Base2() { diff --git a/tests/baselines/reference/parseErrorInHeritageClause1.js b/tests/baselines/reference/parseErrorInHeritageClause1.js index 66facdeadf0..b6640b64257 100644 --- a/tests/baselines/reference/parseErrorInHeritageClause1.js +++ b/tests/baselines/reference/parseErrorInHeritageClause1.js @@ -6,8 +6,7 @@ class C extends A # { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var C = (function (_super) { __extends(C, _super); diff --git a/tests/baselines/reference/parser509630.js b/tests/baselines/reference/parser509630.js index 20e00ea01ed..6862eef4a93 100644 --- a/tests/baselines/reference/parser509630.js +++ b/tests/baselines/reference/parser509630.js @@ -10,8 +10,7 @@ class Any extends Type { var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var Type = (function () { function Type() { diff --git a/tests/baselines/reference/parser509698.errors.txt b/tests/baselines/reference/parser509698.errors.txt index 85485dd6501..dfc155dd364 100644 --- a/tests/baselines/reference/parser509698.errors.txt +++ b/tests/baselines/reference/parser509698.errors.txt @@ -1,24 +1,23 @@ -error TS2318: Cannot find global type 'String'. -error TS2318: Cannot find global type 'RegExp'. -error TS2318: Cannot find global type 'Object'. -error TS2318: Cannot find global type 'Number'. -error TS2318: Cannot find global type 'IArguments'. -error TS2318: Cannot find global type 'Function'. -error TS2318: Cannot find global type 'Boolean'. error TS2318: Cannot find global type 'Array'. +error TS2318: Cannot find global type 'Boolean'. +error TS2318: Cannot find global type 'Function'. +error TS2318: Cannot find global type 'IArguments'. +error TS2318: Cannot find global type 'Number'. +error TS2318: Cannot find global type 'Object'. +error TS2318: Cannot find global type 'RegExp'. +error TS2318: Cannot find global type 'String'. -!!! error TS2318: Cannot find global type 'String'. -!!! error TS2318: Cannot find global type 'RegExp'. -!!! error TS2318: Cannot find global type 'Object'. -!!! error TS2318: Cannot find global type 'Number'. -!!! error TS2318: Cannot find global type 'IArguments'. -!!! error TS2318: Cannot find global type 'Function'. -!!! error TS2318: Cannot find global type 'Boolean'. !!! error TS2318: Cannot find global type 'Array'. +!!! error TS2318: Cannot find global type 'Boolean'. +!!! error TS2318: Cannot find global type 'Function'. +!!! error TS2318: Cannot find global type 'IArguments'. +!!! error TS2318: Cannot find global type 'Number'. +!!! error TS2318: Cannot find global type 'Object'. +!!! error TS2318: Cannot find global type 'RegExp'. +!!! error TS2318: Cannot find global type 'String'. ==== tests/cases/conformance/parser/ecmascript5/RegressionTests/parser509698.ts (0 errors) ==== ///